This commit is contained in:
kejaro committed 2026-10-07 12:31:50 +01:00
1 parent d0ff21db2e
commit ea974f6704
18 files changed
+535

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
from collections import Counter
import urllib.request
def load_dictionary():
"""Download and return a clean set of valid English words."""
url = "https://raw.githubusercontent.com/raun/Scrabble/master/words.txt"
with urllib.request.urlopen(url) as response:
words = response.read().decode("utf-8").splitlines()
# Filter out proper nouns/short words and normalize to lowercase
return [
word.strip().lower()
for word in words
if word.isalpha() and 2 <= len(word) <= 9
]
def solve_countdown(letters, dictionary):
"""Find the longest valid words that can be formed from the input letters."""
letters_count = Counter(letters.lower())
valid_words = []
for word in dictionary:
# Check if word letter frequencies fit within the available letters
if not (Counter(word) - letters_count):
valid_words.append(word)
# Sort by word length (descending), then alphabetically
valid_words.sort(key=lambda w: (-len(w), w))
return valid_words
if __name__ == "__main__":
print("Loading word list...")
dictionary = load_dictionary()
rack = input("\nEnter your letters (e.g., 'mdaisuteo'): ").strip()
matches = solve_countdown(rack, dictionary)
if not matches:
print("No valid words found.")
else:
max_len = len(matches[0])
print(f"\nLongest word length: {max_len} letters")
print("--- Top Matches ---")
# Group and display top results by length
current_len = 0
for word in matches[:20]: # Show top 20 matches
if len(word) != current_len:
current_len = len(word)
print(f"\n{current_len}-letter words:")
print(f" • {word}")
+173
View File
@@ -0,0 +1,173 @@
import sys
import threading
import urllib.request
from collections import Counter
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import GLib, Gtk
# --- Core Countdown Logic ---
def fetch_dictionary():
"""Download and filter valid English words."""
url = "https://raw.githubusercontent.com/raun/Scrabble/master/words.txt"
try:
with urllib.request.urlopen(url, timeout=10) as response:
words = response.read().decode("utf-8").splitlines()
return [
w.strip().lower()
for w in words
if w.isalpha() and 2 <= len(w) <= 9
]
except Exception as e:
print(f"Error fetching dictionary: {e}")
return []
def solve_countdown(letters, dictionary):
"""Find and return matching words sorted by length (descending)."""
letters_count = Counter(letters.lower())
valid_words = []
for word in dictionary:
if not (Counter(word) - letters_count):
valid_words.append(word)
valid_words.sort(key=lambda w: (-len(w), w))
return valid_words
# --- GTK 4 Application Window ---
class CountdownWindow(Gtk.ApplicationWindow):
def __init__(self, **kwargs):
super().__init__(**kwargs, title="Countdown Solver")
self.set_default_size(480, 550)
self.dictionary = []
# --- Main Layout Box ---
main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
main_box.set_margin_top(16)
main_box.set_margin_bottom(16)
main_box.set_margin_start(16)
main_box.set_margin_end(16)
self.set_child(main_box)
# --- Input Section ---
input_box = Gtk.Box(
orientation=Gtk.Orientation.HORIZONTAL, spacing=8
)
self.entry = Gtk.Entry()
self.entry.set_placeholder_text("Enter letters (e.g. mdaisuteo)...")
self.entry.set_hexpand(True)
self.entry.connect("activate", self.on_solve_clicked) # Trigger on Enter
input_box.append(self.entry)
self.solve_button = Gtk.Button(label="Solve")
self.solve_button.connect("clicked", self.on_solve_clicked)
self.solve_button.set_sensitive(False) # Disabled until dictionary loads
input_box.append(self.solve_button)
main_box.append(input_box)
# --- Status / Info Label ---
self.status_label = Gtk.Label(
label="Downloading word list in background..."
)
self.status_label.set_xalign(0)
main_box.append(self.status_label)
# --- Results List Box in Scrolled Window ---
scrolled = Gtk.ScrolledWindow()
scrolled.set_vexpand(True)
self.list_box = Gtk.ListBox()
self.list_box.set_selection_mode(Gtk.SelectionMode.NONE)
scrolled.set_child(self.list_box)
main_box.append(scrolled)
# --- Load Dictionary Asynchronously ---
threading.Thread(target=self._load_dictionary_thread, daemon=True).start()
def _load_dictionary_thread(self):
"""Fetch dictionary off the main thread."""
words = fetch_dictionary()
# Schedule GUI updates on the main GTK thread
GLib.idle_add(self._on_dictionary_loaded, words)
def _on_dictionary_loaded(self, words):
"""Update UI state once dictionary is ready."""
self.dictionary = words
if words:
self.status_label.set_text(
f"Dictionary loaded ({len(words):,} words). Ready!"
)
self.solve_button.set_sensitive(True)
else:
self.status_label.set_text("Failed to load dictionary. Check connection.")
def on_solve_clicked(self, widget):
"""Handle solve trigger."""
letters = self.entry.get_text().strip()
if not letters or not self.dictionary:
return
# Clear existing result rows
while child := self.list_box.get_first_child():
self.list_box.remove(child)
matches = solve_countdown(letters, self.dictionary)
if not matches:
self.status_label.set_text("No valid words found.")
return
max_len = len(matches[0])
self.status_label.set_text(
f"Found {len(matches)} words (Longest: {max_len} letters)"
)
current_len = 0
for word in matches:
word_len = len(word)
# Insert section header row when length changes
if word_len != current_len:
current_len = word_len
header_label = Gtk.Label()
header_label.set_markup(
f"<b>{current_len}-Letter Words</b>"
)
header_label.set_xalign(0)
header_label.set_margin_top(8)
header_label.set_margin_bottom(4)
self.list_box.append(header_label)
# Word row
row_label = Gtk.Label(label=f" • {word}")
row_label.set_xalign(0)
row_label.set_margin_start(8)
self.list_box.append(row_label)
# --- GTK Application Entry Point ---
class CountdownApp(Gtk.Application):
def __init__(self):
super().__init__(application_id="org.countdown.solver")
def do_activate(self):
win = self.props.active_window
if not win:
win = CountdownWindow(application=self)
win.present()
if __name__ == "__main__":
app = CountdownApp()
app.run(sys.argv)
+90
View File
@@ -0,0 +1,90 @@
import itertools
def solve_countdown(numbers, target):
"""
Solves the Countdown numbers game.
Returns (closest_target, math_expression_string).
"""
# Memoization dictionary: maps frozen sets of numbers to expressions
# Structure: { numbers_tuple: { value: expression_string } }
memo = {}
def get_all_results(nums):
# Sort to ensure consistent dictionary key representation
key = tuple(sorted(nums))
if key in memo:
return memo[key]
results = {}
# Base case: single number
if len(nums) == 1:
results[nums[0]] = str(nums[0])
memo[key] = results
return results
# Try all partitions of the list into two non-empty subsets
n = len(nums)
for i in range(1, n):
for left_indices in itertools.combinations(range(n), i):
right_indices = [j for j in range(n) if j not in left_indices]
left_nums = [nums[j] for j in left_indices]
right_nums = [nums[j] for j in right_indices]
left_results = get_all_results(left_nums)
right_results = get_all_results(right_nums)
for l_val, l_expr in left_results.items():
for r_val, r_expr in right_results.items():
# Addition
val = l_val + r_val
if val not in results:
results[val] = f"({l_expr} + {r_expr})"
# Subtraction (Countdown rules: results must be positive integers)
if l_val > r_val:
val = l_val - r_val
if val not in results:
results[val] = f"({l_expr} - {r_expr})"
# Multiplication
if l_val > 1 and r_val > 1: # Avoid trivial x * 1
val = l_val * r_val
if val not in results:
results[val] = f"({l_expr} * {r_expr})"
# Division (Countdown rules: exact integer division only)
if r_val > 1 and l_val % r_val == 0:
val = l_val // r_val
if val not in results:
results[val] = f"({l_expr} / {r_expr})"
memo[key] = results
return results
# Evaluate all valid combinations across all possible subset sizes (1 to len(numbers))
all_possible = {}
for r in range(1, len(numbers) + 1):
for sub in itertools.combinations(numbers, r):
res = get_all_results(sub)
all_possible.update(res)
# Check for exact match
if target in all_possible:
return target, all_possible[target]
# Find closest match if exact target isn't reachable
closest_val = min(all_possible.keys(), key=lambda x: abs(x - target))
return closest_val, all_possible[closest_val]
# --- Example Usage ---
if __name__ == "__main__":
nums = [6, 7, 6, 8, 6, 3]
target = 854
result_val, expression = solve_countdown(nums, target)
print(f"Target: {target}")
print(f"Reached: {result_val}")
print(f"Solution: {expression}")