# Untitled

By: a guest on Aug 13th, 2013  |  syntax: Python  |  size: 1.96 KB  |  views: 46  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. from random import randint
2.
3. #pair operations
4. def pairPrecedence(pair):
5.     op = pair[1] #operator
6.     if op == '*' or op == '/':
7.         return 0
8.     return 1
9. def computePair(pair):
10.     op = pair[1] #operator
11.     x,y = int(pair[0]),int(pair[2])
12.     if op == '*':
13.         return x*y
14.     if op == '+':
15.         return x+y
16.     if op == '-':
17.         return x-y
18.     return int(x/y) #can only be divison
19.
20. operators = ('*','+','-','/') #division last for easy no zero division
21. (x,y) = input("Please input two numbers:  ").split()
22. x,y = int(x),int(y)
23. possNums = range(x,y+1) #range is exclusive, so y+1
24. numbers = tuple(possNums[randint(x,y)] for x in range(0,4))
25. pairs = []
26. for i in range(0,3): #generates three pairs for solution
27.     pair = []
28.     opMaxIndex = 3
29.     if numbers[i+1] == 0:
30.         opMaxIndex -= 1 #prevents division by zero
31.     pair = [numbers[i],operators[randint(0,opMaxIndex)],numbers[i+1]]
32.     pairs.append(pair)
33. expression = str(pairs[0][0])+' '+str(pairs[0][1])+' '+str(pairs[1][0])+' '+str(pairs[1][1])
34. expression = expression+' '+str(pairs[2][0])+' '+str(pairs[2][1])+' '+str(pairs[2][2])
35. print(expression)
36. prec = [pairPrecedence(pair) for pair in pairs]
37. print(prec)
38. #get solution
39. solution = -1
40. if prec == [1,1,1] or prec == [0,0,0]:
41.     solution = computePair([computePair(pairs[0]),pairs[1][1],computePair(pairs[2])])
42. if prec == [1,0,1]:
43.     solution = computePair([pairs[0][0],pairs[0][1],computePair(pairs[1])])
44.     solution += computePair([computePair(pairs[1]),pairs[2][1],pairs[2][2]])
45. if prec == [0,1,0]:
46.     solution = computePair([computePair(pairs[0]),pairs[1][1],computePair(pairs[2])])
47. if prec == [1,0,0]:
48.     solution = computePair([pairs[1][0],pairs[1][1],computePair(pairs[2])])
49.     solution = computePair([pairs[0][0],pairs[0][1],solution])
50. if prec == [0,0,1]:
51.     solution = computePair([pairs[0],pairs[1][1],pairs[1][2]])
52.     solution = computePair(solution,pairs[2][1],pairs[2][2])
53. print(solution)
54. print(eval(expression))
clone this paste RAW Paste Data
Top