starter python Homework|Computer Science

starter python Homework|Computer Science

5 questions, including beginning  code and step by step teaching code

Lab2/.DS_Store
__MACOSX/Lab2/._.DS_Store
Lab2/callable_examples.py
import string import random import math def introduction(): intro1 = “””\n\nA callable is an object that allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions. “”” print intro1 intro2 = “””In Python, a callable is an object which has a __call__ method. You usually don’t see the call method. That’s hidden behind the scenes. But you are using it every time you use round parentheses (). “”” print intro2 intro3 = “””If f is callable, you can enter f() or perhaps f(10) if it requires an argument. f(10) for a callable object f is equivalent to f.__call__(10) Here are some examples to show that equivalence. “”” print intro3 def example1(): print “Example 1: The int() method is callable.” print ‘Is “int” callable?’, callable(int) print “The string ’10’ equals the integer:”, int(’10’) print “The string ’10’ equals the integer:”, int.__call__(’10’) print “Convert the binary number ‘111111’ to base 10.” print “Converting to base 10 we get:”, int(‘111111’, 2) print “Converting to base 10 we get:”, int.__call__(‘111111’, 2) def example2(): print “\nExample 2: The max() method is callable.” print ‘Is “max” callable?’, callable(max) print “The max of 1, 2 & 3 is:”, max(1, 2, 3) print “The max of 1, 2 & 3 is:”, max.__call__(1, 2, 3) result = max.__call__.__call__.__call__.__call__.__call__(1, 2, 3) print “You can chain many ‘__call__’s together.”, print “For example: >>> max.__call__.__call__.__call__.__call__.__call__(1, 2, 3)” print “This gives the same result:”, result def example3(): print “\nExample 3: The upper() method in the string module is callable.” print ‘Is “upper” callable?’, callable(string.upper) s = “usa” print “I live in the %s.” % s.upper() print “I live in the %s.” % string.upper(s) print “I live in the %s.” % s.upper.__call__() print “I live in the %s.” % string.upper.__call__(s) def example4(): print “\nExample 4: The sin() method in the string math is callable.” print ‘Is “sin” callable?’, callable(math.sin) print “The sin of 0 radians is:”, math.sin(0) print “The sin of 0 radians is:”, math.sin.__call__(0) print “Is the math module itself callable?”, callable(math) def example5(): print “\nExample 5: Strings are not callable.” my_string = “I am a string.” print “Is this string callable?”, callable(my_string) print “Is the string module callable?”,callable(string) try: print “Testing if a string is callable.” my_string(10) # Here we try to call a string. except Exception as e: print “Nope! A string object is not callable.” print e.message def example6(): print “\nExample 6: You can create your own callable objects by defining the __call__ method in a class. ” class Caller(object): def __call__(self, name_of_caller=None, message=”How are you?”): if name_of_caller != None: print “Hi, it’s %s.” % name_of_caller, if message != None: print message caller1 = Caller(); caller2 = Caller() print “Is the caller – callable?”, callable(caller1) caller1(name_of_caller=”Me”, message=”How are you?”) caller2( “Joseph”, “Who’s calling?”) caller1(“Mary”, “Are you watching the news?”) caller2(message=”I am. What a mess!”) def example7(): print “\n\nExample 7: A custom function defined using def is callable.” def knock_knock(name): print “Q: Who’s there?”, “A: It’s me, %s.” % name print “Is knock_knock callable?”, callable(knock_knock) # True knock_knock(“Fluffy your cat”) knock_knock.__call__(“Fluffy your cat”) def example8(): print “\nExample 8: Is callable itself callable.” # i. Test if callable is callable without using __call__. Add your code below. # ii. Test if callable is callable using exactly one __call__. Add your code below. # iii. Test if callable is callable using __call__ exactly twice. Add your code below. # There are two solutions. def example9(): # For each object below, print out whether or not it is callable. # Fully document each example using print statements. # If it is callable, demonstrate that using the __call__ operator. pass # part i: Is the number 3 callable. Add code here. # part ii: Is the math module callable. Add code here. # part iii: Is the function math.sqrt callable. Add code here. # part iv: Is the constant math.pi callable. Add code here. # part v: Is range callable. Add code here. if __name__ == “__main__”: introduction() example1() example2() example3() example4() example5() example6() example7() example8() example9()

__MACOSX/Lab2/._callable_examples.py
Lab2/dunder_methods_for_lists.py
# Dunder methods for lists – also called MAGIC methods # Repeat each list operation using a dunder method instead. # If you need to know the name for a dunder method, type >>> help(list) print “\n* * * * * Dunder Methods for Lists * * * * * ” def demo1(): # + print “\n\nExample 1: Concatenation of lists:\t x.__add__(y) <==> x+y” list1 = [1, 2, 3] list2 = [6, 5] result1 = list1 + list2 print “The concatenation of %s and %s is: %s” % (list1, list2, result1) dunder_method = “__add__” result2 = list1.__add__(list2) print “Using %s we get the same result: %s” % (repr(dunder_method), result2) def demo2(): # in print “\n\nExample 2: Is list1 in list2:\t x.__contains__(y) <==> y in x” # Note: | x.__contains__(y) <==> y in x # So you have to switch the order. list1 = [3, 4] list2 = [1, 2, [3, 4], 5] result1 = list1 in list2 print “Is %s in %s %s” % (list1, list2, result1) dunder_method = “__contains__” result2 = list2.__contains__(list1) print “Using %s we get the same result: %s” % (repr(dunder_method), result2) def demo3(): # del print “\n\nExample 3: Deleting an item from a list:\t x.__delitem__(y) <==> del x[y]” list1 = [“cat”, “fish”, “bird”] dunder_method = “__delitem__” # O-o. Looks like the cat was hungry. del list1[2] # none type, deletes in place. print “After the cat ate the bird, list1 is just:”, list1 list1.__delitem__(1) # index of the fish. print “Using %s the ‘cat’ also ate the ‘fish’ leaving just: %s” % (repr(dunder_method), list1) def demo4(): # == print “\n\nExample 4: Testing equality of lists using:\t x.__eq__(y) <==> x==y” list1 = [1, 2, 3] list2 = [1, 2, 3, 4]; list2.pop() # none type, pops in place dunder_method = “__eq__” result1 = list1 == list2 print “Does %s equal %s? %s” % (list1, list2, result1) result2 = list1.__eq__(list2) print “Using %s we get the same result: %s” % (repr(dunder_method), result2) def demo5(): # >= print “\n\nExample 5: Is list1 greater than or equal to list2 using:\t x.__ge__(y) <==> x>=y” list1 = [1, 2, 3, 4] list2 = [1, 2, 3, 3] print list1 >= list2 print list1.__ge__(list2) def demo6(): # indexing print “\n\nExample 6: Getting an item from a list using:\t x.__getitem__(y) <==> x[y]” list1 = range(10,-1,-1) print “Our list for example 6 is: “, list1 print “The item with index 4 is: “, list1[4] dunder_method = “__getitem__” # show how to get the item with index 4 using the dunder method. # add code here. def demo7(): # __reversed__ iterator print “\n\nExample 7: Iterating through a list: Normal and reversed order” # First we iterate through a list in the normal order. list1 = [1, 2, 3, 4, 5] print “The items in the list %s appear in this order:” % list1 print “\t”, for item in list1: print item, # Now add code to iterate through the list in reverse order. Use __reversed__() print “\nHere now are the items in reverse order:” print “\t”, # add a for loop here using your reversed iterator. def demo8(): # * n using __rmul__ print “\n\nExample 8: Multiplying a list by an integer using:\t x.__mul__(n) <==> x*n” list1 = [1, 2, 3] print “Pre-multiplying our list %s on the left by 3 gives: %s” % (list1, 3 * list1 ) dunder_method = “__rmul__” # add code to produce the same result using the dunder method. Print out the result for comparison def demo9(): # != using __ne__ print “\n\nExample 9: Testing if two lists are NOT equal using:\t x.__ne__(y) <==> x!=y” list1 = [1, 2, 3]; list2 = [1, 2, 3, []] # list2 has a hidden empty list nested inside. print “Are the two lists NOT equal? Is %s NOT equal to %s? \t %s” % (list1, list2, list1 != list2) dunder_method = “__ne__” # Add code to reproduce the same result using the dunder method instead. Print out the result for comparison def demo10(): # initialize a list using __init__ print “\n\nExample 10: Initializing a list using __init__” tuple1 = (1, 2, 3, 4, 5) list1 = list(tuple1) print “After initializing the list using a tuple, list1 is %s.” % list1 dunder_method = “__init__” # Add code to reproduce the same result using the dunder method instead. Print out the result for comparison list2 = [] if __name__ == “__main__”: demo1() demo2() demo3() demo4() demo5() demo6() demo7() demo8() demo9() demo10()

