Skip to content

Instantly share code, notes, and snippets.

@winterjung
Created August 22, 2019 12:26
Show Gist options
  • Save winterjung/deaae41080b0a2af59f2b8850b506b39 to your computer and use it in GitHub Desktop.
Save winterjung/deaae41080b0a2af59f2b8850b506b39 to your computer and use it in GitHub Desktop.
PyCon 2019 Banksalad event code
from itertools import permutations
def permutate(cards, n, func):
for p in permutations(cards, n):
try:
yield eval(func(p)), p
except Exception as e:
pass
def only_numbers(result):
value, p = result
return isinstance(value, (int, float))
def calc(cards, n=None, pre_format=None):
if n is None:
n = len(cards)
if pre_format is None:
pre_format = '{}' * n
func = lambda p: pre_format.format(*p)
seq = list(filter(only_numbers, permutate(cards, n, func)))
if not seq:
print('Cannot calculate!')
return
for m_func in (min, max):
value, p = m_func(seq)
print(func(p), '→', value)
available = sorted(set(v for v, _ in seq))
print('available:', available)
from calculator import calc
if __name__ == '__main__':
cards = ['<', '>', '10', '30', '50', '70', '90', 'i', '==']
pre_format = 'sum([int(i {} {}) for i in range({}, {})])'
calc(cards, n=4, pre_format=pre_format)
cards = ['0', '0.1', '0.5', '1', '2', '3', '4', 'x', 'y']
pre_format = '{} ** len(str(sum({} for _ in range({}))))'
calc(cards, n=3, pre_format=pre_format)
cards = ['bin', '4', '"10101"', '2', '16', '8', '"0xff"', '"0o76"', '0']
pre_format = 'int({}, {})'
calc(cards, n=2, pre_format=pre_format)
cards = ['2', '3', '4', '*', '*', '"1"', '"2"', '"3"', '"4"']
calc(cards, n=5)
cards = ['3', '5', '*', 'sum', 'range']
pre_format = '{}(x{}{} for x in {}({}))'
calc(cards, pre_format=pre_format)
cards = ['ord', 'min', 'len', '"banksalad"', '"pycon"', '*']
pre_format = '{}({}({})){}{}({})'
calc(cards, pre_format=pre_format)
cards = ['sum', 'range', '+', '*', '2', '4', '8']
pre_format = '-pow({}({}({})), {})'
calc(cards, n=4, pre_format=pre_format)
cards = ['+', '-', '*', '/', '7', '6', '5', '4', 'None']
calc(cards, n=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment