# Aptamers / dice_calculator.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74``` ```#!/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() ```