• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Solution to Part 1 Final Test kuhnerdm  Nov 20th, 2018 (edited) 111 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # This is the solution to the Final Test of part 1 of the DIY Guide for Learning to Code.
2. # We'll start by defining some functions we're going to use. If you want, you
3. # can skip to the end to see the main program, which is a loop that just calls our
4. # function evaluateEquation.
5.
6. # The following does all the hard work of deciding whether an equation is True or False.
7. def evaluateEquation(equation):
8.
9.     # Remove spaces from the equation entirely
10.     equation = equation.replace(' ', '')
11.
12.     # Split the equation into two halves, one on each side of the equals sign
13.     indexOfEqualSign = equation.find('=')
14.     firstHalf = equation[0:indexOfEqualSign]
15.     secondHalf = equation[(indexOfEqualSign + 1):] # We add one to the first index so that we don't include the sign itself. When we don't include a second index, that means "go to the end"
16.
17.     # For each of these halves, simplify it into a single number.
18.     # We're actually going to use a "helper function" here, because this is a lot of work that we're actually going to use twice.
19.     # You can see what the function looks like down below.
20.     firstHalf = simplifyHalf(firstHalf)
21.
22.     # Great! When that function finally completes, we'll be left with just a number. Now we need to do the exact same thing for the second half:
23.     secondHalf = simplifyHalf(secondHalf)
24.
25.     # So now, we have firstHalf and secondHalf, which are now both just numbers. All we need to do is compare them!
26.     return (firstHalf == secondHalf)
27.
28. # The following is a "helper function" that we use a couple times in the evaluateEquation function above.
29. def simplifyHalf(half):
30.     # The goal here is to start from the first number, the first operator,
31.     # and the second number (For example, "3 * 5"). Evaluate that, and replace
32.     # those three items with the result ("21"). Repeat until you only have a number left.
33.     while(('+' in half) or ('-' in half) or ('*' in half) or ('/' in half)):
34.         # We need to find the first operator (of any type) in the string. We do this in the "findIndexOfFirstOperator" function, which you can find defined below.
35.         firstOperatorIndex = findIndexOfFirstOperator(half)
36.         # Now to find the second one. Why do we need to know where the second operator is?
37.         # This will tell us where to stop looking for numbers, so we'll just have two numbers with an operator in between.
38.         # The operator we're looking for is really the first operator *after* the one we already found.
39.         secondOperatorIndex = findIndexOfFirstOperator(half[(firstOperatorIndex + 1):])
40.
41.         # It's possible the second operator does not exist - Let's set it to the end of the string if that's the case
42.         if(secondOperatorIndex == -1):
43.             secondOperatorIndex = len(half)
44.         else:
45.             secondOperatorIndex = secondOperatorIndex + firstOperatorIndex + 1 # Otherwise, get the position in the entire string
46.
47.         # Let's figure out what those two numbers are, that are separated by an operator.
48.         firstNumber = half[0:firstOperatorIndex]
49.         secondNumber = half[(firstOperatorIndex + 1):secondOperatorIndex]
50.         print(firstNumber)
51.         print(secondNumber)
52.
53.         # So now, we have firstNumber, firstOperator, and secondNumber. Now we can simplify it!
54.         if(half[firstOperatorIndex] == "+"):
55.             val = int(firstNumber) + int(secondNumber)
56.         elif(half[firstOperatorIndex] == "-"):
57.             val = int(firstNumber) - int(secondNumber)
58.         elif(half[firstOperatorIndex] == '*'):
59.             val = int(firstNumber) * int(secondNumber)
60.         elif(half[firstOperatorIndex] == '/'):
61.             val = int(firstNumber) / int(secondNumber)
62.
63.         # We now have a simplified value, so let's plug it in.
64.         half = str(val) + half[secondOperatorIndex:]
65.
66.     # When this loop completes, we'll have just a number!
67.     return half
68.
69. # The following is a "helper function" that we use a couple times in the simplifyHalf function above.
70. def findIndexOfFirstOperator(expression):
71.     # Find the first of each type of operator
72.     firstPlus = expression.find('+')
73.     firstMinus = expression.find('-')
74.     firstTimes = expression.find('*')
75.     firstDiv = expression.find('/')
76.
77.     # Now to find which of these actually comes first. We're trying to find the lowest of these numbers that is NOT -1
78.     firstOp = firstPlus
79.     if(firstOp == -1 or (firstMinus != -1 and firstMinus < firstOp)):
80.         firstOp = firstMinus
81.     if(firstOp == -1 or (firstTimes != -1 and firstTimes < firstOp)):
82.         firstOp = firstTimes
83.     if(firstOp == -1 or (firstDiv != -1 and firstDiv < firstOp)):
84.         firstOp = firstDiv
85.     return firstOp
86.
87. # So now that all our functions are defined, here's all that the main program takes:
88. equationFromConsole = input("Enter equation: ")
89. while(equationFromConsole != "exit"): # This is how we get it to quit out
90.     print(evaluateEquation(equationFromConsole))
91.     equationFromConsole = input("Enter equation: ")
92.
93. # All done! The real trick to all of this was being able to take work that
94. # you have to do multiple times, and make it a function. We did this three times:
95. #     1. For finding the first operator in a string
96. #     2. For simplifying one half of the expression to a single number
97. #     3. For figuring out whether an equation is true or false
98. # All of these functions build on each other, and that's the key to solving a really complex problem
99. # with code - Break it down into parts, and treat each part as a simpler problem.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top