Skip to content

Instantly share code, notes, and snippets.

@jyn514
Created August 23, 2020 16:20
Show Gist options
  • Save jyn514/7e74c0e2c70a02035c4ddeeb66698837 to your computer and use it in GitHub Desktop.
Save jyn514/7e74c0e2c70a02035c4ddeeb66698837 to your computer and use it in GitHub Desktop.
import sys
from collections import defaultdict, Counter
def lexer():
for line in sys.stdin:
for token in line.split():
yield token
def lookup(var, scope):
while scope.get(var):
var = scope[var]
return var
def peek(stack, default):
if stack:
return stack[-1]
return default
def subsumes(term, other):
# whether subsequences of the term are wholly contained in the other
# 'kmn' in 'kmmn' is true
for key, value in term.items():
if value > other[key]:
return False
return True
def should_print(term, terms):
'''Given a term, return whether it should be printed
For example, ('nn', ['nnn', 'nn']) should not print 'nn'.
Additionally, ('kmn', ['kmmn', 'nn']) should not print.'''
if not term:
return False
print("term=", term, file=sys.stderr)
return not any(map(lambda other: term != other and subsumes(term, other), terms))
l = lexer()
complexity = defaultdict(lambda: '')
scope = {}
stack = []
outputs = set()
for token in l:
if token == 'for':
local = next(l)
assert(next(l) == 'in')
right = next(l)
scope[local] = right
current_comp = peek(stack, '')
print('current_c is', current_comp, 'complexity is', complexity[current_comp],
'stack is', stack, file=sys.stderr)
complexity[local] = complexity[current_comp] + right
stack.append(local)
elif token == 'end':
it = stack.pop()
# lookup turns 'ijn' into 'nnn'
# sorted turns 'nnm' into 'mnn'
#print('before', complexity[it], 'looking up', it, file=sys.stderr)
#terms = tuple(sorted(map(lambda i: lookup(i, scope), complexity[it])))
terms = tuple(sorted(map(lambda i: lookup(i, scope), complexity[it])))
outputs.add(''.join(terms))
print(complexity[it], it, file=sys.stderr)
complexity[it] = complexity[it][:-1] # remove the last iteration
# issue: complixity is not being updated
#scope = {k: v for k, v in scope.items() if v != it} # remove all items pointing to it
print('after', complexity[it], file=sys.stderr)
else:
raise ValueError('help')
'''
def remove_all_keys_with_value(v, d):
index = d.index(v)
while index is not None:
del[d[]]
'''
def counter_to_string(c):
return ''.join(map(lambda tup: tup[0] * tup[1], c.items()))
outputs = tuple(map(Counter, outputs))
# it's all LISP to me
print('+'.join(sorted(map(counter_to_string,
filter(lambda term: should_print(term, outputs),
outputs)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment