Commits

Anonymous committed 9c23af6

initial import of example code

  • Participants

Comments (0)

Files changed (1)

dice_calculator.py

+#!/usr/bin/python
+
+import sys
+import random
+
+def d2s(dice):
+  pos = dice.find('d')       # index of dice operator
+  try:
+    n = int(dice[pos + 1:])    # number of sides
+  except ValueError:
+    n = 6
+  try:  
+    t = int(dice[:pos])        # number of throws
+  except ValueError:
+    t = 1
+  return str(sum([random.randint(1, n) for x in range(t)]))
+
+
+def validate(expression):
+  # before validation remove spaces and newlines
+  expression = expression.replace(' ', '').strip()
+  
+  # change case to lowercase
+  expression = expression.lower()
+  
+  # define valid characters
+  validCharset = [str(x) for x in range(10)] + ['+','-','*','/','(',')','d']
+  
+  # check there are no invalid chars
+  if False in [x in validCharset for x in expression]:
+    raise ValueError("Invalid characters in %s" % expression)
+
+  return expression
+
+
+def transform(expression):
+  # find the position of the operator. Python's find() function finds
+  # the leftmost match, we are going to substitute 'd' from left to right
+  pos = expression.find('d')
+  
+  # if there's no operator, we can return the expression itself
+  if pos == -1:
+    return expression
+
+  # look forward and backward, stop when character is not a digit. Since it
+  # has been already validated, we are sure that there are only digits and valid tokens.
+  start = end = 1
+  while pos - start > 0 and expression[pos - start].isdigit() :
+    start += 1
+   
+  # decrement start so that the operator is found at proper place :-) 
+  start -= 1
+  while pos + end < len(expression) and expression[pos + end].isdigit():
+    end += 1
+    
+  # call this function recursively, until all 'dice operators' have been substituted 
+  return transform(expression.replace(expression[pos - start:pos+end], d2s(expression[pos - start:pos+end])))
+
+
+def main():
+  if len(sys.argv) > 1:
+    expression = ''.join(sys.argv[1:])
+  else: 
+    expression = raw_input('Enter formula: ')
+  
+  try:
+    validate(expression)
+  except ValueError:
+    sys.stderr.write("There is an error in your expression\n")
+    sys.exit(1)
+  print(eval(transform(expression)))
+
+
+if __name__ == '__main__': main()