Lab2/HanoiStack.py
“”” A subclass of the Stack superclass designed to help solve the Tower of Hanoi problem. Unlike classical stacks, HanoiStacks are callable. If A and B are HanoiStacks then A(B) is defined so that the stack with the smaller element on top is popped and then pushed onto the other stack. No value is returned, but both stacks are changed; unless both stacks are empty, and then nothing happens. Since the definition is symmetric, A(B) and B(A) produce the same result. It is also always the case that A(A(B)) and B(A(B)) have no effect. The previous action is undone. Each new element on a HanoiStack must be smaller than the previous, except the first. “”” from Stack import * # Note that super() can only be used with new-style classes. # Therefore Stack was assured to be a new-style for this homework by adding ob ject in its header. class HanoiStack(Stack): # A HanoiStack is first of all, a Stack. def __init__(self, initial_list=[]): super(HanoiStack, self).__init__(initial_list) # A HanoiStack has a flag which makes it active or inactive. self.isActive = True # But HanoiStacks can also call each other. Complete this call method. def __call__(self, other): # We will have to handle a few special cases first. # i. If both HanoiStacks are empty, just return. Use isEmpty() twice. Be sure to return! # ii. If the calling stack named ‘self’ is empty, pop ‘other’ and push that onto ‘self’. Be sure to return! # iii. If the called stack named ‘other’ is empty, pop ‘self’ and push that onto ‘other’. Be sure to return! # iv. Now handle the general case. Neither stack is empty. Done for you. # Pop the stack with the smaller item on top and push that onto the other stack. # If the top of stack ‘self’ is less than the top of ‘other’, pop ‘self’ and push onto ‘other’ if self.peek() < other.peek(): other.push( self.pop() ) else: self.push( other.pop() ) def __str__(self): if self.isActive: return “+ ” + str(self.stack_list) else: return “- ” + str(self.stack_list) def show(A, B, C): print “A:”, A print “B:”, B print “C:”, C if __name__ == “__main__”: print “\n * * * * * Demo for HanoiStack Class * * * * * ” print ” Solve the Hanoi Tower with N = 3 Rings” print “\n\n* * * * * SETUP * * * * * ” rings = range(3, 0, -1) # [3, 2, 1] print “The starting rings are:”, rings A = HanoiStack(rings) print “\nHere is stack A with its three rings:”, A print “Note the plus sign which indicates its status is active.\n\n” print “2. B and C are two empty HanoiStacks.” B = HanoiStack([]) # empty C = HanoiStack([]) # empty B.isActive = False print “Here are all three HanoiStacks A, B and C. Which one is the inactive one?” show(A, B, C) print “\n\n3. Ready! Our Tower Of Hanoi with n = 3 is all setup. Let’s solve it in 2**n – 1 = 7 moves. ” print “\n\n* * * * * SOLUTION STEPS * * * * * ” print “\nMove 1: A(C), then move the inactive arrow one to the right from B to C since n is odd.” try: A(C); B.isActive = True; C.isActive = False; except Exception as e: print “ALERT: You must fix __call__ first.”, repr(e) show(A, B, C) print “\nMove 2: A(B), then move the inactive arrow one to the right from C to A since n is odd.” try: A(B); C.isActive = True; A.isActive = False; except Exception as e: print “ALERT: You must fix __call__ first.”, repr(e) show(A, B, C) print “\nMove 3: B(C), then move the inactive arrow one to the right from A to B since n is odd.” B(C); A.isActive = True; B.isActive = False; show(A, B, C) print “\nMove 4: A(C), then move the inactive arrow one to the right from B to C since n is odd.” A(C); B.isActive = True; C.isActive = False; show(A, B, C) print “\nMove 5: A(B), then move the inactive arrow one to the right from C to A since n is odd.” A(B); C.isActive = True; A.isActive = False; show(A, B, C) # Add code here to solve the problem with two more moves. Moves number 6 and 7. # Have the two active stacks call each other, move the inactive arrow one to the right since n is odd. # Move #6 is exactly the same as move number 3. print “\nMove 6: B(C), then move the inactive arrow one to the right from A to B since n is odd.” # Move #7 is exactly the same as move number 4. print “\nMove 7: A(C), then move the inactive arrow one to the right from B to C since n is odd.”

Lab2/Stack.py
__author__ = ‘robincarr’ import time # Last item in the list named “items” is the TOP of the stack. # First item (index 0) in the list “items” is the bottom of the stack. # Top of the stack is the end of its list of items. # LIST IMPLEMENTATION OF A STACK IN PYTHON class Stack(object): def __init__(self, initial_list=[]): # example of an optional argument self.stack_list = initial_list # the list of items in the Stack def isEmpty(self): return self.stack_list == [] # Returns True if the stack is empty, otherwise False. def push(self, item): self.stack_list.append(item) # Append the new item to the top of the stack’s list. def pop(self): # Implements the pop() method for stacks, using the pop() method for its list. if not self.isEmpty(): return self.stack_list.pop() def peek(self): return self.stack_list[len(self.stack_list) – 1] # These next methods are not core stack methods, but are still useful. def size(self): return len(self.stack_list) def __str__(self): return str(self.stack_list) + “<–” # The arrow here represents the pointer to the top of the stack. def __eq__(self, other): # i. two stacks are equal iff their stack_list attributes are equal. Be sure to return the result. return True # just a stub that always returns True. Fix it! def demo1(): print “\n * * * * * STACKS: DEMO # 1 * * * * * ” stack1 = Stack([1, 2, 3, [4, 5]]) print “Here is out initial stack”, stack1 print “Next, we will pop it, until it is empty. ” while not stack1.isEmpty(): stack1.pop() print “\tAfter popping: “, stack1 print “It’s OK to pop an empty stack. We added code so that does nothing and does not throw an error either.” stack1.pop() # no problem, does not throw error. def demo2(): pass print “\n\n * * * * * STACKS: DEMO # 2: PALINDROME * * * * * ” stack1 = Stack([]); stack2 = Stack([]); temp = Stack([]) # a temporary stack, soon to be consumed. test_phrase = “TacoCat”.upper() # test_phrase = “Aerate pet area.”.upper() # ii. Add a for loop and an if statement to push each character in the test_phrase onto both stack1 and temp, # if that character (ch) isalpha(). # iii. pop every item from temp and push it onto stack2. This will create a reversed stack. # iv. test if stack1 and stack2 are equal using ==. Print an appropriate message. # Must fix the dunder method __eq__ first! # Use an if/else structure to print yes or no messages that also mprint out the test_phrase. if __name__ == “__main__”: demo1() demo2()

Lab2/Tower_of_Hanoi.py
# we will model a Tower of Hanoi as having three HanoiStacks and two integer counters, one for ring # and one for # of moves. # from Stack import * from HanoiStack import * class TowerOfHanoi: # the Tower of Hanoi aggregates three Hanoi Towers. def __init__(self, n): rings = range(n, 0, -1) self.A = HanoiStack(rings) self.B = HanoiStack([]) # empty self.C = HanoiStack([]) # empty self.numberOfRings = n self.numberOfMoves = 0 # Exactly one stack is at rest. Depends on even or odd number of rings. if n%2 == 0: self.C.isActive = False else: self.B.isActive = False def __str__(self): # the Tower of Hanoi can display itself as a string. return “A: ” + str(self.A) + “\nB: ” + str(self.B) + “\nC: ” + str(self.C) # The puzzle is solved when both stacks A and B are empty. def isDone(self): return self.A.isEmpty() and self.B.isEmpty() def updateStackActivityStatus(self): # Assume stacks A, B and C have indices 0, 1, 2. # Let the number of rings be n. # Then after k moves, the inactive stack has index: (2-k) %3 if k even, else (1+k) % 3 k = self.numberOfMoves if self.numberOfRings % 2 == 0: inactive_index = (2-k) % 3 else: inactive_index = (1+k) % 3 self.A.isActive = True; self.B.isActive = True; self.C.isActive = True if inactive_index == 0: self.A.isActive = False; if inactive_index == 1: self.B.isActive = False; if inactive_index == 2: self.C.isActive = False; def solve(self): if self.isDone(): return # Find the two active stacks. all_stacks = [self.A, self.B, self.C] active_stack = [] for stack in all_stacks: if stack.isActive: active_stack.append(stack) active_stack[0]( active_stack[1]) self.numberOfMoves +=1 self.updateStackActivityStatus() print “\nAfter move number: “, self.numberOfMoves; print self if __name__ == “__main__”: number_of_rings = 6 # c. try 5 instead. tower = TowerOfHanoi(number_of_rings) # Construct the Tower of Hanoi with this many rings. print “Starting position: Tower of Hanoi with %d Rings” % tower.numberOfRings print tower # a. Add the while loop here to keeping calling tower.solve until the problem is solved. while not tower.isDone(): tower.solve() # d. add an if statement inside this while loop to test if we have reached the half-way point. # if we have, pause for 10 seconds. # b. Add a print statement here to show the number of moves it required to solve the problem.

Order from us and get better grades. We are the service you have been looking for.