Telegram solver bot for 24 cards game
Generated by AI for fun.
```
#!/usr/bin/env python3
import os
from itertools import permutations, product
from telegram.ext import Application, CommandHandler, MessageHandler, filters
def fmt(n):
return str(int(n)) if n == int(n) else str(n)
def solve(cards):
try:
vals = [
[float(int(c) or 10)] if c.isdigit() else [1.0, 11.0] if c == "a" else []
for c in cards.lower()
]
if any(not v for v in vals) or len(vals) != 4:
return set()
except:
return set()
sols = set()
ops = [
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b if b else None),
]
for v in product(*vals):
for p in permutations(v):
a, b, c, d = p
A, B, C, D = fmt(a), fmt(b), fmt(c), fmt(d)
for op1, op2, op3 in product(ops, repeat=3):
s1, f1 = op1
s2, f2 = op2
s3, f3 = op3
exprs = [
(lambda: f3(f2(f1(a, b), c), d), f"(({A}{s1}{B}){s2}{C}){s3}{D}"),
(lambda: f3(f1(a, f2(b, c)), d), f"({A}{s1}({B}{s2}{C})){s3}{D}"),
(lambda: f2(f1(a, b), f3(c, d)), f"({A}{s1}{B}){s2}({C}{s3}{D})"),
(lambda: f1(a, f3(f2(b, c), d)), f"{A}{s1}(({B}{s2}{C}){s3}{D})"),
(lambda: f1(a, f2(b, f3(c, d))), f"{A}{s1}({B}{s2}({C}{s3}{D}))"),
]
for calc, expr in exprs:
try:
r = calc()
if r is not None and abs(r - 24) < 1e-9:
sols.add(expr)
except:
pass
return sols
last_cards = {}
async def start(u, _):
await u.message.reply_text("Send 4 cards (1-9, a=ace, 0=10)")
async def msg(u, _):
text = u.message.text.strip()
uid = u.effective_user.id
if text == "/all":
cards = last_cards.get(uid, "")
if not cards:
await u.message.reply_text("Send cards first")
return
sols = solve(cards)
await u.message.reply_text(
"\n".join(sorted(sols)[:20]) if sols else "No solution"
)
return
if len(text) != 4:
await u.message.reply_text("Send exactly 4 cards")
return
last_cards[uid] = text
sols = solve(text)
if sols:
await u.message.reply_text(f"Found {len(sols)}\n{min(sols, key=len)}=24")
else:
await u.message.reply_text("No solution")
app = Application.builder().token(os.getenv("TELEGRAM_BOT_TOKEN")).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT, msg))
app.run_polling()
```
Created: 2026-04-03 13:28:06, Updated: 2026-04-03 13:28:06, ID: ac2fdddd-342b-47b7-bfba-efd99278cba4