From 65497c0f44364fdbb06acf14493a424c830179a5 Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Mon, 10 Dec 2018 05:44:59 -0800 Subject: [PATCH 1/6] Initial attempt at bite 89 --- days/07-09-data-structures/code/states.py | 93 +++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 days/07-09-data-structures/code/states.py diff --git a/days/07-09-data-structures/code/states.py b/days/07-09-data-structures/code/states.py new file mode 100644 index 00000000..27cb25fb --- /dev/null +++ b/days/07-09-data-structures/code/states.py @@ -0,0 +1,93 @@ +us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', + 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', + 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', + 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', + 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', + 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', + 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', + 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', + 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', + 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', + 'New Mexico': 'NM', 'New York': 'NY', + 'North Carolina': 'NC', 'North Dakota': 'ND', + 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', + 'Pennsylvania': 'PA', 'Rhode Island': 'RI', + 'South Carolina': 'SC', 'South Dakota': 'SD', + 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', + 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', + 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY'} + +states = ['Oklahoma', 'Kansas', 'North Carolina', 'Georgia', 'Oregon', + 'Mississippi', 'Minnesota', 'Colorado', 'Alabama', + 'Massachusetts', 'Arizona', 'Connecticut', 'Montana', + 'West Virginia', 'Nebraska', 'New York', 'Nevada', 'Idaho', + 'New Jersey', 'Missouri', 'South Carolina', 'Pennsylvania', + 'Rhode Island', 'New Mexico', 'Alaska', 'New Hampshire', + 'Tennessee', 'Washington', 'Indiana', 'Hawaii', 'Kentucky', + 'Virginia', 'Ohio', 'Wisconsin', 'Maryland', 'Florida', + 'Utah', 'Maine', 'California', 'Vermont', 'Arkansas', 'Wyoming', + 'Louisiana', 'North Dakota', 'South Dakota', 'Texas', + 'Illinois', 'Iowa', 'Michigan', 'Delaware'] + +NOT_FOUND = 'N/A' + + +def get_every_nth_state(states=states, n=10): + """Return a list with every nth item (default argument n=10, so every + 10th item) of the states list above (remember: lists keep order)""" + results = [] + for i in range(len(states)): + if (i + 1) % n == 0: + results.append(states[i]) + return results + + +def get_state_abbrev(state_name, us_state_abbrev=us_state_abbrev): + """Look up a state abbreviation by querying the us_state_abbrev + dict by full state name, for instance 'Alabama' returns 'AL', + 'Illinois' returns 'IL'. + If the state is not in the dict, return 'N/A' which we stored + in the NOT_FOUND constant (takeaway: dicts are great for lookups)""" + + return us_state_abbrev.get(state_name, NOT_FOUND) + + +def get_longest_state(data): + """Receives data, which can be the us_state_abbrev dict or the states + list (see above). It returns the longest state measured by the length + of the string""" + data_list = [] + if type(data) == dict: + for key in data.keys(): + data_list.append(key) + else: + data_list = data + + longest = '' + for state in data_list: + if len(state) > len(longest): + longest = state + return longest + + +def combine_state_names_and_abbreviations(us_state_abbrev=us_state_abbrev, + states=states): + """Get the first 10 state abbreviations ('AL', 'AK', 'AZ', ...) from + the us_state_abbrev dict, and the last 10 states from the states + list (see above) and combine them into a new list without losing + alphabetical order""" + results = [] + abbrev_list = [] + for value in us_state_abbrev.values(): + abbrev_list.append(value) + + abbrev_list.sort() + + for i in range(10): + results.append(abbrev_list[i]) + + states.sort() + ten_states = states[-10:] + for i in range(10): + results.append(ten_states[i]) + return results From 0501f3f2a1b8758e493fe374aa6049418c96da9d Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Tue, 11 Dec 2018 08:06:07 -0800 Subject: [PATCH 2/6] pytest practice --- days/07-09-data-structures/code/guess.py | 88 +++++++++++++++++++ days/07-09-data-structures/code/states.py | 39 ++------ .../07-09-data-structures/code/states_test.py | 32 +++++++ days/10-12-pytest/code/mydb.py | 0 days/10-12-pytest/code/test_mydb.py | 0 5 files changed, 127 insertions(+), 32 deletions(-) create mode 100644 days/07-09-data-structures/code/guess.py create mode 100644 days/07-09-data-structures/code/states_test.py create mode 100644 days/10-12-pytest/code/mydb.py create mode 100644 days/10-12-pytest/code/test_mydb.py diff --git a/days/07-09-data-structures/code/guess.py b/days/07-09-data-structures/code/guess.py new file mode 100644 index 00000000..c9ec904a --- /dev/null +++ b/days/07-09-data-structures/code/guess.py @@ -0,0 +1,88 @@ +import random + +MAX_GUESSES = 5 +START, END = 1, 20 + + +def get_random_number(): + """Get a random number between START and END, returns int""" + return random.randint(START, END) + + +class Game: + """Number guess class, make it callable to initiate game""" + + def __init__(self): + """Init _guesses, _answer, _win to set(), get_random_number(), False""" + self._guesses = set() + self._answer = get_random_number() + self._win = False + + def guess(self): + """Ask user for input, convert to int, raise ValueError outputting + the following errors when applicable: + 'Please enter a number' + 'Should be a number' + 'Number not in range' + 'Already guessed' + If all good, return the int""" + guess = input(f'Guess a number between {START} and {END}: ') + if not guess: + raise ValueError('Please enter a number') + + try: + guess = int(guess) + except ValueError: + raise ValueError('Should be a number') + + if guess not in range(START, END+1): + raise ValueError('Number not in range') + + if guess in self._guesses: + raise ValueError('Already guessed') + + self._guesses.add(guess) + return guess + + def _validate_guess(self, guess): + """Verify if guess is correct, print the following when applicable: + {guess} is correct! + {guess} is too high + {guess} is too low + Return a boolean""" + if guess == self._answer: + print(f'{guess} is correct!') + return True + else: + high_or_low = 'low' if guess < self._answer else 'high' + print(f'{guess} is too {high_or_low}') + return False + + @property + def num_guesses(self): + return len(self._guesses) + + def __call__(self): + """Entry point / game loop, use a loop break/continue, + see the tests for the exact win/lose messaging""" + while len(self._guesses) < MAX_GUESSES: + try: + guess = self.guess() + except ValueError as ve: + print(ve) + continue + + win = self._validate_guess(guess) + if win: + guess_str = self.num_guesses == 1 and "guess" or "guesses" + print(f'It took you {self.num_guesses} {guess_str}') + self._win = True + break + else: + # else on while/for = anti-pattern? do find it useful in this case! + print(f'Guessed {MAX_GUESSES} times, answer was {self._answer}') + + +if __name__ == '__main__': + game = Game() + game() diff --git a/days/07-09-data-structures/code/states.py b/days/07-09-data-structures/code/states.py index 27cb25fb..36a76fd8 100644 --- a/days/07-09-data-structures/code/states.py +++ b/days/07-09-data-structures/code/states.py @@ -1,3 +1,5 @@ + + us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', @@ -35,11 +37,9 @@ def get_every_nth_state(states=states, n=10): """Return a list with every nth item (default argument n=10, so every 10th item) of the states list above (remember: lists keep order)""" - results = [] - for i in range(len(states)): - if (i + 1) % n == 0: - results.append(states[i]) - return results + for i, state in enumerate(states, 1): + if i % n == 0: + yield state def get_state_abbrev(state_name, us_state_abbrev=us_state_abbrev): @@ -56,18 +56,7 @@ def get_longest_state(data): """Receives data, which can be the us_state_abbrev dict or the states list (see above). It returns the longest state measured by the length of the string""" - data_list = [] - if type(data) == dict: - for key in data.keys(): - data_list.append(key) - else: - data_list = data - - longest = '' - for state in data_list: - if len(state) > len(longest): - longest = state - return longest + return max(data,key=len) def combine_state_names_and_abbreviations(us_state_abbrev=us_state_abbrev, @@ -76,18 +65,4 @@ def combine_state_names_and_abbreviations(us_state_abbrev=us_state_abbrev, the us_state_abbrev dict, and the last 10 states from the states list (see above) and combine them into a new list without losing alphabetical order""" - results = [] - abbrev_list = [] - for value in us_state_abbrev.values(): - abbrev_list.append(value) - - abbrev_list.sort() - - for i in range(10): - results.append(abbrev_list[i]) - - states.sort() - ten_states = states[-10:] - for i in range(10): - results.append(ten_states[i]) - return results + return sorted(us_state_abbrev.values())[:10] + sorted(states)[-10:] diff --git a/days/07-09-data-structures/code/states_test.py b/days/07-09-data-structures/code/states_test.py new file mode 100644 index 00000000..51ca7f9e --- /dev/null +++ b/days/07-09-data-structures/code/states_test.py @@ -0,0 +1,32 @@ +from states import (get_every_nth_state, + get_state_abbrev, + get_longest_state, + combine_state_names_and_abbreviations, + states, + us_state_abbrev, + NOT_FOUND) + + +def test_get_every_nth_state(): + expected = ['Massachusetts', 'Missouri', 'Hawaii', + 'Vermont', 'Delaware'] + assert list(get_every_nth_state()) == expected + + expected = ['Missouri', 'Vermont'] + assert list(get_every_nth_state(n=20)) == expected + +def test_get_state_abbrev(): + expected = 'WI' + assert get_state_abbrev('Wisconsin') + +def test_get_longest_state(): + correct_answers = ('North Carolina','South Carolina') + assert get_longest_state(states) in correct_answers + assert get_longest_state(us_state_abbrev) in correct_answers + +def test_combine_state_names_and_abbreviations(): + expected = ['AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', + 'South Dakota', 'Tennessee', 'Texas', 'Utah', + 'Vermont', 'Virginia', 'Washington', 'West Virginia', + 'Wisconsin', 'Wyoming'] + assert combine_state_names_and_abbreviations() == expected \ No newline at end of file diff --git a/days/10-12-pytest/code/mydb.py b/days/10-12-pytest/code/mydb.py new file mode 100644 index 00000000..e69de29b diff --git a/days/10-12-pytest/code/test_mydb.py b/days/10-12-pytest/code/test_mydb.py new file mode 100644 index 00000000..e69de29b From 3cfd56b5286ffd88d04fa30f9a886c62756ddff1 Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Mon, 17 Dec 2018 08:23:04 -0800 Subject: [PATCH 3/6] In progress --- days/10-12-pytest/code/mydb.py | 28 +++++++++++ days/10-12-pytest/code/test_mydb.py | 22 +++++++++ .../RockPaperScissors/player.py | 3 ++ .../RockPaperScissors/program.py | 48 +++++++++++++++++++ .../RockPaperScissors/roll.py | 27 +++++++++++ .../RockPaperScissors/test_program.py | 17 +++++++ 6 files changed, 145 insertions(+) create mode 100644 days/13-15-text-games/RockPaperScissors/player.py create mode 100644 days/13-15-text-games/RockPaperScissors/program.py create mode 100644 days/13-15-text-games/RockPaperScissors/roll.py create mode 100644 days/13-15-text-games/RockPaperScissors/test_program.py diff --git a/days/10-12-pytest/code/mydb.py b/days/10-12-pytest/code/mydb.py index e69de29b..583d06cf 100644 --- a/days/10-12-pytest/code/mydb.py +++ b/days/10-12-pytest/code/mydb.py @@ -0,0 +1,28 @@ +class MyDB: + def __init__(self): + self.connection = Connection() + + def connect(self, connection_string): + return self.connection + +class Connection: + def __init__(self): + self.cur = Cursor() + + def cursor(self): + return self.cur + + def close(self): + pass + +class Cursor(): + def execute(self, query): + if query == "select id from employee_db where name=John": + return 123 + elif query == "select id from employee_db where name=Tom": + return 789 + else: + return -1 + + def close(self): + pass \ No newline at end of file diff --git a/days/10-12-pytest/code/test_mydb.py b/days/10-12-pytest/code/test_mydb.py index e69de29b..989e431f 100644 --- a/days/10-12-pytest/code/test_mydb.py +++ b/days/10-12-pytest/code/test_mydb.py @@ -0,0 +1,22 @@ +from mydb import MyDB + +import pytest + +@pytest.fixture(scope="module") +def cur(): + print("Setting up") + db = MyDB() + conn = db.connect("server") + curs = conn.cursor() + yield curs + curs.close() + conn.close() + print("Closing DB") + +def test_johns_id(cur): + id = cur.execute("select id from employee_db where name=John") + assert id==123 + +def test_toms_id(cur): + id = cur.execute("select id from employee_db where name=Tom") + assert id == 789 \ No newline at end of file diff --git a/days/13-15-text-games/RockPaperScissors/player.py b/days/13-15-text-games/RockPaperScissors/player.py new file mode 100644 index 00000000..ba599324 --- /dev/null +++ b/days/13-15-text-games/RockPaperScissors/player.py @@ -0,0 +1,3 @@ +class Player(): + def __init__(self, name): + self.name = name diff --git a/days/13-15-text-games/RockPaperScissors/program.py b/days/13-15-text-games/RockPaperScissors/program.py new file mode 100644 index 00000000..d8692565 --- /dev/null +++ b/days/13-15-text-games/RockPaperScissors/program.py @@ -0,0 +1,48 @@ +from player import Player +from roll import Roll +import random + +def main(): + print_header() + + rolls = build_the_three_rolls() + + name = get_players_name() + + player1 = Player(name) + player2 = Player("computer") + + game_loop(player1, player2, rolls) + +def get_players_name(): + + player_name = input("What is your name? ") + + return player_name + +def print_header(): + print('---------------------------------') + print(' ROCK PAPER SCISSORS') + print('---------------------------------') + print() + +def build_the_three_rolls(): + rock = Roll("Rock","Scissors") + paper = Roll("Paper","Rock") + scissors = Roll("Scissors","Paper") + +def game_loop(player1, player2, rolls): + count = 1 + while count < 3: + p2_roll = random.choices("Rock","Paper","Scissors") + p1_roll = input("{}, roll: 1..2..3..".format(player1.name)) + + outcome = p1_roll.can_defeat(p2_roll) + print(outcome) + + count += 1 + + # Compute who won + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/days/13-15-text-games/RockPaperScissors/roll.py b/days/13-15-text-games/RockPaperScissors/roll.py new file mode 100644 index 00000000..49399b73 --- /dev/null +++ b/days/13-15-text-games/RockPaperScissors/roll.py @@ -0,0 +1,27 @@ +import random + +class Roll(): + + def __init__(self, name, defeats): + self.name = name + self.defeats = defeats + self.valid_rolls = ["Rock", "Paper", "Scissors"] + + def get_random(self): + return random.choices("Rock", "Paper", "Scissors") + + def choose(self): + valid_choice = False + while not valid_choice: + choice = input("Choose a roll (Rock, Paper, Scissors): ") + if choice in self.valid_rolls: + valid_choice = True + return choice + + def can_defeat(self,roll): + if (roll == self.defeats): + return True + return False + + + diff --git a/days/13-15-text-games/RockPaperScissors/test_program.py b/days/13-15-text-games/RockPaperScissors/test_program.py new file mode 100644 index 00000000..16b2c293 --- /dev/null +++ b/days/13-15-text-games/RockPaperScissors/test_program.py @@ -0,0 +1,17 @@ +import pytest + +from roll import Roll + + +@pytest.fixture(scope="module") +def rolls(): + print("Setting up") + pass + +def test_get_random(): + pass + +def test_choose(): + roll = Roll() + choice = roll.choose() + assert choice == "Rock" \ No newline at end of file From 47a94431c967d9bf04edef2c2782a5083f82d2ba Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Wed, 19 Dec 2018 06:27:14 -0800 Subject: [PATCH 4/6] Rock Paper Scissors works --- .../{program.py => RockPaperScissors.py} | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) rename days/13-15-text-games/RockPaperScissors/{program.py => RockPaperScissors.py} (83%) diff --git a/days/13-15-text-games/RockPaperScissors/program.py b/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py similarity index 83% rename from days/13-15-text-games/RockPaperScissors/program.py rename to days/13-15-text-games/RockPaperScissors/RockPaperScissors.py index d8692565..17275adc 100644 --- a/days/13-15-text-games/RockPaperScissors/program.py +++ b/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py @@ -27,14 +27,16 @@ def print_header(): print() def build_the_three_rolls(): - rock = Roll("Rock","Scissors") - paper = Roll("Paper","Rock") - scissors = Roll("Scissors","Paper") + rock = Roll('Rock') + paper = Roll('Paper') + scissors = Roll('Scissors') + valid_rolls = ['Rock','Paper','Scissors'] def game_loop(player1, player2, rolls): + round1 = Roll() count = 1 while count < 3: - p2_roll = random.choices("Rock","Paper","Scissors") + p2_roll = roll. p1_roll = input("{}, roll: 1..2..3..".format(player1.name)) outcome = p1_roll.can_defeat(p2_roll) From f0eeab88bb2a30df7281300909f2d8fc68eca05f Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Fri, 21 Dec 2018 06:00:23 -0800 Subject: [PATCH 5/6] Rock Paper Scissor completed --- .../RockPaperScissors/RockPaperScissors.py | 47 ++++++++++++++----- .../RockPaperScissors/player.py | 1 + .../RockPaperScissors/roll.py | 20 ++------ 3 files changed, 42 insertions(+), 26 deletions(-) diff --git a/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py b/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py index 17275adc..325d7e79 100644 --- a/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py +++ b/days/13-15-text-games/RockPaperScissors/RockPaperScissors.py @@ -27,22 +27,47 @@ def print_header(): print() def build_the_three_rolls(): - rock = Roll('Rock') - paper = Roll('Paper') - scissors = Roll('Scissors') - valid_rolls = ['Rock','Paper','Scissors'] + rock = Roll('rock') + paper = Roll('paper') + scissors = Roll('scissors') + rolls = [rock, paper, scissors] + return rolls + +def get_player_roll(): + valid_choice = False + while not valid_choice: + choice = input("Choose Rock, Paper, or Scissors: ").lower() + if choice == 'rock': + return Roll('rock') + elif choice == 'paper': + return Roll('paper') + elif choice == 'scissors': + return Roll('scissors') + + def game_loop(player1, player2, rolls): - round1 = Roll() count = 1 - while count < 3: - p2_roll = roll. - p1_roll = input("{}, roll: 1..2..3..".format(player1.name)) + while player1.score < 3 and player2.score < 3: + p2_roll = random.choice(rolls) + p1_roll = get_player_roll() + win = p1_roll.can_defeat(p2_roll) + if win: + player1.score += 1 + print("{} {} {}. {} wins!".format(p1_roll.name, p1_roll.action, p2_roll.name, player1.name)) + elif p2_roll.name == p1_roll.name: + print("it's a tie. Try again") + else: + player2.score += 1 + print("{} {} {}. Computer wins.".format(p2_roll.name, p2_roll.action, p1_roll.name)) - outcome = p1_roll.can_defeat(p2_roll) - print(outcome) + print("{}: {} {}: {}".format(player1.name, player1.score, player2.name, player2.score)) - count += 1 + if player1.score == 3: + print("Congrats, {}. You are the champion!".format(player1.name)) + else: + print(" ") + print("Sorry. Computer wins the match.") # Compute who won diff --git a/days/13-15-text-games/RockPaperScissors/player.py b/days/13-15-text-games/RockPaperScissors/player.py index ba599324..dbc1cd75 100644 --- a/days/13-15-text-games/RockPaperScissors/player.py +++ b/days/13-15-text-games/RockPaperScissors/player.py @@ -1,3 +1,4 @@ class Player(): def __init__(self, name): self.name = name + self.score = 0 diff --git a/days/13-15-text-games/RockPaperScissors/roll.py b/days/13-15-text-games/RockPaperScissors/roll.py index 49399b73..0de112b9 100644 --- a/days/13-15-text-games/RockPaperScissors/roll.py +++ b/days/13-15-text-games/RockPaperScissors/roll.py @@ -2,24 +2,14 @@ class Roll(): - def __init__(self, name, defeats): + def __init__(self, name): self.name = name - self.defeats = defeats - self.valid_rolls = ["Rock", "Paper", "Scissors"] - - def get_random(self): - return random.choices("Rock", "Paper", "Scissors") - - def choose(self): - valid_choice = False - while not valid_choice: - choice = input("Choose a roll (Rock, Paper, Scissors): ") - if choice in self.valid_rolls: - valid_choice = True - return choice + action = {'rock': 'smashes','paper':'covers','scissors':'cuts'} + self.action = action[name] def can_defeat(self,roll): - if (roll == self.defeats): + win = {'rock': 'scissors','paper':'rock','scissors':'paper'} + if (roll.name == win[self.name]): return True return False From 71330c54ecfb1e51852760c5f2847f8035643702 Mon Sep 17 00:00:00 2001 From: Rachel-Hill Date: Sun, 30 Dec 2018 09:52:28 -0800 Subject: [PATCH 6/6] itertools --- .../list-comprehensions-generators.ipynb | 298 +++++++++++++++--- days/19-21-itertools/bite17.py | 10 + days/19-21-itertools/bite64.py | 14 + days/19-21-itertools/bite65.py | 28 ++ .../traffic_lights/traffic_lights.py | 17 + 5 files changed, 328 insertions(+), 39 deletions(-) create mode 100644 days/19-21-itertools/bite17.py create mode 100644 days/19-21-itertools/bite64.py create mode 100644 days/19-21-itertools/bite65.py create mode 100644 days/19-21-itertools/traffic_lights/traffic_lights.py diff --git a/days/16-18-listcomprehensions-generators/list-comprehensions-generators.ipynb b/days/16-18-listcomprehensions-generators/list-comprehensions-generators.ipynb index 5c675528..a7a7c00d 100644 --- a/days/16-18-listcomprehensions-generators/list-comprehensions-generators.ipynb +++ b/days/16-18-listcomprehensions-generators/list-comprehensions-generators.ipynb @@ -16,7 +16,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 40, "metadata": {}, "outputs": [], "source": [ @@ -46,7 +46,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -55,7 +55,7 @@ "['pybites', 'mike', 'bob', 'julian', 'tim', 'sara', 'guido']" ] }, - "execution_count": 2, + "execution_count": 1, "metadata": {}, "output_type": "execute_result" } @@ -67,7 +67,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 6, "metadata": {}, "outputs": [ { @@ -98,7 +98,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -107,7 +107,7 @@ "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']" ] }, - "execution_count": 4, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -119,7 +119,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 12, "metadata": {}, "outputs": [ { @@ -128,7 +128,7 @@ "['Mike', 'Bob', 'Julian', 'Guido']" ] }, - "execution_count": 5, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -152,7 +152,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 13, "metadata": {}, "outputs": [ { @@ -161,7 +161,7 @@ "['Mike', 'Bob', 'Julian', 'Guido']" ] }, - "execution_count": 6, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -173,7 +173,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -191,7 +191,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 18, "metadata": {}, "outputs": [ { @@ -200,7 +200,7 @@ "['the', 'boy', 'who', 'lived', 'mr.']" ] }, - "execution_count": 8, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } @@ -213,7 +213,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 19, "metadata": {}, "outputs": [ { @@ -222,7 +222,7 @@ "[('the', 202), ('he', 136), ('a', 108), ('and', 100), ('to', 93)]" ] }, - "execution_count": 9, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } @@ -241,7 +241,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 20, "metadata": {}, "outputs": [ { @@ -250,7 +250,7 @@ "True" ] }, - "execution_count": 10, + "execution_count": 20, "metadata": {}, "output_type": "execute_result" } @@ -268,7 +268,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 21, "metadata": {}, "outputs": [], "source": [ @@ -277,7 +277,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -286,7 +286,7 @@ "False" ] }, - "execution_count": 12, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } @@ -297,7 +297,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 23, "metadata": {}, "outputs": [ { @@ -306,7 +306,7 @@ "True" ] }, - "execution_count": 13, + "execution_count": 23, "metadata": {}, "output_type": "execute_result" } @@ -324,7 +324,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 24, "metadata": {}, "outputs": [ { @@ -333,7 +333,7 @@ "['a', 'about', 'above', 'across', 'after']" ] }, - "execution_count": 14, + "execution_count": 24, "metadata": {}, "output_type": "execute_result" } @@ -346,7 +346,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 25, "metadata": {}, "outputs": [ { @@ -355,7 +355,7 @@ "['boy', 'lived', 'mr', 'mrs', 'dursley']" ] }, - "execution_count": 15, + "execution_count": 25, "metadata": {}, "output_type": "execute_result" } @@ -367,7 +367,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 26, "metadata": {}, "outputs": [ { @@ -376,7 +376,7 @@ "False" ] }, - "execution_count": 16, + "execution_count": 26, "metadata": {}, "output_type": "execute_result" } @@ -394,7 +394,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 27, "metadata": {}, "outputs": [ { @@ -407,7 +407,7 @@ " ('professor', 30)]" ] }, - "execution_count": 17, + "execution_count": 27, "metadata": {}, "output_type": "execute_result" } @@ -442,7 +442,7 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 37, "metadata": {}, "outputs": [], "source": [ @@ -455,7 +455,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 38, "metadata": {}, "outputs": [ { @@ -464,7 +464,7 @@ "0" ] }, - "execution_count": 19, + "execution_count": 38, "metadata": {}, "output_type": "execute_result" } @@ -475,7 +475,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 39, "metadata": {}, "outputs": [ { @@ -782,14 +782,234 @@ }, { "cell_type": "code", - "execution_count": 32, + "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',\n", " 'julian sequeira', 'sandra bullock', 'keanu reeves',\n", " 'julbob pybites', 'bob belderbos', 'julian sequeira',\n", - " 'al pacino', 'brad pitt', 'matt damon', 'brad pitt']" + " 'al pacino', 'brad pitt', 'matt damon', 'brad pitt']\n" + ] + }, + { + "cell_type": "code", + "execution_count": 119, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Schwarzenegger Arnold',\n", + " 'Baldwin Alec',\n", + " 'Belderbos Bob',\n", + " 'Sequeira Julian',\n", + " 'Bullock Sandra',\n", + " 'Reeves Keanu',\n", + " 'Pybites Julbob',\n", + " 'Belderbos Bob',\n", + " 'Sequeira Julian',\n", + " 'Pacino Al',\n", + " 'Pitt Brad',\n", + " 'Damon Matt',\n", + " 'Pitt Brad']" + ] + }, + "execution_count": 119, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def reverse_first_last_names(name):\n", + " first, last = name.title().split()\n", + " return f'{last} {first}'\n", + "\n", + "[reverse_first_last_names(name) for name in NAMES]" + ] + }, + { + "cell_type": "code", + "execution_count": 126, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[['Arnold', 'Schwarzenegger'],\n", + " ['Alec', 'Baldwin'],\n", + " ['Bob', 'Belderbos'],\n", + " ['Julian', 'Sequeira'],\n", + " ['Sandra', 'Bullock'],\n", + " ['Keanu', 'Reeves'],\n", + " ['Julbob', 'Pybites'],\n", + " ['Bob', 'Belderbos'],\n", + " ['Julian', 'Sequeira'],\n", + " ['Al', 'Pacino'],\n", + " ['Brad', 'Pitt'],\n", + " ['Matt', 'Damon'],\n", + " ['Brad', 'Pitt']]" + ] + }, + "execution_count": 126, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "name_pairs = [name.title().split() for name in NAMES]\n", + "name_pairs" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [], + "source": [ + "def reverse_name_gen(NAMES=NAMES):\n", + " name_pairs = [name.title().split() for name in NAMES]\n", + " for pair in name_pairs:\n", + " yield pair[1]+\", \"+pair[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Schwarzenegger, Arnold',\n", + " 'Baldwin, Alec',\n", + " 'Belderbos, Bob',\n", + " 'Sequeira, Julian',\n", + " 'Bullock, Sandra',\n", + " 'Reeves, Keanu',\n", + " 'Pybites, Julbob',\n", + " 'Belderbos, Bob',\n", + " 'Sequeira, Julian',\n", + " 'Pacino, Al',\n", + " 'Pitt, Brad',\n", + " 'Damon, Matt',\n", + " 'Pitt, Brad']" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reverse_names = list(reverse_name_gen())\n", + "reverse_names" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Schwarzenegger, Arnold',\n", + " 'Baldwin, Alec',\n", + " 'Belderbos, Bob',\n", + " 'Sequeira, Julian',\n", + " 'Bullock, Sandra',\n", + " 'Reeves, Keanu',\n", + " 'Pybites, Julbob',\n", + " 'Belderbos, Bob',\n", + " 'Sequeira, Julian',\n", + " 'Pacino, Al',\n", + " 'Pitt, Brad',\n", + " 'Damon, Matt',\n", + " 'Pitt, Brad']" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reverse_name = [name[1]+\", \"+name[0] for name in new_names]\n", + "reverse_name" + ] + }, + { + "cell_type": "code", + "execution_count": 137, + "metadata": {}, + "outputs": [], + "source": [ + "def gen_pairs(name_pairs=name_pairs):\n", + " for name in name_pairs: \n", + " rand_name=random.choice(name_pairs)\n", + " yield name[0]+' teams up with '+rand_name[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 129, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "('Arnold teams up with Bob',\n", + " 'Alec teams up with Matt',\n", + " 'Bob teams up with Brad',\n", + " 'Julian teams up with Bob',\n", + " 'Sandra teams up with Keanu',\n", + " 'Keanu teams up with Bob',\n", + " 'Julbob teams up with Alec',\n", + " 'Bob teams up with Brad',\n", + " 'Julian teams up with Keanu',\n", + " 'Al teams up with Bob',\n", + " 'Brad teams up with Brad',\n", + " 'Matt teams up with Keanu',\n", + " 'Brad teams up with Arnold')" + ] + }, + "execution_count": 129, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pair = tuple(gen_pairs())\n", + "pair\n" + ] + }, + { + "cell_type": "code", + "execution_count": 138, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Arnold teams up with Al\n", + "Alec teams up with Bob\n", + "Bob teams up with Keanu\n", + "Julian teams up with Matt\n", + "Sandra teams up with Keanu\n", + "Keanu teams up with Julian\n", + "Julbob teams up with Matt\n", + "Bob teams up with Alec\n", + "Julian teams up with Julian\n", + "Al teams up with Julbob\n" + ] + } + ], + "source": [ + "pairs = gen_pairs()\n", + "for _ in range(10):\n", + " print(next(pairs))" ] }, { @@ -1048,9 +1268,9 @@ ], "metadata": { "kernelspec": { - "display_name": "venv", + "display_name": "Python 3", "language": "python", - "name": "venv" + "name": "python3" }, "language_info": { "codemirror_mode": { @@ -1062,7 +1282,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.1" + "version": "3.7.0" } }, "nbformat": 4, diff --git a/days/19-21-itertools/bite17.py b/days/19-21-itertools/bite17.py new file mode 100644 index 00000000..0ec6dc81 --- /dev/null +++ b/days/19-21-itertools/bite17.py @@ -0,0 +1,10 @@ +from itertools import combinations +#friends, team_size=2, order_does_matter=True + +def friends_teams(friends, team_size=2, order_does_matter=False): + teams=combinations(friends,2) + return teams + +if __name__ == '__main__': + friends = 'Bob Dante Julian Martin'.split() + print(list(friends_teams(friends))) diff --git a/days/19-21-itertools/bite64.py b/days/19-21-itertools/bite64.py new file mode 100644 index 00000000..7b8d8cf2 --- /dev/null +++ b/days/19-21-itertools/bite64.py @@ -0,0 +1,14 @@ +from itertools import zip_longest + +names = 'Tim Bob Julian Carmen Sofia Mike Kim Andre'.split() +locations = 'DE ES AUS NL BR US'.split() +confirmed = [False, True, True, False, True] + + +def get_attendees(): + for participant in zip_longest(names, locations, confirmed, fillvalue='-'): + print(participant) + + +if __name__ == '__main__': + get_attendees() diff --git a/days/19-21-itertools/bite65.py b/days/19-21-itertools/bite65.py new file mode 100644 index 00000000..44132d24 --- /dev/null +++ b/days/19-21-itertools/bite65.py @@ -0,0 +1,28 @@ +from itertools import permutations +import os +import urllib.request + +# PREWORK +DICTIONARY = os.path.join('/tmp', 'dictionary.txt') +urllib.request.urlretrieve('http://bit.ly/2iQ3dlZ', DICTIONARY) + +with open(DICTIONARY) as f: + dictionary = set([word.strip().lower() for word in f.read().split()]) + + +def get_possible_dict_words(draw): + """Get all possible words from a draw (list of letters) which are + valid dictionary words. Use _get_permutations_draw and provided + dictionary""" + perms=_get_permutations_draw(draw) + words=[] + for combos in perms: + for combo in combos: + if ''.join(combo).lower() in dictionary: + words.append(''.join(combo).lower()) + return words + +def _get_permutations_draw(draw): + """Helper to get all permutations of a draw (list of letters), hint: + use itertools.permutations (order of letters matters)""" + return [list(permutations(draw,i)) for i in range(2,len(draw)+1)] \ No newline at end of file diff --git a/days/19-21-itertools/traffic_lights/traffic_lights.py b/days/19-21-itertools/traffic_lights/traffic_lights.py new file mode 100644 index 00000000..4923de2e --- /dev/null +++ b/days/19-21-itertools/traffic_lights/traffic_lights.py @@ -0,0 +1,17 @@ +import itertools +import time +import random + +yellow_duration=1 +duration=1 +colors = 'Green Yellow Red'.split() +rotation=itertools.cycle(colors) +while True: + color=next(rotation) + if color=='Yellow': + duration=yellow_duration + elif color=='Red': + duration=random.randint(1,3) + + print(f'{color} - {duration} seconds') + time.sleep(duration)