Merge remote-tracking branch 'youngjin/master'

This commit is contained in:
Nico Schottelius 2020-06-26 15:57:32 +02:00
commit a0012ef6c4
16 changed files with 860 additions and 0 deletions

View file

@ -1,3 +1,84 @@
* 2020-06-17
*** Python #11:
**** DONE Lecture content
CLOSED: [2020-06-17 수 22:24]
- Same structure as "Python #2"
- Exercise 44
**** Lecture material
- Available on https://cloud.ungleich.ch/s/435FyfrQyEq6oF3
* 2020-06-15
*** DONE Python #10:
CLOSED: [2020-06-15 월 23:55]
**** Lecture content
- Same structure as "Python #2"
- Exercise 43
**** Lecture material
- Available on https://cloud.ungleich.ch/s/435FyfrQyEq6oF3
* 2020-06-12
*** Python #9:
**** DONE Lecture content
CLOSED: [2020-06-12 금 22:43]
- Same structure as "Python #2"
- Exercise 42
- Review all previous exercises, ensure you understand them
**** Lecture material
- Available on https://cloud.ungleich.ch/s/435FyfrQyEq6oF3
* 2020-06-10
*** Python #8:
**** DONE Lecture content
CLOSED: [2020-06-11 목 00:00]
- Same structure as "Python #2"
- Exercises 40-41
**** Lecture material
- Available on https://cloud.ungleich.ch/s/435FyfrQyEq6oF3
* 2020-06-08
*** Python #7:
**** DONE Lecture content
CLOSED: [2020-06-08 월 22:49]
- Same structure as "Python #2"
- Exercises 37-39
**** Lecture material
- Available on https://cloud.ungleich.ch/s/435FyfrQyEq6oF3
* 2020-06-01
*** Python applying learnings from 1..6
**** DONE Lecture notes
CLOSED: [2020-06-02 화 11:21]
- Previous topics covered:
- Printing
- Formatting
- Variables
- Escape Sequences
- Inputting text
- Reading arguments / using argv
- Reading files
- Defining methods
- Boolean logic
- Branching using if/else/elif
- Loops: for/while
- Today we write a calculator that saves results in a file in python
- How it works in general
You read the input until you read a line that only contains a
"q". Every input line consists of numbers separated by a
space. For instance "4 5 9". You will need to .split() the
input.
- Steps
- Create a python script named "calc.py"
- It takes 1 command line argument (argv), which is the filename
- We will store the calculations *and* results in this file
- Create a method named "input_and_calculate_one_line"
- It does not have any arguments
- It reads one line via *input*
- It splits the input (let's say "4 5 9" => [ "4", "5", "9") ])
- It calculates the result (f.i. 4+5+9 = 18) and stores it in
a variable (use *sum* over the *list*)
- It returns a string of the format "4 + 5 + 9 = 18"
- If the line only contains a "q" it return "" (an empty string)
- Create a method named "editor" that takes a filename as an argument
- It opens the file for writing
- It uses input_and_calculate_one_line in a while loop
- while the return result is not "", we append the string to
the file
- When the return result is "", the function exits
* 2020-05-29 * 2020-05-29
*** Python #6: *** Python #6:
**** DONE Lecture content **** DONE Lecture content

View file

@ -0,0 +1,45 @@
import sys
a_py_file, a_calc_file = sys.argv
def input_and_calculate_one_line():
l_input_array = list()
l_s_result = ""
l_input_string_num = 0
l_input_string = input("""Only numbers and spaces are allowed.
'q' is exit.
> """).split()
if "q" != l_input_string[0] or 1 != len(l_input_string):
try:
for i in l_input_string:
l_input_string_num += 1
l_input_array.append(int(i))
if l_input_string_num != len(l_input_string):
l_s_result += f"{i} + "
else:
l_s_result += f"{i} = "
l_result = sum(l_input_array)
l_s_result += f"{l_result}"
except:
l_s_result = f"input error : input string = {l_input_string}"
print(l_s_result)
return l_s_result
def editor(p_calc_file):
l_calc_result = open(p_calc_file, 'w')
l_calc_result.write("")
l_calc_result.close()
while True:
l_s_result = input_and_calculate_one_line()
if "" != l_s_result:
l_calc_result = open(p_calc_file, 'a')
l_calc_result.write(f"""{l_s_result}\n""")
l_calc_result.close()
else:
exit(0)
editor(a_calc_file)

View file

@ -0,0 +1,23 @@
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(' '.join(stuff)) # what? cool!
print('#'.join(stuff[3:5])) # super stellar!

View file

@ -0,0 +1,65 @@
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
'Texas': 'TX'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville',
'Gyeonggi-do': 'Sungnam',
'Chungcheongbuk-do': 'Cheongju'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
cities['TX'] = 'Houston'
# print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])
# print some states
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")

View file

@ -0,0 +1,58 @@
#mystuff = {'apple': "I AM APPLES!"}
#print(mystuff['apple'])
#
#import mystuff
#mystuff.apple()
#
#import mystuff
#
#mystuff.apple()
#print(mystuff.tangerine)
#
#mystuff['apple'] # get apple from dict
#mystuff.apple() # get apple from the module
#mystuff.tangerine # same thing, it's just a variable
#
#class MyStuff(object):
#
# def __init__(self):
# self.tangerine = "And now a thousand years between"
#
# def apple(self):
# print("I AM CLASSY APPLES!")
#
#thing = MyStuff()
#thing.apple()
#print(thing.tangerine)
#
## dict style
#mystuff['apples']
#
## module style
#mystuff.apples()
#print(mystuff.tangerine)
#
## class style
#thing = MyStuff()
#thing.apples()
#print(thing.tangerine)
#
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around tha family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

View file

@ -0,0 +1,84 @@
import random
from urllib.request import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
"class %%% has-a __init__ that takes self and *** params.",
"class %%%(object):\n\tdef ***(self, @@@)":
"class %%% has-a function *** that takes self and @@@ params.",
"*** = %%%()":
"Set *** to an instance of class %%%.",
"***.***(@@@)":
"From *** get the *** function, call it with params self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
# do they want to drill phrases first
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
else:
PHRASE_FIRST = False
# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(str(word.strip(), encoding="utf-8"))
def convert(snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0, snippet.count("@@@")):
param_count = random.randint(1,3)
param_names.append(', '.join(
random.sample(WORDS, param_count)))
for sentence in snippet, phrase:
# this is how you duplicate a list or string
result = sentence[:]
# fake class names
for word in class_names:
result = result.replace("%%%", word, 1)
# fake other names
for word in other_names:
result = result.replace("***", word, 1)
# fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until they hit CTRL-D
try:
while True:
snippets = list(PHRASES.keys())
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print(question)
input("> ")
print(f"ANSWER: {answer}\n\n")
except EOFError:
print("\nBye")

View file

@ -0,0 +1,94 @@
## Animal is parents
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Animal is parents and Dog is child
## Dog is-a Animal and has-a __init__ that takes self and name parameters
class Dog(Animal):
def __init__(self, name):
## Dos has-a name
self.name = name
## Animal is parents and Cat is child
## Cat is-a Animal and has-a __init__ that takes self and name parameters
class Cat(Animal):
def __init__(self, name):
## Cat has-a name
self.name = name
## Person is parents
## Person is-a object and has-a __init__ that takes self and name parameters
class Person(object):
def __init__(self, name):
## Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
## Persion is parents and Employee is child
## Employee is-a Person and has-a __init__ that takes self and name parameters
class Employee(Person):
def __init__(self, name, salary):
## ?? hmm what is this strange magic?
## From super, get the __init__ function, and call it with parameters self, name
super(Employee, self).__init__(name)
## Employee has-a salary
self.salary = salary
## Fish is parents
## Fish is-a object
class Fish(object):
pass
## Fish is parents and Salmon is child
## Salmon is-a Fish
class Salmon(Fish):
pass
## Fish is parents and Halibut is child
## Halibut is-a Fish
class Halibut(Fish):
pass
## Set rover to an instance of class Dog
## rover is-a Dog that has-a name is-a Rover
rover = Dog("Rover")
## Set satan to an instance of class Cat
## stan is-a cat that has-a name is-a Satan
satan = Cat("Satan")
## Set mary to an instance of class Person
## mary is-a Person that has-a name is-a Mary
mary = Person("Mary")
## From mary, get the pet attribute, and set it to satan
## mary's pet is-a cat that has-a name that is-a Satan
mary.pet = satan
## Set frank to an instance of class Employee
## frank is-a Employee and salary is-a 120000
frank = Employee("Frank", 120000)
## From frank, get the pet attribute, and set it to rover
## frank's pet is-a dog that has-a name that is-a Rover
frank.pet = rover
## Set flipper to an instance of class Fish
## flipper is-a Fish
flipper = Fish()
## Set crouse to an instance of class Salmon
## crouse is-a Salmon
crouse = Salmon()
## Set harry to an instance of class Halibut
## harry is-a Halibut
harry = Halibut()

View file

@ -0,0 +1,266 @@
from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This scene is not yet configured.")
print("Subclass it and implement enter().")
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your Mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this.",
"You're worse than your Dad's jokes."
]
def enter(self):
print(Death.quips[randint(0, len(self.quips)-1)])
exit(1)
class CentralCorridor(Scene):
def enter(self):
print(dedent("""
The Gothons of Planet Percal #25 have invaded your ship and
destroyed your entire crew. You are the last surviving
member and your last mission is to get the neutron destruct
bomb from the Weapons Armory, put it in the bridge, and
blow the ship up after getting into an escape pod.
You're running down the central corridor to the Weapons
Armory when a Gothon jumps out, red scaly skin, dark grimy
teeth, and evil clown costume flowing around his hate
filled body. He's blocking the door to the Armory and
about to pull a weapon to blast you.
"""))
action = input("> ")
if action == "shoot!":
print(dedent("""
Quick on the draw you yank out your blaster and fire
it at the Gothon. His clown costume is flowing and
moving around his body, which throws off your aim.
Your laser hits his costume but misses him entirely.
This completely ruins his brand new costume his mother
bought him, which makes him fly into an insane rage
and blast you repeatedly in the face until you are
dead. Then he eats you.
"""))
return 'death'
elif action == "dodge!":
print(dedent("""
Like a world class boxer you dodge, weave, slip and
slide right as the Gothon's blaster cranks a laser
past your head. In the middle of your artful dodge
your foot slips and you bang your head on the metal
wall and pass out. You wake up shortly after only to
die as the Gothon stomps on your head and eats you.
"""))
return 'death'
elif action == "tell a joke" or int(action) == 0:
print(dedent("""
Lucky for you they made you learn Gothon insults in
the academy. You tell the one Gothon joke you know:
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
fur fvgf nebhaq gur ubhfr. The Gothon stops, tries
not to laugh, then busts out laughing and can't move.
While he's laughing you run up and shoot him square in
the head putting him down, then jump through the
Weapon Armory door.
"""))
return 'laser_weapon_armory'
else:
print("DOES NOT COMPUTE!")
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print(dedent("""
You do a dive roll into the Weapon Armory, crouch and scan
the room for more Gothons that might be hiding. It's dead
quiet, too quiet. You stand up and run to the far side of
the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to
get the bomb out. If you get the code wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
"""))
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
guess = input("[keypad]> ")
guesses = 0
while guess != code and guesses < 9:
print("BZZZZEDDD!")
guesses += 1
guess = input("[keypad]> ")
if guess == code or int(guess) == 0:
print(dedent("""
The container clicks open and the seal breaks, letting
gas out. You grab the neutron bomb and run as fast as
you can to the bridge where you must place it in the
right spot.
"""))
return 'the_bridge'
else:
print(dedent("""
The lock buzzes one last time and then you hear a
sickening melting sound as the mechanism is fused
together. You decide to sit there, and finally the
Gothons blow up the ship from their ship and you die.
"""))
return 'death'
class TheBridge(Scene):
def enter(self):
print(dedent("""
You burst onto the Bridge with the netron destruct bomb
under your arm and surprise 5 Gothons who are trying to
take control of the ship. Each of them has an even uglier
clown costume than the last. They haven't pulled their
weapons out yet, as they see the active bomb under your
arm and don't want to set it off.
"""))
action = input("> ")
if action == "throw the bomb":
print(dedent("""
In a panic you throw the bomb at the group of Gothons
and make a leap for the door. Right as you drop it a
Gothon shoots you right in the back killing you. As
you die you see another Gothon frantically try to
disarm the bomb. You die knowing they will probably
blow up when it goes off.
"""))
return 'death'
elif action == "slowly place the bomb" or int(action) == 0:
print(dedent("""
You point your blaster at the bomb under your arm and
the Gothons put their hands up and start to sweat.
You inch backward to the door, open it, and then
carefully place the bomb on the floor, pointing your
blaster at it. You then jump back through the door,
punch the close button and blast the lock so the
Gothons can't get out. Now that the bomb is placed
you run to the escape pod to get off this tin can.
"""))
return 'escape_pod'
else:
print("DOES NOT COMPUTE!")
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print(dedent("""
You rush through the ship desperately trying to make it to
the escape pod before the whole ship explodes. It seems
like hardly any Gothons are on the ship, so your run is
clear of interference. You get to the chamber with the
escape pods, and now need to pick one to take. Some of
them could be damaged but you don't have time to look.
There's 5 pods, which one do you take?
"""))
good_pod = randint(1,5)
guess = input("[pod #]> ")
if int(guess) != good_pod:
print(dedent(f"""
You jump into pod {guess} and hit the eject button.
The pod escapes out into the void of space, then
implodes as the hull ruptures, crushing your body into
jam jelly.
"""))
return 'death'
elif int(guess) == 0:
print(dedent(f"""
You jump into pod {guess} and hit the eject button.
The pod easily slides out into space heading to the
planet below. As it flies to the planet, you look
back and see your ship implode then explode like a
bright star, taking out the Gothon ship at the same
time. You won!
"""))
return 'finished'
else:
print(dedent(f"""
You jump into pod {guess} and hit the eject button.
The pod easily slides out into space heading to the
planet below. As it flies to the planet, you look
back and see your ship implode then explode like a
bright star, taking out the Gothon ship at the same
time. You won!
"""))
return 'finished'
class Finished(Scene):
def enter(self):
print("You won! Good job.")
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

View file

@ -0,0 +1,13 @@
class Parent(object):
def implicit(self):
print("PARENT implicit()")
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()

View file

@ -0,0 +1,15 @@
class Parent(object):
def override(self):
print("PARENT override()")
class Child(Parent):
def override(self):
print("CHILD override()")
dad = Parent()
son = Child()
dad.override()
son.override()

View file

@ -0,0 +1,17 @@
class Parent(object):
def altered(self):
print("PARENT altered()")
class Child(Parent):
def altered(self):
print("CHILD, BEFORE PARENT altered()")
super(Child, self).altered()
print("CHILD, AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.altered()
son.altered()

View file

@ -0,0 +1,32 @@
class Parent(object):
def override(self):
print("PARENT override()")
def implicit(self):
print("PARENT implicit()")
def altered(self):
print("PARENT altered()")
class Child(Parent):
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, BEFORE PARENT altered()")
super(Child, self).altered()
print("CHILD, AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()

View file

@ -0,0 +1,32 @@
class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, BEFORE OTHER altered()")
self.other.altered()
print("CHILD, AFTER OTHER altered()")
son = Child()
son.implicit()
son.override()
son.altered()

View file

@ -0,0 +1,5 @@
def apple():
print("I AM APPLES!")
# this is just a variable
tangerine = "Living reflection of a dream"

View file

@ -0,0 +1 @@
input error : input string = ['1', 'q']

View file

@ -1,4 +1,33 @@
* 2020-06-17
** note
- ex44.py
- none
* 2020-06-15
** note
- ex43.py
- none
* 2020-06-12
** note
- ex42.py
- MRO(method resolution order)
* 2020-06-10
** note
- ex40.py
- none
- ex41.py
- none
* 2020-06-08
** note
- ex37.py
- none
- ex38.py
- ten_things.split(' ') == split(ten_things, ' ')
- more_stuff.pop() == pop(more_stuff)
- stuff.append(next_one) == append(stuff, next_one)
- ex39.py
- dictionaries do not use index number to search a key or a value.
* 2020-05-29 * 2020-05-29
** note
- ex32.py - ex32.py
- remove, insert, index, append, '+' and del - remove, insert, index, append, '+' and del
- ex33.py - ex33.py