Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Ugly solution to https://news.ycombinator.com/item?id=40989044
- $ cat testrun.py
- import sys
- prio1ops = ('*', '/')
- prio2ops = ('+', '-')
- def compute(tokens):
- while True:
- resolveAt = None
- for i, token in enumerate(tokens):
- # this can be done more elegantly if prio1 and -2 are an array-like type: TODO
- if token in prio1ops:
- resolveAt = i
- break
- if resolveAt is None:
- break
- else:
- if i == 0 or i == (len(tokens) - 1):
- print('operator at the start or end?', tokens)
- return False
- # so tempting to use eval here, since this is ugly, but not sure what the better solution is
- if tokens[i] == '/':
- tokens[i - 1] = tokens[i - 1] / tokens[i + 1]
- if tokens[i] == '*':
- tokens[i - 1] = tokens[i - 1] * tokens[i + 1]
- # so we modified index-1, then delete index and index+1
- del tokens[i]
- # because it shifts, we need to remove the index position twice
- del tokens[i]
- # Copied from the whileTrue above, TODO really should merge this into DRY...
- while True:
- resolveAt = None
- for i, token in enumerate(tokens):
- if token in prio2ops:
- resolveAt = i
- break
- if resolveAt is None:
- break
- else:
- if i == 0 or i == (len(tokens) - 1):
- print('operator at the start or end?', tokens)
- return False
- # so tempting to use eval here, since this is ugly, but not sure what the better solution is
- if tokens[i] == '+':
- tokens[i - 1] = tokens[i - 1] + tokens[i + 1]
- if tokens[i] == '-':
- tokens[i - 1] = tokens[i - 1] - tokens[i + 1]
- # so we modified index-1, then delete index and index+1
- del tokens[i]
- # because it shifts, we need to remove the index position twice
- del tokens[i]
- if len(tokens) != 1:
- print('Resolved the operators, but we are left with more than one token?', tokens)
- return False
- return tokens[0]
- for line in sys.stdin:
- line = line.replace(' ', '').strip()
- charssofar = ''
- tokens = []
- for char in line:
- if char in prio1ops + prio2ops:
- tokens.append(float(charssofar))
- charssofar = ''
- tokens.append(char)
- else:
- charssofar += char
- if len(charssofar) < 1:
- print('ends in an operator?')
- continue
- # TODO wrap float interpreting in try-catches
- tokens.append(float(charssofar))
- print(line, '=', compute(tokens))
- $ cat testset
- 1 + 1
- 1 * 2
- 1 + 2 * 2
- 1-1
- 1/2
- 1+2/2
- $ python3 testrun.py <testset
- 1+1 = 2.0
- 1*2 = 2.0
- 1+2*2 = 5.0
- 1-1 = 0.0
- 1/2 = 0.5
- 1+2/2 = 2.0
Advertisement
Add Comment
Please, Sign In to add comment