diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py index 06a830e4c8..edb77fee8f 100644 --- a/src/day-1-toy/args.py +++ b/src/day-1-toy/args.py @@ -1,5 +1,5 @@ # Experiment with positional arguments, arbitrary arguments, and keyword -# arguments. +# arguments # 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. diff --git a/src/day-1-toy/bar.txt b/src/day-1-toy/bar.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py index 77e8d66ffa..8ad38fc735 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..920fe96e4c 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -14,3 +14,8 @@ # docs for the calendar module closely. import sys +import calendar + +year = int(input("enter year:")) +month = int(input("enter month:")) +print(calendar.month(year, month)) diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 083e9b9140..6af0dbea58 100644 --- a/src/day-1-toy/comp.py +++ b/src/day-1-toy/comp.py @@ -1,13 +1,13 @@ # Write a list comprehension to produce the array [1, 2, 3, 4, 5] -y = [] +y = [i for i in range(1,6)] print (y) # Write a list comprehension to produce the cubes of the numbers 0-9: # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] -y = [] +y = [i**3 for i in range (10)] print(y) @@ -16,7 +16,7 @@ a = ["foo", "bar", "baz"] -y = [] +y = [i.upper() for i in a] print(y) @@ -26,7 +26,7 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] +y = [i for i in x if int(i) % 2 == 0] print(y) diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py index f5967611a7..aaa2797b2c 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..701d2fe61f 100644 --- a/src/day-1-toy/dicts.py +++ b/src/day-1-toy/dicts.py @@ -25,5 +25,7 @@ ] # Write a loop that prints out all the field values for all the waypoints - +for w in waypoints: + print(w['lat'], w['lon'], w['name']) # Add a new waypoint to the list +waypoints.append({'lat':1, 'lon':2, 'name':'nowhere'})# doesnt seem to add waypoint \ No newline at end of file diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index bc8e79b7cc..cf2420cf8d 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -1,12 +1,16 @@ # Use open to open file "foo.txt" for reading +file = open('foo.txt', 'r') # Print all the lines in the file +for line in file: + print(line) # Close the file - +file.close() # Use open to open file "bar.txt" for writing - +file = open('bar.txt', 'w') # Use the write() method to write three lines to the file - -# Close the file \ No newline at end of file +file.write(3) +# Close the file +file.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..844452543c 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -3,4 +3,11 @@ # 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" +def is_even(num): + if int(num) % 2 == 0: + print("even") + else: + print("odd") + +is_even(num) \ 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..fc6be3b957 100644 --- a/src/day-1-toy/lists.py +++ b/src/day-1-toy/lists.py @@ -7,23 +7,25 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -# [command here] +x.insert(3,4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -# [command here] +x.extend(y) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] -# [command here] +x.pop(4) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -# [command here] +x.insert(5,99) print(x) # Print the length of list x -# [command here] +x.count 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 i in x: + print((i * 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..7b7d5ec6b3 100644 --- a/src/day-1-toy/modules.py +++ b/src/day-1-toy/modules.py @@ -9,10 +9,11 @@ # Print out the plaform from sys: -print() +for argv in sys.argv: + print(argv) # Print out the Python version from sys: -print() +print(sys.platform) @@ -21,11 +22,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..60de120614 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -1,21 +1,45 @@ # 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): + super().__init__(lat, lon) + self.name = name + def change(self): + return "{}: latitude {}, longitude {}".format( + 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): + super().__init__(name, lat, lon) + self.size = size + self.name = name + self.difficulty = difficulty + def change(self): + return "{}: difficulty {}, size {}, latitude {}, longitude {}".format( + self.name, self.difficulty, self.size, self.lat, self.lon) # Make a new waypoint "Catacombs", 41.70505, -121.51521 +newWaypoint = Waypoint("Catacombs", 41.70505, -121.51521) # Print it -# +print(newWaypoint.change()) + # Without changing the following line, how can you make it print into something # more human-readable? +w = newWaypoint.change() print(w) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 +newGeocache = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556) # Print it--also make this print more nicely +g = newGeocache.change() print(g) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index d4bc9abb48..95760fe1be 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 %d, 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 {:.2f}, z is "{}"'.format(x, y, z)) \ No newline at end of file diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py index 3c6cb38730..32f99edb01 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:6]) # Output every element except the last one: [2, 4, 1, 7, 9] -print() +print(a[0:5]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[8:13]) \ No newline at end of file diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index ec42b0cdf8..899539d7b2 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -22,11 +22,12 @@ 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..6c1e217eb6 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,26 +1,34 @@ from room import Room +from player import Player +from item import Item, Treasure + # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", - "North of you, the cave mount beckons"), + "North of you, the cave mount beckons", []), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), '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.""", []), '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.""", []), '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.""", []), } +#Add Items +item = { + 'sword' : Item("small sword", "small sword to fight with"), + 'shield' : Item("wooden shield", "durable shild to protect you") +} # Link rooms together @@ -33,19 +41,105 @@ room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] -# -# Main -# + +#Add to item room +room['outside'].addItem(item['sword']) +room['overlook'].addItem(item['shield']) + +#treasure gold, silver # Make a new player object that is currently in the 'outside' room. +newPlayer = Player(room['outside']) +dir = "" # Write a loop that: -# +while not dir == "q": + def room_info(): # * Prints the current room name + print(newPlayer.room.name) + # * Prints the current description (the textwrap module might be useful here). + print(newPlayer.room.description) +# see items in the room + + if len( newPlayer.room.items ) == 0: + print(" nothing") + else: + print("There is an item in this room: ") + for i in newPlayer.room.items: + print(" " + str(i)) + # * Waits for user input and decides what to do. -# + dir = input("Where would you like to go? Enter n, w, e, s or q to quit") + splt_cmd = dir.split() + if len(splt_cmd) > 1: + action = splt_cmd[0] + for i in range(1, len(splt_cmd[i])): + item += splt_cmd[i] + " " + item = item.strip() + +#grabbing or dropping +if action =="g" or action == "grab": + for i in newPlayer.room.items: + if splt_cmd[1] == i.name: + i.on_grab( newPlayer ) + + cmd = input("you grabbed an item") + # else: + # print("invalid selection") + +#drop +if action == "d" or action == "drop": + for i in newPlayer.room.items: + if splt_cmd[1] == i.name: + i.on_grab( newPlayer ) + + cmd = input("you dropped an item") + # else: + # print("invalid selection") +#inventory +if cmd == "i" or cmd == "inventory": + print("inventory: ") + if len(newPlayer.items ) == 0: + print("you don't have anything in your inventory") + for i in newplayer.item: + print("\t" + str(i)) +#score +if cmd == "score": + print("score: " + str(newPlayer.score) + "\n") # If the user enters a cardinal direction, attempt to move to the room there. +if dir == "n": + if hasattr(newPlayer.room, "n_to"): + newPlayer.room = newPlayer.room.n_to + else: + print("Try another direction") +elif dir == "s": + if hasattr(newPlayer.room, "s_to"): + newPlayer.room = newPlayer.room.s_to + else: + print("Try another direction") +elif dir == "e": + if hasattr(newPlayer.room, "e_to"): + newPlayer.room = newPlayer.room.e_to + else: + print("Try another direction") +elif dir == "w": + if hasattr(newPlayer.room, "w_to"): + newPlayer.room = newPlayer.room.w_to + else: + print("Try another direction") + + # Check inventory +elif command[1] in ["i", "inventory"]: + if len(newplayer.inventory) > 0: + print("Your inventory is:") + for i in newPlayer.inventory: + print(" " + i.description) + else: + print("There is nothing in your inventory") # Print an error message if the movement isn't allowed. -# # If the user enters "q", quit the game. +elif dir == "q": + print("Thank you, come again!") +else: + print("This movement isn't allowed") \ No newline at end of file diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py new file mode 100644 index 0000000000..391deff3ce --- /dev/null +++ b/src/days-2-4-adv/item.py @@ -0,0 +1,28 @@ +class Item: + def __init__(self, name, description): + self.name = name + self.description = description + + def __str__(self): + return f"{self.name}" + + def on_grab(self, player): + print("item picked up") + # player has item + newPlayer.item.append(self) + #remove item from room + + newPlayer.room.item.remove(self) + +class Treasure(Item): + def __init__ (self, name , descrition, value): + super ().__init__(self, name, descrition) + self.value = value + self.picked_up = False + + def on_grab(self, player): + super().on_grab(player) + if self.picked_up == False: + #score updated + newPlayer.score += self.value + self.pickeup_up == True \ 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..1f820ee852 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,2 +1,7 @@ # Write a class to hold player information, e.g. what room they are in # currently. +class Player: + def __init__(self, room, inventory=[]): + self.room = room + self.inventory = inventory + self.score = 0 \ 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..1a3a2bf5fb 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,2 +1,15 @@ # 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, items=[]): + self.name = name + self.description = description + self.items = items + + + def addItem (self, item): + self.items.append(item) + + + + diff --git a/src/mini-challenge/hangman.py b/src/mini-challenge/hangman.py new file mode 100644 index 0000000000..c0532b3924 --- /dev/null +++ b/src/mini-challenge/hangman.py @@ -0,0 +1,75 @@ +# There are at least 10 "mistakes" in this Hangman game +# These could include syntax errors, logical errors, spelling errors... +# Find the mistakes and fix the game! +# +# STRETCH GOAL: If you fix all the errors, can you find a way to improve +# it? Add a cheat code, more error handling, chose randomly +# 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---", +" ------\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---" ] +strikes = 0 +words = [None] +file = open("words.txt", "r") +for line in file: + words.append(line) +file.close() +targetWord = words[random.randint(0, len(words))] +lettersLeft = len(targetWord)-1 +length = len(targetWord)-1 +curWord = "_" * length +alphabet = [chr(65+x) for x in range(0, 26) ] + +# Draw body based on # of incorrect guesses +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: + global curWord # maybe this works? + curWord = curWord[0: i] + letter + curWord[i+1: ] + global lettersLeft + lettersLeft -= 1 + +# Add spaces when displaying letters / blanks for readability +def printWord( word ): + prntWord = "" + for letter in word: + prntWord += letter + " " + print(prntWord) + +# Begin game +print( "Welcome to Hangman!" ) +printWord(curWord) +drawBody() +print("Letters left:") +printWord(alphabet) + +# Gameplay loop +while strikes < 5 and lettersLeft > 0: + letter = input("\nPlease guess a letter...") + if letter in targetWord: + print("Great!") + fillLetters(letter) + else: + strikes += 1 + print(str( strikes) + " / 5 strikes" ) + printWord(curWord) + drawBody() + alphabet.remove(letter.upper()) + print("Letters left:") + printWord(alphabet) + +# Game over, print outcome +if lettersLeft == 0: + print("YOU WIN!!") +else: + print("YOU LOSE...word was " + targetWord) \ No newline at end of file diff --git a/src/mini-challenge/words.txt b/src/mini-challenge/words.txt new file mode 100644 index 0000000000..d62f474859 --- /dev/null +++ b/src/mini-challenge/words.txt @@ -0,0 +1,80 @@ +adhesive +amuse +arson +battery +blimp +bunny +buzzcut +carjack +carriage +cashbox +cocoon +colonel +crushing +demolishment +doberman +drizzle +elephant +exclaim +fermentation +fighting +flimsy +gazelle +generation +glowing +gritty +headquarters +hearse +heart +heretical +hopper +honeybee +injured +itching +jacuzzi +jukebox +ketchup +kickoff +kleenex +lacquer +legendary +limitless +liquify +marble +mittens +mummify +mystical +necrotic +nickle +nitpick +north +orphanage +overjoy +patient +photograph +plantation +quack +queen +quickly +refugee +sizzled +smallpox +southern +squawks +taxicab +thickly +tweezer +undersea +useless +violent +vulture +walkway +warning +waxlike +wheezed +xeroxed +yawning +yellow +zephyr +zipper +zombie \ No newline at end of file