Você está na página 1de 11

Calculator Python + locker problem:

Design a functioning calculator

#------------------------------------------------------------------------------# Name:

module3

# Purpose:
#
# Author:

Tyler

#
# Created:

19/10/2013

# Copyright: (c) Tyler 2013


# Licence:

<your licence>

#-------------------------------------------------------------------------------

class Stack(object):
def __init__(self):
self._s = []
def stackPush(self, item):
return self._s.append(item)

def stackList(self):
return self._s

def stackLength(self):

return len(self._s)

def stackPeek(self):
if len(self._s) == 0:
return []
else:
return self._s[len(self._s) - 1]
def stackPop(self):
if self.stackIsEmpty():
raise SyntaxError, "ERROR: Stack is empty."
else:
return self._s.pop()
def stackIsEmpty(self):
if len(self._s) == 0:
return True
else:
return False

def __str__(self):
start = ", ".join(map(str, self.stackList()))
return "Stack contains: " + start

class Queue(object):
def __init__(self):
self._q = []

def queueIsEmpty(self):
if len(self._q) == 0:
return True
else:
return False

def queuePush(self, item):


return self._q.append(item)

def queuePop(self):

if self.queueIsEmpty():
raise SyntaxError, "ERROR: Queue is empty"
else:
return self._q.pop()

def queuePeek(self):
if len(self._q) == 0:
return []
else:
return self._q[len(self._q) - 1]

def queueLength(self):
return len(self._q)

def queueList(self):
return self._q
def tokenizer(inString):
NUMBERS = '1234567890'
q = []
temp = ''
for i in inString:
if (temp == '' and i == '-') or (i in NUMBERS or i == '.'):
temp += i
elif i in ['^','*','/','+','-','(',')']:
if temp <> '':
q.append(temp)
temp = ''
q.append(i)
elif i == ' ' or i == ',':
continue
else:
raise ValueError, '*** Invalid character in input string: ' + i

if temp <> '':


q.append(temp)
return q

def Precedence(i):
if i == '^':
return 3
if i == '*' or i == '/':
return 2
if i == '+' or i == '-':
return 1

def infix2postfix(list):
pemdas = ['^', '*', '/', '+', '-']

s = Stack()
q = Queue()

for i in list:
if i != '^' and i != '*' and i != '/' and i != '+' and i != '-' and i != '(' and i != ')':
q.queuePush(i)
elif i in pemdas:
if s.stackPeek() in pemdas and precedence(i) <= precedence(s.stackPeek()):
q.queuePush(s.stackPop())
s.stackPush(i)
elif i == '(':
s.stackPush(i)
elif i == ')':

while s.stackPeek() != '(':


q.queuePush(s.stackPop())
s.stackPop()
while s.stackLength() > 0:
q.queuePush(s.stackPop())
return q.queueList()

def theEvaluator(answer):
s = Stack()
for i in answer:
if i != '-' and i != '*' and i != '^' and i != '/' and i != '+' :
s.stackPush(i)
else:
Xnumber = float(s.stackPop())
Ynumber = float(s.stackPop())

if i == '^':
answer = Ynumber**Xnumber
s.stackPush(answer)

elif i == '+':
answer = Xnumber+Ynumber
s.stackPush(answer)
elif i == '/':
answer = Ynumber/Xnumber

s.stackPush(answer)
elif i == '-':
answer = Ynumber-Xnumber
s.stackPush(answer)
elif i == '*':
answer = Ynumber*Xnumber
s.stackPush(answer)
final = s.stackPeek()
return (float(final))

def main():
print 'This calculator wil evaluate any mathematical expression '
print ' you may use parenthesis () ^ (exponent) * (multiplication) / (division) +
(addition) - (subtraction).'
expression = raw_input('Enter infix expression: ')
list = tokenizer(expression)
answer = infix2postfix(list)
temp = ''
for i in answer:
temp += i + ''
print 'The postifx expression is: ' + temp
print 'The answer is ' + str(round(theEvaluator(answer), 4))

main()

Imagine you are at a school that has 1,000 lockers. All lockers are currently closed and unlocked. The
school also has 1,000 students.
Here's the problem:

Suppose the first student goes along the row and opens all 1,000 lockers.

The second student then goes along and shuts every even numbered locker, beginning with
number 2.

The third student changes the state of every third locker, beginning with number 3. (If the locker is
open the student shuts it, and if the locker is closed the student opens it.)

The fourth student changes the state of every fourth locker beginning with number 4.

Imagine that this continues for all 1000 students. Student 100 changes locker 100, 200, 300, etc. up to
locker 1000. Student 500 changes locker 500 and locker 1000. Finally, Student 1,000 simply changes the
state of locker 1,000.
At the end, how many lockers will be open? which ones? Why?

def locker(lockers):

students = lockers
Open = [ False ] * (lockers+1)

for x in range(1,students+1):
for i in range(x, lockers+1, x):
Open[i] = not Open[i]
lockercount=0
print "the following are the locker numbers that are open:"
for i in range(1, lockers+1):

if Open[i]:

print i;
lockercount=lockercount+1

print Open
print "the amount of lockers open are the true lockers therefore there are: ",
lockercount, "lockers open when there are a total of", x, "lockers"

def main():
x=input("How many lockers are there?")
locker(x)
main()

#Tyler Sherman
#Explanation: After running the program we see the results of 31 lockers open of
the 1000 lockers present.
#Very noticeably, the locker numbers that were left open are all perfect squares as
seen below.
#Why is this the case? The perfect squares have an odd number of factors.
#Therefore, since the lockers started off closed, and an odd number of students
changed the status of the locker
#those lockers will always end up open after all the students have finished.
#In other words, on or off, open or closed, true or false,
#if we assign these actions and states values, like 1 for true and -1 for false
(otherwise known as an odd number of sequence changes)
#the state will always be the opposite of what it started out to be.
#Therefore, if we wanted to predict the number of open lockers within a sequence
#such as this all we would have to do is take the original amount of locker and
divide it by the amount of perfect squares within that range.

#Locker numbers:
#1
#4
#9
#16
#25
#36
#49
#64
#81
#100
#121
#144
#169
#196
#225
#256
#289
#324
#361
#400
#441
#484
#529
#576

#625
#676
#729
#784
#841
#900
#961

Você também pode gostar