Last active
August 29, 2015 14:17
-
-
Save CT075/0d0a7caf06cdf569b758 to your computer and use it in GitHub Desktop.
Daily Programmer #206 naive implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
func_dict = { | |
'+' : lambda x,y:y+x, | |
'-' : lambda x,y:y-x, | |
'*' : lambda x,y:y*x, | |
'/' : lambda x,y:y/x | |
} | |
# Given the RPN string, return a function that calculates the nth term | |
# based on the list of previous terms. | |
def create_func_naive(data): | |
def recurse(n, acc): | |
stack = [] | |
for atom in data.split(): | |
# XXX - probably don't need to check both paren's | |
if '(' in atom and ')' in atom: | |
index = n-int(atom[1:-1]) | |
if index < 0: return None | |
term = acc[index] | |
# Reference undefined term | |
if term == None: return None | |
stack.append(term) | |
# lol | |
elif atom in '+-*/': | |
stack.append(func_dict[atom](stack.pop(), stack.pop())) | |
else: stack.append(int(atom)) | |
return stack[0] | |
return recurse | |
data = {} | |
func = create_func_naive(input()) | |
nums = list(map(int, input().split(':'))) | |
while len(nums) == 2: | |
data[nums[0]] = nums[1] | |
nums = list(map(int, input().split(':'))) | |
top = nums[0]+1 | |
for i in range(top): | |
if i not in data: data[i] = func(i, data) | |
for i in data: | |
if data[i] is not None: print('%s:\t%s' % (i, data[i])) | |
input() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment