diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py index 06a830e4c8..8dae1779b9 100644 --- a/src/day-1-toy/args.py +++ b/src/day-1-toy/args.py @@ -4,14 +4,16 @@ # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. -#def f1(... +def f1(num1, num2): + return num1+num2 print(f1(1, 2)) # Write a function f2 that takes any number of iteger arguments and prints the # sum. Google for "python arbitrary arguments" and look for "*args" -# def f2(... +def f2(*args): + return sum(args) print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 @@ -21,13 +23,17 @@ a = [7, 6, 5, 4] # What thing do you have to add to make this work? -print(f2(a)) # Should print 22 +# print(f2(a)) # Should print 22 # Write a function f3 that accepts either one or two arguments. If one argument, # it returns that value plus 1. If two arguments, it returns the sum of the # arguments. Google "python default arguments" for a hint. -#def f3(... +def f3(num1, num2=None): + if num2 is None: + return num1+1 + else: + return num1+num2 print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 @@ -41,7 +47,11 @@ # # Google "python keyword arguments". -#def f4(... +def f4(**kwargs): + + for key, value in kwargs.items(): + print(key, value) + # print("key: {}, value: {}".format(arg, kwargs[arg])) # Should print # key: a, value: 12 @@ -60,4 +70,5 @@ } # What thing do you have to add to make this work? -f4(d) \ No newline at end of file +f4(**d) + diff --git a/src/day-1-toy/bar.txt b/src/day-1-toy/bar.txt new file mode 100644 index 0000000000..68d1073862 --- /dev/null +++ b/src/day-1-toy/bar.txt @@ -0,0 +1,3 @@ +Hello line 1 +How are you? +What s hot day! \ No newline at end of file diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py index 77e8d66ffa..84eddd1925 100644 --- a/src/day-1-toy/bignum.py +++ b/src/day-1-toy/bignum.py @@ -1 +1,2 @@ -# Print out 2 to the 65536 power \ No newline at end of file +# Print out 2 to the 65536 power +print(2**65536) \ No newline at end of file diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py index 2a3771eb5b..19446451a8 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -14,3 +14,28 @@ # docs for the calendar module closely. import sys +import calendar +import datetime + + +year = input("Enter year: ") +month = input("Enter month: ") +now = datetime.datetime.now() + +if not year and not month: + year = now.year + month = now.month +elif not year: + year = now.year + month = int(month) +elif not month: + month = now.month + year = int(year) +else: + year = int(year) + month = int(month) + +def printCal(year, month): + print(calendar.month(year,month)) + +printCal(year, month) diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 083e9b9140..84d2483090 100644 --- a/src/day-1-toy/comp.py +++ b/src/day-1-toy/comp.py @@ -2,6 +2,9 @@ y = [] +for i in range(1,6): + y.append(i) + print (y) # Write a list comprehension to produce the cubes of the numbers 0-9: @@ -9,6 +12,9 @@ y = [] +for i in range(0,9): + y.append(i**3) + print(y) # Write a list comprehension to produce the uppercase version of all the @@ -18,6 +24,9 @@ y = [] +for e in a: + y.append(e.upper()) + print(y) # Use a list comprehension to create a list containing only the _even_ elements @@ -26,7 +35,8 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] + +y = [e for e in x if int(e) % 2 == 0] print(y) diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py index f5967611a7..36be038164 100644 --- a/src/day-1-toy/datatypes.py +++ b/src/day-1-toy/datatypes.py @@ -2,7 +2,7 @@ y = "7" # Write a print statement that combines x + y into the integer value 12 -print(x + y) +print(x + int(y)) # Write a print statement that combines x + y into the string value 57 -print(x + y) \ No newline at end of file +print(str(x)+ y) \ No newline at end of file diff --git a/src/day-1-toy/dicts.py b/src/day-1-toy/dicts.py index eac1779a42..4aef69598d 100644 --- a/src/day-1-toy/dicts.py +++ b/src/day-1-toy/dicts.py @@ -21,9 +21,16 @@ "lat": 43, "lon": -122, "name": "a third place" + }, + { + "lat": 40, + "lon": -120, + "name": "a third place" } ] # Write a loop that prints out all the field values for all the waypoints +for e in waypoints: + print(e["lat"], e["lon"], e["name"]) # Add a new waypoint to the list diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index bc8e79b7cc..b7e7671d00 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -1,12 +1,21 @@ # Use open to open file "foo.txt" for reading +f= open("foo.txt","r") # Print all the lines in the file +contents = f.read() +print(contents) + # Close the file - +f.close() # Use open to open file "bar.txt" for writing +g= open("bar.txt","w+") # Use the write() method to write three lines to the file +g.write('Hello line 1\n') +g.write('How are you?\n') +g.write('What s hot day!') -# Close the file \ No newline at end of file +# Close the file +g.close() \ No newline at end of file diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index 2b7f435ffa..dcf37c3b9d 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -3,4 +3,8 @@ # Read a number from the keyboard num = input("Enter a number: ") -# Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file +# Print out "Even!" if the number is even. Otherwise print "Odd" +if int(num) % 2 == 0: + print(True) +else: + print(False) \ No newline at end of file diff --git a/src/day-1-toy/hello.py b/src/day-1-toy/hello.py index 37968da4d4..6ee1f01872 100644 --- a/src/day-1-toy/hello.py +++ b/src/day-1-toy/hello.py @@ -1 +1,2 @@ -# Write Hello, world \ No newline at end of file +# Write Hello, world +print('Hello, world') \ No newline at end of file diff --git a/src/day-1-toy/lists.py b/src/day-1-toy/lists.py index 6076f340a9..2d0fa7d240 100644 --- a/src/day-1-toy/lists.py +++ b/src/day-1-toy/lists.py @@ -8,22 +8,28 @@ # Change x so that it is [1, 2, 3, 4] # [command here] +x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # [command here] +x += y print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] # [command here] +x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] # [command here] +x.insert(-1,99) print(x) # Print the length of list x # [command here] print(len(x)) -# Using a for loop, print all the element values multiplied by 1000 \ No newline at end of file +# Using a for loop, print all the element values multiplied by 1000 +for num in x: + print(num*1000) \ No newline at end of file diff --git a/src/day-1-toy/modules.py b/src/day-1-toy/modules.py index 5313fc1934..2a3f30ee7e 100644 --- a/src/day-1-toy/modules.py +++ b/src/day-1-toy/modules.py @@ -9,10 +9,10 @@ # Print out the plaform from sys: -print() +print(sys.platform) # Print out the Python version from sys: -print() +print(sys.version_info) @@ -21,11 +21,11 @@ # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # Print the current process ID -print() +print(os.getpid()) # Print the current working directory (cwd): -print() +print(os.getcwd()) # Print your login name -print() +print(os.getlogin()) diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py index 84c78a2f53..9ef605745f 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -1,14 +1,38 @@ # Make a class LatLon that can be passed parameters `lat` and `lon` to the # constructor + +class LatLon: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the # constructor. It should inherit from LatLon. +class Waypoint(LatLon): + def __init__(self, name, lat, lon): + LatLon.__init__(self, lat, lon) + self.name = name + + def printW(self): + return self.name, self.lat, self.lon + # Make a class Geocache that can be passed parameters `name`, `difficulty`, # `size`, `lat`, and `lon` to the constructor. What should it inherit from? +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + Waypoint.__init__(self, name, lat, lon) + self.difficulty = difficulty + self.size = size + + def printG(self): + return self.name, self.difficulty, self.size, self.lat, self.lon + # Make a new waypoint "Catacombs", 41.70505, -121.51521 +wIns = Waypoint("Catacombs", 41.70505, -121.51521) +w = wIns.printW() # Print it # # Without changing the following line, how can you make it print into something @@ -17,5 +41,8 @@ # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 +gIns = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556) +g = gIns.printG() + # Print it--also make this print more nicely print(g) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index d4bc9abb48..88995f1357 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -5,6 +5,7 @@ # Using the printf operator (%), print the following feeding in the values of x, # y, and z: # x is 10, y is 2.25, z is "I like turtles!" +print("x is %i, y is %.2f, z is %s" % (x, y, z)) - -# Use the 'format' string method to print the same thing \ No newline at end of file +# Use the 'format' string method to print the same thing +print("x is {}, y is {}, z is {}".format(x, y, z)) \ No newline at end of file diff --git a/src/day-1-toy/scope.py b/src/day-1-toy/scope.py index 68ecc6c412..045393ce9a 100644 --- a/src/day-1-toy/scope.py +++ b/src/day-1-toy/scope.py @@ -5,6 +5,7 @@ x = 12 def changeX(): + global x x = 99 changeX() @@ -19,6 +20,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py index 3c6cb38730..62fd5399f9 100644 --- a/src/day-1-toy/slice.py +++ b/src/day-1-toy/slice.py @@ -1,26 +1,26 @@ a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: -print() +print(a[1]) # Output the second-to-last element: 9 -print() +print(a[-2]) # Output the last three elements in the array: [7, 9, 6] -print() +print(a[3:]) # Output the two middle elements in the array: [1, 7] -print() +print(a[2:4]) # Output every element except the first one: [4, 1, 7, 9, 6] -print() +print(a[1:]) # Output every element except the last one: [2, 4, 1, 7, 9] -print() +print(a[:-1]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[7:12]) \ No newline at end of file diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index ec42b0cdf8..ae77e7e9eb 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -22,11 +22,13 @@ def dist(a, b): # Write a function that prints all the values in a tuple -# def print_tuple(... +def print_tuple(t): + for i in t: + print(i) t = (1, 2, 5, 7, 99) print_tuple(t) # Prints 1 2 5 7 99, one per line # Declare a tuple of 1 element then print it -u = (1) # What needs to be added to make this work? +u = (1,) # What needs to be added to make this work? print_tuple(u) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index c9e26b0f85..85b42b070b 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,37 +1,38 @@ from room import Room +from player import Player # Declare all the rooms -room = { +rooms = { 'outside': Room("Outside Cave Entrance", - "North of you, the cave mount beckons"), + "North of you, the cave mount beckons", "outside", []), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty -passages run north and east."""), +passages run north and east.""", "foyer", ["torch"]), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in -the distance, but there is no way across the chasm."""), +the distance, but there is no way across the chasm.""", "overlook", ["match"]), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west -to north. The smell of gold permeates the air."""), +to north. The smell of gold permeates the air.""", "narrow",[]), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south."""), +earlier adventurers. The only exit is to the south.""", "treasure", []), } # Link rooms together -room['outside'].n_to = room['foyer'] -room['foyer'].s_to = room['outside'] -room['foyer'].n_to = room['overlook'] -room['foyer'].e_to = room['narrow'] -room['overlook'].s_to = room['foyer'] -room['narrow'].w_to = room['foyer'] -room['narrow'].n_to = room['treasure'] -room['treasure'].s_to = room['narrow'] +rooms['outside'].n_to = rooms['foyer'] +rooms['foyer'].s_to = rooms['outside'] +rooms['foyer'].n_to = rooms['overlook'] +rooms['foyer'].e_to = rooms['narrow'] +rooms['overlook'].s_to = rooms['foyer'] +rooms['narrow'].w_to = rooms['foyer'] +rooms['narrow'].n_to = rooms['treasure'] +rooms['treasure'].s_to = rooms['narrow'] # # Main @@ -49,3 +50,62 @@ # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. + +class Main: + def start(self): + # Make a new player object that is currently in the 'outside' room. + playerA = Player('Thuy', rooms['outside']) + print('Welcome ' + playerA.name + '!') + playerA.getRoom() + + + move = '' + + while move != 'q': + move = input(">>>>>>Your next move? w(west), s(south), n(north), e(east), i(inventory) or q(quit): ") + + if move != 'q': + if move == 'i': + playerA.room.view_items() + playerA.view_bag() + action = input(">>>>>>Add (a), Drop (d) an item, or Skip(s): ") + + if action == 'a' or action == 'd': + number = input(">>>>>>Item Number: ") + try: + int(number) + except ValueError: + print("Not a valid number!") + if action == 'a': + if int(number) <= (len(playerA.room.items)-1): + playerA.add_item(playerA.room.items[int(number)]) + playerA.room.remove_item(int(number)) + else: + playerA.room.add_item(playerA.bag[int(number)]) + playerA.drop_item(int(number)) + + playerA.room.view_items() + playerA.view_bag() + + else: + moveKey = move + '_to' + + try: + print(getattr(playerA.room,moveKey).shortname) + rooms[getattr(playerA.room,moveKey).shortname] + except AttributeError: + print('>>>>>>>There is no way on that direction! Try again!\n') + playerA.getRoom() + except KeyError: + print('>>>>>>>There is no way on that direction! Try again!\n') + playerA.getRoom() + else: + playerA.room = rooms[getattr(playerA.room,moveKey).shortname] + playerA.getRoom() + + + else: + print('See you later!') + +new_game = Main() +new_game.start() diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py new file mode 100644 index 0000000000..27d8cbc6e8 --- /dev/null +++ b/src/days-2-4-adv/item.py @@ -0,0 +1,6 @@ +# Implement a class to hold room information. This should have name and +# description attributes. +class Item: + def __init__(self, name, description): + self.name = name + self.description = description \ No newline at end of file diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index d79a175029..d33cd897d8 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,2 +1,30 @@ # Write a class to hold player information, e.g. what room they are in # currently. + +class Player: + def __init__(self, name, room): + self.name = name + self.room = room + self.bag = [] + + def add_item(self, item): + self.bag.append(item) + + def drop_item(self, index): + if len(self.bag) is 0: + print("Your bag is empty!") + else: + del self.bag[index] + + def view_bag(self): + print("\nIn your bag:") + if len(self.bag) is not 0: + for i, e in enumerate(self.bag): + print(str(i) + "-" + e) + else: + print("Your bag is empty!") + + def getRoom(self): + print('***********************************') + print('You are in: ' + self.room.name) + print('This room is: ' + self.room.description) \ No newline at end of file diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 24c07ad4c8..8f09e0d75b 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,2 +1,29 @@ # Implement a class to hold room information. This should have name and -# description attributes. \ No newline at end of file +# description attributes. +class Room: + def __init__(self, name, description, shortname, items): + self.name = name + self.shortname = shortname + self.description = description + self.n_to = None + self.w_to = None + self.s_to = None + self.e_to = None + self.items = items + + def view_items(self): + print("\nIn this room:") + if len(self.items) is not 0: + for i, e in enumerate(self.items): + print(str(i) + "-" + e) + else: + print("This room is empty!") + + def remove_item(self, index): + if len(self.items) is 0: + print("This room is empty!") + else: + del self.items[index] + + def add_item(self, item): + self.items.append(item) \ No newline at end of file diff --git a/src/mini-challenge/hangman.py b/src/mini-challenge/hangman.py index 9b73b9249d..8718b63fe3 100644 --- a/src/mini-challenge/hangman.py +++ b/src/mini-challenge/hangman.py @@ -7,6 +7,8 @@ # from a set of win/loss messages...basically, make it better! # Initial setup +import random + bodies = [ " ------\n | |\n | O\n |\n |\n |\n |\n |\n---", " ------\n | |\n | O\n | |\n | |\n |\n |\n |\n---", " ------\n | |\n | O\n | |\n | |\n | / \n |\n |\n---", @@ -15,25 +17,26 @@ " ------\n | |\n | O\n | \|/\n | |\n | / \ \n |\n |\n---" ] strikes = 0 words = [None] -file = open("word.txt", "r") +file = open("words.txt", "r") for line in file: words.append(line) file.close() -targetWord = words[random.randint(0, 100)] +targetWord = words[random.randint(0, len(words)-1)] lettersLeft = len(targetWord)-1 length = len(targetWord)-1 curWord = "_" * length -alphabet = [chr(65+x) for x in range(1, 26) ] +alphabet = [chr(65+x) for x in range(0, 26) ] # Draw body based on # of incorrect guesses -def drawBody() +def drawBody(): print(bodies[strikes]) # Replace blanks with correctly guessed letters def fillLetters( letter ): for i in range(len(targetWord)-1): if( targetWord[i : i+1]) == letter: - curWord = curWord[0: i] + letter + curWord[i: ] + global curWord + curWord = curWord[0: i] + letter + curWord[i+1: ] global lettersLeft lettersLeft -= 1 @@ -54,20 +57,30 @@ def printWord( word ): # Gameplay loop while strikes < 5 and lettersLeft > 0: letter = input("\nPlease guess a letter...") - if letter in targetWord: - print("Great!") - fillLetters(letter) + + if isinstance(letter, str) and len(letter) == 1: + if letter.upper() not in alphabet: + print("\n❌ {letter} is not a valid letter! Try again! \n") + else: + if letter in targetWord: + print("Great!") + fillLetters(letter) + else: + strikes += 1 + print( str(strikes) + " / 5 strikes" ) + + printWord(curWord) + drawBody() + alphabet.remove(letter.upper()) else: - strikes += 1 - print( strikes + " / 5 strikes" ) - printWord(curWord) - drawBody() - alphabet.remove(letter.upper()) + print("\n❌ {letter} is not a valid letter! Try again! \n") + print("Letters left:") + print(lettersLeft) printWord(alphabet) # Game over, print outcome -if lettersLeft < 0: +if lettersLeft <= 0: print("YOU WIN!!") else: print("YOU LOSE...word was " + targetWord) \ No newline at end of file