Skip to content

Instantly share code, notes, and snippets.

@bryanwieger
Last active June 2, 2022 03:24
Show Gist options
  • Save bryanwieger/8d783c466de4c18d50584ad0fade4f38 to your computer and use it in GitHub Desktop.
Save bryanwieger/8d783c466de4c18d50584ad0fade4f38 to your computer and use it in GitHub Desktop.
# you'll need a .txt file of english words.
# you can find one here https://github.com/dwyl/english-words/blob/master/words_alpha.txt
# inspiration 8 out of 10 cats does countdown https://youtu.be/l9MXCjPwDro
from enum import Enum, auto
SYMBOL = "+*-/"
cache = set()
def symbol(arr, target, path):
arr.sort()
key = str(arr)+str(target)
if key in cache:
return None
cache.add(key)
if target in arr:
return path
if len(arr) <= 1:
return None
for sym in SYMBOL:
tmp = item(arr, target, sym, path+"\n")
if tmp is not None:
return tmp
def op(sym,a,b):
if sym == "+":
return a+b
if sym == "-":
return a-b
if sym == "*":
return a*b
if sym == "/":
if b == 0:
return None
return a/b
raise Exception('Error occured at {function} with {p1,p2,p3}'.format(function='op',p1=sym,p2=a,p3=b))
def item(arr, target, sym, path):
if target in arr:
return path
if len(arr) <= 1:
return None
n = len(arr)
for i in range(n):
ith = arr[i]
for j in range(n):
if i == j:
continue
jth = arr[j]
val = op(sym,ith,jth)
if val is None:
continue
newArr = [arr[k] for k in range(n) if not (k==j or k==i)]
newArr.append(val)
tmp = symbol(newArr, target, '{} {} {} {} = {}'.format(path,ith,sym,jth,val))
if tmp is not None:
return tmp
def countdown(arr, target):
cache.clear()
print(symbol(arr, target, ""))
english = open("english_words.txt", "r").readlines()
english = [i.strip().lower() for i in english]
english_words = dict()
for word in english:
key = ''.join(sorted(word))
if key not in english_words:
english_words[key] = [word]
else:
english_words[key].append(word)
def countdown_word(letters):
q = [letters]
while len(q) != 0:
word = q.pop(0)
word = ''.join(sorted(word))
if word in english_words:
return english_words[word]
for i in range(len(word)):
q.append(word[:i] + word[i+1:])
return ""
countdown([10,5,1], 3)
countdown([100,4,5,4,7,10], 579)
countdown_word("iwadshong")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment