diff --git a/.github/disabled-workflows/formatter.yml b/.github/disabled-workflows/formatter.yml deleted file mode 100644 index 724ce731..00000000 --- a/.github/disabled-workflows/formatter.yml +++ /dev/null @@ -1,25 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: Black Code Formatter -# Controls when the action will run. Triggers the workflow on push or pull request -# events but only for the master branch -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "build" - black-format: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - name: Black Code Formatter - uses: lgeiger/black-action@v1.0.1 - - diff --git a/.github/workflows/disabled/python-lint.yml b/.github/workflows/disabled/python-lint.yml new file mode 100644 index 00000000..308b56a8 --- /dev/null +++ b/.github/workflows/disabled/python-lint.yml @@ -0,0 +1,29 @@ +# Uses (Lintly): https://github.com/grantmcconnaughey/Lintly +# Submits code reviews based on flake8 output +name: Python (Lintly) + +on: pull_request + +jobs: + lint-python: + name: Lint Python with flake8 + runs-on: ubuntu-latest + + steps: + - name: Check out Git repository + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: '3.x' + + # Install flake8 and Lintly + - name: Install Python dependencies + run: pip install flake8 lintly + + # Run Lintly with flake8 + - name: Lint with flake8 + run: flake8 | lintly --commit-sha=${{ github.event.pull_request.head.sha }} + env: + LINTLY_API_KEY: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml deleted file mode 100644 index cf4467bd..00000000 --- a/.github/workflows/pull_request.yml +++ /dev/null @@ -1,22 +0,0 @@ -# Uses https://github.com/marketplace/actions/lintly-flake8?version=v1.0 -name: Python Style (PR) - -on: - pull_request: - branches: [ master ] - -jobs: - check-style: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Lintly-Flake8 - uses: grantmcconnaughey/lintly-flake8-github-action@v1.0 - with: - # The GitHub API token to create reviews with - token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml deleted file mode 100644 index 0e15d291..00000000 --- a/.github/workflows/push.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Python Style (Push) - -on: - push: - branches: [ master ] - -jobs: - check-style: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Lint with flake8 - run: | - pip install flake8 - flake8 . \ No newline at end of file diff --git a/.github/workflows/python-format.yml b/.github/workflows/python-format.yml new file mode 100644 index 00000000..0eac2193 --- /dev/null +++ b/.github/workflows/python-format.yml @@ -0,0 +1,33 @@ +# Uses (Lint Action): https://github.com/marketplace/actions/lint-action#supported-tools +# Creates annotations from linting problems +# Autofixes problems if possible (it's a black formatter) +name: Python (Lint Action) + +on: pull_request + +jobs: + format-lint-python: + name: Format Python with black and lint with flake8 + runs-on: ubuntu-latest + + steps: + - name: Check out Git repository + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install Python dependencies + run: pip install black flake8 + + - name: Run black and flake8 + uses: wearerequired/lint-action@v1 + with: + black: true + flake8: true + black_args: "--line-length 79 --exclude='1_beginner/chapter1/examples/error.py'" # same max line length as flake8 + flake8_args: "--max-line-length=88 --ignore=E203,W503 --exclude=1_beginner/chapter1/examples/error.py" # prevent conflicts with black + auto_fix: true # auto commit style fixes + \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1d74e219..c233127c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ .vscode/ +*.xml +*.iml +venv/ \ No newline at end of file diff --git a/1_beginner/chapter1/examples/comments.py b/1_beginner/chapter1/examples/comments.py index ae3363a0..af16ba6e 100644 --- a/1_beginner/chapter1/examples/comments.py +++ b/1_beginner/chapter1/examples/comments.py @@ -2,11 +2,11 @@ # This is a single line comment -''' +""" This is a multi-line comment -''' +""" """ This is also a multi-line diff --git a/1_beginner/chapter1/examples/error.py b/1_beginner/chapter1/examples/error.py new file mode 100644 index 00000000..269c6720 --- /dev/null +++ b/1_beginner/chapter1/examples/error.py @@ -0,0 +1,8 @@ +# Syntax Errors +prnt("Hello") # this would be a syntax error +# someone misspelled 'print' as 'prnt' + + print("Hello") # this would also result in an error since there's an extra indent + +# Runtime Error +print(1 / 0) # this would result in a ZeroDivision error diff --git a/1_beginner/chapter1/examples/printing.py b/1_beginner/chapter1/examples/printing.py index 1a754a83..40f4ab82 100644 --- a/1_beginner/chapter1/examples/printing.py +++ b/1_beginner/chapter1/examples/printing.py @@ -1,13 +1,18 @@ # Printing +# You can print other types besides strings; we'll get to that later +print("Hello") +print(1) +print(99.99) + # Strings can be in single or double quotes -print('Message') +print("Message") print("Message") # You can print with multiple arguments # Arguments are separated by a space by default -print('Message', 'with', 'arguments') +print("Message", "with", "arguments") # You can use string concatenation ("adding") # to put strings together (just be careful about spacing!) -print('Message' + 'with' + 'concatenation') # no spaces between words +print("Message" + "with" + "concatenation") # no spaces between words diff --git a/1_beginner/chapter1/practice/style.py b/1_beginner/chapter1/practice/style.py index 17d24ce2..1385d773 100644 --- a/1_beginner/chapter1/practice/style.py +++ b/1_beginner/chapter1/practice/style.py @@ -3,7 +3,7 @@ # fix the style in this file so that it runs properly # and there are comments explaining the program -''' +""" print("Hello World!") print("This is a Python program") @@ -12,4 +12,4 @@ input("Enter your age: ") print("Your age is " + age) -''' +""" diff --git a/1_beginner/chapter1/solutions/hello_world_again.py b/1_beginner/chapter1/solutions/hello_world_again.py index c387c637..18cb59e0 100644 --- a/1_beginner/chapter1/solutions/hello_world_again.py +++ b/1_beginner/chapter1/solutions/hello_world_again.py @@ -1,3 +1,3 @@ # Hello World Again # Print "Hello World" to the console -print('Hello World') +print("Hello World") diff --git a/1_beginner/chapter1/solutions/my_first_chapter.py b/1_beginner/chapter1/solutions/my_first_chapter.py index 4774bf60..86413b93 100644 --- a/1_beginner/chapter1/solutions/my_first_chapter.py +++ b/1_beginner/chapter1/solutions/my_first_chapter.py @@ -1,8 +1,8 @@ # My First Chapter # Print "My first chapter" and "Good morning!" # Then print 3 other messages of your choice to the console -print('My first chapter') -print('Good morning!') -print('This is a message') -print('This is another message') -print('One more message!') +print("My first chapter") +print("Good morning!") +print("This is a message") +print("This is another message") +print("One more message!") diff --git a/1_beginner/chapter2/examples/convert.py b/1_beginner/chapter2/examples/convert.py index 588ce4a3..f41618c6 100644 --- a/1_beginner/chapter2/examples/convert.py +++ b/1_beginner/chapter2/examples/convert.py @@ -1,7 +1,7 @@ # Converting to Different Data Types -x = '5' -y = '6' +x = "5" +y = "6" sum = int(x) + int(y) # this is 11 because x and y were converted to integers print(sum) diff --git a/1_beginner/chapter2/examples/data.py b/1_beginner/chapter2/examples/data.py index e3579a6d..c194bc27 100644 --- a/1_beginner/chapter2/examples/data.py +++ b/1_beginner/chapter2/examples/data.py @@ -3,7 +3,7 @@ # strings are a series of characters # they are in single or double quotes print("Jane") -print('Doe') +print("Doe") # integers are whole numbers (positive, negative, and 0) print(25) diff --git a/1_beginner/chapter2/examples/string_or_number.py b/1_beginner/chapter2/examples/string_or_number.py index 71a7b04f..3d5b7f74 100644 --- a/1_beginner/chapter2/examples/string_or_number.py +++ b/1_beginner/chapter2/examples/string_or_number.py @@ -1,8 +1,8 @@ # String or Number? # strings -x = '5' -y = '6' +x = "5" +y = "6" print(x + y) # this 56 (concatenation) # integers diff --git a/1_beginner/chapter2/examples/variables.py b/1_beginner/chapter2/examples/variables.py index e27e936f..80758363 100644 --- a/1_beginner/chapter2/examples/variables.py +++ b/1_beginner/chapter2/examples/variables.py @@ -2,7 +2,7 @@ # use variables to store data first_name = "Jane" -last_name = 'Doe' +last_name = "Doe" age = 25 diff --git a/1_beginner/chapter2/solutions/favorite.py b/1_beginner/chapter2/solutions/favorite.py index dfa82425..0915dcb0 100644 --- a/1_beginner/chapter2/solutions/favorite.py +++ b/1_beginner/chapter2/solutions/favorite.py @@ -10,7 +10,10 @@ # Display output print( - favorite_person + " bought you " - + favorite_food + " and " - + favorite_drink + "." + favorite_person + + " bought you " + + favorite_food + + " and " + + favorite_drink + + "." ) diff --git a/1_beginner/chapter2/solutions/print_data_types.py b/1_beginner/chapter2/solutions/print_data_types.py index 96fefe04..28848bb9 100644 --- a/1_beginner/chapter2/solutions/print_data_types.py +++ b/1_beginner/chapter2/solutions/print_data_types.py @@ -14,5 +14,5 @@ # strings print("Tahiti, it's a magical place") -print('May the Force be with you') +print("May the Force be with you") print("Hey guys") diff --git a/1_beginner/chapter3/examples/math_operators.py b/1_beginner/chapter3/examples/math_operators.py index 00648a58..8c54a408 100644 --- a/1_beginner/chapter3/examples/math_operators.py +++ b/1_beginner/chapter3/examples/math_operators.py @@ -29,4 +29,4 @@ # Exponent x = 2 y = 3 -print(x ** y) # prints 8 +print(x**y) # prints 8 diff --git a/1_beginner/chapter3/practice/change.py b/1_beginner/chapter3/practice/change.py index e8b172e6..443b95b6 100644 --- a/1_beginner/chapter3/practice/change.py +++ b/1_beginner/chapter3/practice/change.py @@ -1,4 +1,4 @@ -''' +""" Write code that takes, as input, the number of dollars a person has (a floating number), and outputs how much they have in dollars, quarters, dimes, nickels and pennies. @@ -15,13 +15,12 @@ Note: This is a challenge problem! Do not feel bad or disheartned if you can't solve it. We will go over it next class. -''' +""" CENTS_PER_DOLLAR = 100 num_cents = int( - float(input("How many dollars do you have: $")) - * CENTS_PER_DOLLAR + float(input("How many dollars do you have: $")) * CENTS_PER_DOLLAR ) # What do you do next? Write code here diff --git a/1_beginner/chapter3/practice/decimal.py b/1_beginner/chapter3/practice/decimal.py index bb8a4ee2..bc381d1e 100644 --- a/1_beginner/chapter3/practice/decimal.py +++ b/1_beginner/chapter3/practice/decimal.py @@ -1,7 +1,10 @@ # Decimal # Write a program that asks the user for a floating point number as input. -# It returns the decimal part (the part to the right of the decimal point). +# It prints out the decimal part (the part to the right of the decimal point). # Don't worry about floating point errors! -# The output should round to the correct answer, though. +# Note: To display a more exact output, you can use +# rounded_decimal = round(decimal_variable, 10) +# to set rounded_decimal to your decimal_variable rounded to a precision +# of 10 decimal places. # Write code here diff --git a/1_beginner/chapter3/practice/decisions_1.py b/1_beginner/chapter3/practice/decisions_1.py index 635d8a11..bc7e87c8 100644 --- a/1_beginner/chapter3/practice/decisions_1.py +++ b/1_beginner/chapter3/practice/decisions_1.py @@ -1,5 +1,5 @@ # Decisions 1 # Write in Python syntax what you would say -# if you wanted either a 5 dollars OR (2 drinks AND 1 snack). +# if you wanted either 5 dollars OR (2 drinks AND 1 snack). # write your code here diff --git a/1_beginner/chapter3/practice/integer.py b/1_beginner/chapter3/practice/integer.py new file mode 100644 index 00000000..96693b18 --- /dev/null +++ b/1_beginner/chapter3/practice/integer.py @@ -0,0 +1,9 @@ +""" +Integer + +Write a program that takes any number +(decimals included) as input, and outputs +whether or not it's an integer. +""" + +# Insert code here. diff --git a/1_beginner/chapter3/practice/names.py b/1_beginner/chapter3/practice/names.py new file mode 100644 index 00000000..dcda62a9 --- /dev/null +++ b/1_beginner/chapter3/practice/names.py @@ -0,0 +1,9 @@ +""" +Names + +Write a program that asks a user +for two names, and outputs True if +the names are NOT the same. +""" + +# Insert code here. diff --git a/1_beginner/chapter3/practice/no_greater_than.py b/1_beginner/chapter3/practice/no_greater_than.py index 686c1ae1..fc4e31ed 100644 --- a/1_beginner/chapter3/practice/no_greater_than.py +++ b/1_beginner/chapter3/practice/no_greater_than.py @@ -1,4 +1,4 @@ -''' +""" Create a program that takes a POSITIVE integer as an input and checks if it is no greater than 100. Print True if it is, and False if it isn't @@ -7,6 +7,6 @@ LESS THAN OPERATORS (>, <, >=, or <=). Find a way to do this problem only using only the == operator and any math operators you want. -''' +""" # write code here diff --git a/1_beginner/chapter3/practice/wizard.py b/1_beginner/chapter3/practice/wizard.py new file mode 100644 index 00000000..49c8d555 --- /dev/null +++ b/1_beginner/chapter3/practice/wizard.py @@ -0,0 +1,39 @@ +""" +Wizard + +There are 3 criteria to determine whether +you’re a wizard or not. + +Define a variable called is_wizard and +use logic operators to set it to the correct +value based on the criteria. + +Here are some example variable values and outputs. +You'll need to figure out the order of logic operators +needed to turn these inputs into these outputs! :) + +Example variable values and output: + +If you can fly, you’ve not a battled a dragon, +and you’re alive, output “Wizard: True” + +If you can fly, you’ve battled a dragon, +and you’re not alive, output “Wizard: True” + +If you can’t fly, you’ve battled a dragon, +and you’re not alive, output “Wizard: False” + +If you can’t fly, you’ve battled a dragon, +and you’re alive, output “Wizard: True" + +The initial variables are given, but you'll have +to change the values to test your code. +""" + +can_fly = True +battled_dragon = False +is_alive = True + +# Insert your code here. + +# print("Wizard:", is_wizard) diff --git a/1_beginner/chapter3/solutions/change.py b/1_beginner/chapter3/solutions/change.py index 6372d84f..a8cd5ee9 100644 --- a/1_beginner/chapter3/solutions/change.py +++ b/1_beginner/chapter3/solutions/change.py @@ -1,4 +1,4 @@ -''' +""" Write code that takes, as input, the number of dollars a person has (a floating number), and outputs how much they have in dollars, quarters, dimes, nickels and pennies. @@ -15,7 +15,7 @@ Note: This is a challenge problem! Do not feel bad or disheartned if you can't solve it. We will go over it next class. -''' +""" CENTS_PER_DOLLAR = 100 CENTS_PER_QUARTER = 25 @@ -24,26 +24,25 @@ # prompt user for dollars and convert it to cents num_cents = int( - float(input("How many dollars do you have: $")) - * CENTS_PER_DOLLAR + float(input("How many dollars do you have: $")) * CENTS_PER_DOLLAR ) # calculate change and display it dollars = num_cents // CENTS_PER_DOLLAR remaining = num_cents % CENTS_PER_DOLLAR -print(dollars, " dollars") +print(dollars, "dollars") quarters = remaining // CENTS_PER_QUARTER remiaining = remaining % CENTS_PER_QUARTER -print(quarters, " quarters") +print(quarters, "quarters") dimes = remaining // CENTS_PER_DIME remiaining = remaining % CENTS_PER_DIME -print(dimes, " dimes") +print(dimes, "dimes") nickels = remaining // CENTS_PER_NICKEL remiaining = remaining % CENTS_PER_NICKEL -print(nickels, " nickels") +print(nickels, "nickels") cents = remaining -print(cents, " cents") +print(cents, "cents") diff --git a/1_beginner/chapter3/solutions/circle.py b/1_beginner/chapter3/solutions/circle.py index 3afe613f..78463e52 100644 --- a/1_beginner/chapter3/solutions/circle.py +++ b/1_beginner/chapter3/solutions/circle.py @@ -10,7 +10,7 @@ radius = float(input("Enter a radius: ")) # Calculate the area and circumference -area = PI * radius ** 2 +area = PI * radius**2 circumference = 2 * PI * radius # Print the result diff --git a/1_beginner/chapter3/solutions/cylinder_volume.py b/1_beginner/chapter3/solutions/cylinder_volume.py index 6c04f715..07494915 100644 --- a/1_beginner/chapter3/solutions/cylinder_volume.py +++ b/1_beginner/chapter3/solutions/cylinder_volume.py @@ -4,7 +4,7 @@ # The formula for the volume of a cylinder is # volume = pi * (radius ^ 2) * height PI = 3.14 -height = float(input('Height of cylinder: ')) -radius = float(input('Radius of cylinder: ')) -volume = PI * radius ** 2 * height +height = float(input("Height of cylinder: ")) +radius = float(input("Radius of cylinder: ")) +volume = PI * radius**2 * height print("The volume of the cylinder is", volume) diff --git a/1_beginner/chapter3/solutions/decimal.py b/1_beginner/chapter3/solutions/decimal.py index 21ca8fde..f1917397 100644 --- a/1_beginner/chapter3/solutions/decimal.py +++ b/1_beginner/chapter3/solutions/decimal.py @@ -1,8 +1,11 @@ # Decimal # Write a program that asks the user for a floating point number as input. -# It returns the decimal part (the part to the right of the decimal point). +# It prints out the decimal part (the part to the right of the decimal point). # Don't worry about floating point errors! -# The output should round to the correct answer, though. +# Note: To display a more exact output, you can use +# rounded_decimal = round(decimal_variable, 10) +# to set rounded_decimal to your decimal_variable rounded to a precision +# of 10 decimal places. # Get the floating point number input num = float(input("Enter a floating point number: ")) diff --git a/1_beginner/chapter3/solutions/even.py b/1_beginner/chapter3/solutions/even.py index c05aba99..9f76d08a 100644 --- a/1_beginner/chapter3/solutions/even.py +++ b/1_beginner/chapter3/solutions/even.py @@ -7,5 +7,5 @@ i = int(input("Enter an integer: ")) # Display output -is_even = (i % 2 == 0) +is_even = i % 2 == 0 print("Is this number even? " + str(is_even)) diff --git a/1_beginner/chapter3/solutions/integer.py b/1_beginner/chapter3/solutions/integer.py new file mode 100644 index 00000000..b2f23268 --- /dev/null +++ b/1_beginner/chapter3/solutions/integer.py @@ -0,0 +1,15 @@ +""" +Integer + +Write a program that takes any number +(decimals included) as input, and outputs +whether or not it's an integer. +""" + +# Get input as a floating point +x = float(input("Enter a number: ")) + +# Compare x to the integer version of itself +is_integer = x == int(x) + +print("Is integer? " + str(is_integer)) diff --git a/1_beginner/chapter3/solutions/names.py b/1_beginner/chapter3/solutions/names.py new file mode 100644 index 00000000..c48cedb3 --- /dev/null +++ b/1_beginner/chapter3/solutions/names.py @@ -0,0 +1,15 @@ +""" +Names + +Write a program that asks a user +for two names, and outputs True if +the names are NOT the same. +""" + +name1 = input("Person 1: ") +name2 = input("Person 2: ") + +# "False" if name1 and name2 are equal +not_same = name1 != name2 + +print("Not the same?", not_same) diff --git a/1_beginner/chapter3/solutions/no_greater_than.py b/1_beginner/chapter3/solutions/no_greater_than.py index f0134080..09b5ce63 100644 --- a/1_beginner/chapter3/solutions/no_greater_than.py +++ b/1_beginner/chapter3/solutions/no_greater_than.py @@ -1,4 +1,4 @@ -''' +""" Create a program that takes a POSITIVE integer as an input and checks if it is no greater than 100. Print True if it is, and False if it isn't @@ -7,6 +7,6 @@ LESS THAN OPERATORS (>, <, >=, or <=). Find a way to do this problem only using only the == operator and any math operators you want. -''' +""" x = int(input("Enter you number here. It must be positive: ")) print(x // 100 == 0) diff --git a/1_beginner/chapter3/solutions/wizard.py b/1_beginner/chapter3/solutions/wizard.py new file mode 100644 index 00000000..10154aba --- /dev/null +++ b/1_beginner/chapter3/solutions/wizard.py @@ -0,0 +1,39 @@ +""" +Wizard + +There are 3 criteria to determine whether +you’re a wizard or not. + +Define a variable called is_wizard and +use logic operators to set it to the correct +value based on the criteria. + +Here are some example variable values and outputs. +You'll need to figure out the order of logic operators +needed to turn these inputs into these outputs! :) + +Example variable values and output: + +If you can fly, you’ve not a battled a dragon, +and you’re alive, output “Wizard: True” + +If you can fly, you’ve battled a dragon, +and you’re not alive, output “Wizard: True” + +If you can’t fly, you’ve battled a dragon, +and you’re not alive, output “Wizard: False” + +If you can’t fly, you’ve battled a dragon, +and you’re alive, output “Wizard: True" + +The initial variables are given, but you'll have +to change the values to test your code. +""" + +can_fly = True +battled_dragon = False +is_alive = True + +is_wizard = can_fly or (battled_dragon and is_alive) + +print("Wizard:", is_wizard) diff --git a/1_beginner/chapter4/practice/four_numbers.py b/1_beginner/chapter4/practice/four_numbers.py index 1baca338..f9c724a8 100644 --- a/1_beginner/chapter4/practice/four_numbers.py +++ b/1_beginner/chapter4/practice/four_numbers.py @@ -1,4 +1,4 @@ -''' +""" Ask the user for 4 numbers. Use only 3 if else blocks to find the largest number. You may not use elifs. @@ -10,6 +10,6 @@ print("nay") This question is really tricky, and requires some ingenuity. -''' +""" # Write code here diff --git a/1_beginner/chapter4/practice/grade.py b/1_beginner/chapter4/practice/grade.py index 22274604..992997ed 100644 --- a/1_beginner/chapter4/practice/grade.py +++ b/1_beginner/chapter4/practice/grade.py @@ -1,4 +1,4 @@ -''' +""" Grade Write a program that asks the user to enter the score for a student's test. @@ -11,13 +11,13 @@ F: < 60 Print the letter grade that the test score receives. -''' +""" # write code here -''' +""" See if you can write the same program, but without using >= anywhere. -''' +""" # write code here diff --git a/1_beginner/chapter4/practice/hours.py b/1_beginner/chapter4/practice/hours.py index fa9b8e15..53d87890 100644 --- a/1_beginner/chapter4/practice/hours.py +++ b/1_beginner/chapter4/practice/hours.py @@ -1,7 +1,7 @@ # Hours # Write a program that asks the user # how many hours they spend on the internet -# per day, and return if they’re addicted +# per day, and print if they’re addicted # or not based on the hours. (5 or more hours # is addicted, less is not). diff --git a/1_beginner/chapter4/practice/menu.py b/1_beginner/chapter4/practice/menu.py index a615a953..b528e351 100644 --- a/1_beginner/chapter4/practice/menu.py +++ b/1_beginner/chapter4/practice/menu.py @@ -7,7 +7,7 @@ But if the customer enters 'french toast' AND 'coffee', there is a discount of $1. -And if the customer enters 'chicken soup' OR 'apple juice', +Otherwise, if the customer enters 'chicken soup' OR 'apple juice', the price increases by $1. Write a program that takes an order from a user diff --git a/1_beginner/chapter4/practice/simplify.py b/1_beginner/chapter4/practice/simplify.py index 35f9e1fe..fac39e8f 100644 --- a/1_beginner/chapter4/practice/simplify.py +++ b/1_beginner/chapter4/practice/simplify.py @@ -1,6 +1,7 @@ """ -Here is a block of code where one tries do determine -if somone is a nobel prize winner. +Simplify +Here is a block of code where one tries to determine +if someone is a Nobel Prize winner. Rewrite the code to work in one statement. @@ -8,7 +9,7 @@ you start working.) """ -''' +""" if does_significant_work: if makes_breakthrough: is_nobel_prize_candidate = True @@ -16,4 +17,4 @@ is_nobel_prize_candidate = False elif not does_significant_work: is_nobel_prize_candidate = False -''' +""" diff --git a/1_beginner/chapter4/practice/temperature.py b/1_beginner/chapter4/practice/temperature.py index 5aa44841..576dc9d4 100644 --- a/1_beginner/chapter4/practice/temperature.py +++ b/1_beginner/chapter4/practice/temperature.py @@ -13,8 +13,8 @@ temp = int(input("Enter temperature: ")) if temp < 100: # 60-100 is hot - print('hot') + print("hot") if temp <= 60: # 30-59 is normal - print('normal') + print("normal") if temp < 30: # 0-29 is cold - print('cold') + print("cold") diff --git a/1_beginner/chapter4/solutions/difference.py b/1_beginner/chapter4/solutions/difference.py index 3f5de68e..ac84d4e3 100644 --- a/1_beginner/chapter4/solutions/difference.py +++ b/1_beginner/chapter4/solutions/difference.py @@ -4,9 +4,9 @@ # greater than 17 print "Negative". Otherwise, # print the result of 17 minus the given number. -x = float(input('Enter a number: ')) +x = float(input("Enter a number: ")) if x > 17: - print('Negative') + print("Negative") else: print(17 - x) diff --git a/1_beginner/chapter4/solutions/four_numbers.py b/1_beginner/chapter4/solutions/four_numbers.py index e333dc33..45b0445d 100644 --- a/1_beginner/chapter4/solutions/four_numbers.py +++ b/1_beginner/chapter4/solutions/four_numbers.py @@ -1,4 +1,4 @@ -''' +""" Ask the user for 4 numbers. Use only 3 if else blocks to find the largest number. You may not use elifs. @@ -10,7 +10,7 @@ print("nay") This question is really tricky, and requires some ingenuity. -''' +""" a = float(input("Enter number 1: ")) b = float(input("Enter number 2: ")) diff --git a/1_beginner/chapter4/solutions/grade.py b/1_beginner/chapter4/solutions/grade.py index 07f0f553..6ae3c9dc 100644 --- a/1_beginner/chapter4/solutions/grade.py +++ b/1_beginner/chapter4/solutions/grade.py @@ -1,4 +1,4 @@ -''' +""" Grade Write a program that asks the user to enter the score for a student's test. @@ -11,7 +11,7 @@ F: < 60 Print the letter grade that the test score receives. -''' +""" score = float(input("Enter test score: ")) if score >= 90: @@ -25,10 +25,10 @@ else: print("F") -''' +""" See if you can write the same program, but without using >= anywhere. -''' +""" score = float(input("Enter test score: ")) if score < 60: diff --git a/1_beginner/chapter4/solutions/hours.py b/1_beginner/chapter4/solutions/hours.py index 8e5a97d8..87b964e1 100644 --- a/1_beginner/chapter4/solutions/hours.py +++ b/1_beginner/chapter4/solutions/hours.py @@ -1,7 +1,7 @@ # Hours # Write a program that asks the user # how many hours they spend on the internet -# per day, and return if they’re addicted +# per day, and print if they’re addicted # or not based on the hours. (5 or more hours # is addicted, less is not). diff --git a/1_beginner/chapter4/solutions/menu.py b/1_beginner/chapter4/solutions/menu.py index 4369b529..9412b483 100644 --- a/1_beginner/chapter4/solutions/menu.py +++ b/1_beginner/chapter4/solutions/menu.py @@ -7,7 +7,7 @@ But if the customer enters 'french toast' AND 'coffee', there is a discount of $1. -And if the customer enters 'chicken soup' OR 'apple juice', +Otherwise, if the customer enters 'chicken soup' OR 'apple juice', the price increases by $1. Write a program that takes an order from a user @@ -24,11 +24,10 @@ drink = input("What drink would you like? ") # discount of $1 if the user orders french toast and coffee -if food == 'french toast' and drink == 'coffee': +if food == "french toast" and drink == "coffee": total_cost -= 1 - # charge extra $1 if user orders chicken soup or apple juice -if food == 'chicken soup' or drink == 'apple juice': +elif food == "chicken soup" or drink == "apple juice": total_cost += 1 # display total diff --git a/1_beginner/chapter4/solutions/simplify.py b/1_beginner/chapter4/solutions/simplify.py index be28f1c3..4b453bd0 100644 --- a/1_beginner/chapter4/solutions/simplify.py +++ b/1_beginner/chapter4/solutions/simplify.py @@ -1,6 +1,7 @@ """ -Here is a block of code where one tries do determine -if somone is a nobel prize winner. +Simplify +Here is a block of code where one tries to determine +if someone is a Nobel Prize winner. Rewrite the code to work in one statement. diff --git a/1_beginner/chapter4/solutions/square.py b/1_beginner/chapter4/solutions/square.py index 2dbde5cf..678cae8b 100644 --- a/1_beginner/chapter4/solutions/square.py +++ b/1_beginner/chapter4/solutions/square.py @@ -9,7 +9,7 @@ if number % 2 == 0: # if number is even, print its square - print(number ** 2) + print(number**2) else: # otherwise, print the number itself print(number) diff --git a/1_beginner/chapter4/solutions/temperature.py b/1_beginner/chapter4/solutions/temperature.py index 03f54670..28c5cb0c 100644 --- a/1_beginner/chapter4/solutions/temperature.py +++ b/1_beginner/chapter4/solutions/temperature.py @@ -11,11 +11,11 @@ temp = int(input("Enter temperature: ")) if 60 <= temp <= 100: # 60-100 is hot - print('hot') + print("hot") if 30 <= temp < 60: # 30-59 is normal - print('normal') + print("normal") if 0 <= temp < 30: # 0-29 is cold - print('cold') + print("cold") # alternatively, you can also use elif # if temp >= 60: diff --git a/1_beginner/chapter4/solutions/walk.py b/1_beginner/chapter4/solutions/walk.py index c6cc4b45..f6dc7d72 100644 --- a/1_beginner/chapter4/solutions/walk.py +++ b/1_beginner/chapter4/solutions/walk.py @@ -22,8 +22,8 @@ """ # prompt user for first walk start time -first_hour = int(input('Enter the hour of the time of the first walk: ')) -first_minute = int(input('Enter the minute of the time of the first walk: ')) +first_hour = int(input("Enter the hour of the time of the first walk: ")) +first_minute = int(input("Enter the minute of the time of the first walk: ")) # calculate second walk start time # add first_hour + 1 is when the first walk ends, @@ -32,20 +32,20 @@ second_minute = first_minute # prompt user for current time -current_hour = int(input('Enter the current hour: ')) -current_minute = int(input('Enter the current minute: ')) +current_hour = int(input("Enter the current hour: ")) +current_minute = int(input("Enter the current minute: ")) # print whether Timmy is late or early # to the second walk if current_hour > second_hour: - print('Late') + print("Late") elif current_hour < second_hour: - print('Early') + print("Early") else: # compare minutes if hours are equal if current_minute > second_minute: - print('Late') + print("Late") elif current_minute < second_minute: - print('Early') + print("Early") else: # current_minute == second_minute - print('Now') + print("Now") diff --git a/1_beginner/chapter5/practice/TV.py b/1_beginner/chapter5/practice/TV.py index 9a2e1622..842bc783 100644 --- a/1_beginner/chapter5/practice/TV.py +++ b/1_beginner/chapter5/practice/TV.py @@ -1,9 +1,9 @@ # TV -# Pretend you just got a 37 on your test, -# and you mom says you can’t watch TV until you get above an 84. -# (HINT: comparison operators). You increase -# your test score 6 points per day (iterations). +# Pretend you just got a 50 on your test, +# and you mom says you can’t watch TV until you get +# a score of at least 80. (HINT: comparison operators). +# You increase your test score by 10 points per day. # Write a program that tells you after -# how many days you'll be able to watch TV +# how many days you'll be able to watch TV. Use a loop. # write code here diff --git a/1_beginner/chapter5/practice/add_all_the_way.py b/1_beginner/chapter5/practice/add_all_the_way.py index fbd2f8a5..b91d4817 100644 --- a/1_beginner/chapter5/practice/add_all_the_way.py +++ b/1_beginner/chapter5/practice/add_all_the_way.py @@ -1,8 +1,10 @@ # Add All the Way -# Write a program that asks for and -# reads an input from the user -# Then add all the numbers up from 0 -# to that number up. You can use a -# for or while loop. Print out the sum. +# Take a number from the user and +# add every number up from 1 to that number. +# Print the result. +# You can use a for or while loop. # write code here + + +# Try using the other loop and do the same p[roblem again diff --git a/1_beginner/chapter5/practice/alternating.py b/1_beginner/chapter5/practice/alternating.py new file mode 100644 index 00000000..0fe44abc --- /dev/null +++ b/1_beginner/chapter5/practice/alternating.py @@ -0,0 +1,12 @@ +""" +Alternating +Ask the user for a positive integer. Then print the numbers from 1 +to that number, but alternating in sign. For example, if the input +was 5, what would be printed is 1, -1, 2, -2, 3, -3, 4, -4, 5. +(Note, DO NOT include the last negative number). +Do this with a for loop and then with a while loop. +""" + +# Write code here + +# Now try it with a while loop diff --git a/1_beginner/chapter5/practice/even.py b/1_beginner/chapter5/practice/even.py index 97c95033..b5b1b482 100644 --- a/1_beginner/chapter5/practice/even.py +++ b/1_beginner/chapter5/practice/even.py @@ -1,5 +1,5 @@ # Even # Print every even number greater than 10 -# and less than 101 +# and less than 101 (10 ia included) # write code here diff --git a/1_beginner/chapter5/practice/fibonnaci.py b/1_beginner/chapter5/practice/fibonnaci.py new file mode 100644 index 00000000..1aa27bde --- /dev/null +++ b/1_beginner/chapter5/practice/fibonnaci.py @@ -0,0 +1,20 @@ +""" CHALLENGE PROBLEM!! NOT FOR THE FAINT OF HEART! + +The Fibonacci numbers, discovered by Leonardo di Fibonacci, +is a sequence of numbers that often shows up in mathematics and, +interestingly, nature. The sequence goes as such: + +1,1,2,3,5,8,13,21,34,55,... + +where the sequence starts with 1 and 1, and then each number is the sum of the +previous 2. For example, 8 comes after 5 because 5+3 = 8, and 55 comes after 34 +because 34+21 = 55. + +The challenge is to use a for loop (not recursion, if you know what that is), +to find the 100th Fibonnaci number. +""" + +# write code here + + +# Can you do it with a while loop? diff --git a/1_beginner/chapter5/practice/fizzbuzz.py b/1_beginner/chapter5/practice/fizzbuzz.py new file mode 100644 index 00000000..894f212b --- /dev/null +++ b/1_beginner/chapter5/practice/fizzbuzz.py @@ -0,0 +1,22 @@ +# Fizz Buzz +""" +Credit to: https://www.youtube.com/watch?v=QPZ0pIK_wsc + +Fizz Buzz is a game played between 2 people +where they take turns counting up starting at 1. +However, if the number is divisible by 3, the person +should say "fizz" instead of the number. +If the number is divisible by 5, the person should +say "buzz" instead of the number. +If the number is divisible by both 3 and 5, +the person should say "fizzbuzz" instead of the number. +For example, this is how the first 5 results would look like: +1 +2 +fizz +4 +buzz +Write a program that outputs the first 100 results. +""" + +# Write your code here diff --git a/1_beginner/chapter5/practice/multiply.py b/1_beginner/chapter5/practice/multiply.py new file mode 100644 index 00000000..95f0b4aa --- /dev/null +++ b/1_beginner/chapter5/practice/multiply.py @@ -0,0 +1,12 @@ +""" +Multiply + +Write a program that asks the user +for 10 integers, multiplies them all +together, and displays the product at +the end. + +Use a for loop! +""" + +# Insert your code here. diff --git a/1_beginner/chapter5/practice/prime.py b/1_beginner/chapter5/practice/prime.py new file mode 100644 index 00000000..e631641e --- /dev/null +++ b/1_beginner/chapter5/practice/prime.py @@ -0,0 +1,28 @@ +""" + +Write a program to check if a number is prime or not. A prime +number is one that is not divisible by any number other than +1 and itself. For example, 11 is prime because it is not divisible +by 2,3,4,5,...10 (i.e. 11/10, for example, is not an integer). + +Write a for loop to check if a number is prime or not. + +""" + +# write code here + +numer = int(input("Enter number here: ")) + +""" +Given a number less than or equal to 10 billion, see if you can check if it is +prime in UNDER 2 SECONDS. The code you wrote above probably wont do that, so +you will have to figure out a clever solution. + +NOTE: THE ABOVE IS A CHALLENGE PROBLEM, AND IS EXTRREEMMLY HARD TO DO. +I COULDN'T DO IT OPTIMALY UNTIL I LEARNED HOW TO. If you can't +figure out the solution, don't feel discouraged, its seriously a really +hard problem (I have seen this asked to college students :O) + +""" + +# write code here diff --git a/1_beginner/chapter5/practice/series.py b/1_beginner/chapter5/practice/series.py new file mode 100644 index 00000000..c8ea06e8 --- /dev/null +++ b/1_beginner/chapter5/practice/series.py @@ -0,0 +1,16 @@ +""" + +Here are some interesting results from mathematics that we can +model with computer science. + +In class we added up 1 + 1/2 + 1/4 + 1/8 ... +See if you can add up 1 + 1/3 + 1/9 + 1/27 + 1/81 ... in a similar fashion. +What is the answer? What if, instead of 3, we use 5 (1 + 1/5 + 1/25 + 1/125...) +7? Do you see a patter? (Note: make sure not to end up with an infinite loop). + + + +Also, try adding up 1 -1/3 + 1/5 - 1/7 + 1/9 - 1/11 ... 10 million times. then +multiply this result by 4. What number is this close to? + +""" diff --git a/1_beginner/chapter5/practice/up_2_fifty.py b/1_beginner/chapter5/practice/up_2_fifty.py index 3d800176..d2b99f89 100644 --- a/1_beginner/chapter5/practice/up_2_fifty.py +++ b/1_beginner/chapter5/practice/up_2_fifty.py @@ -2,7 +2,7 @@ # Write a program that takes a number from the user # and adds 2 to it until it reaches 50 or more, # then prints out how many times 2 was added. -# If the number is already greater than 50, +# If the number is already 50 or greater, # then print out ('Already there!') # write code here diff --git a/1_beginner/chapter5/solutions/TV.py b/1_beginner/chapter5/solutions/TV.py index 510df61d..76f87a2e 100644 --- a/1_beginner/chapter5/solutions/TV.py +++ b/1_beginner/chapter5/solutions/TV.py @@ -1,14 +1,14 @@ # TV -# Pretend you just got a 37 on your test, -# and you mom says you can’t watch TV until you get above an 84. -# (HINT: comparison operators). You increase -# your test score 6 points per day (iterations). +# Pretend you just got a 50 on your test, +# and you mom says you can’t watch TV until you get +# a score of at least 80. (HINT: comparison operators). +# You increase your test score by 10 points per day. # Write a program that tells you after -# how many days you'll be able to watch TV +# how many days you'll be able to watch TV. Use a loop. -x = 37 -d = 0 -while x < 84: - x += 6 - d += 1 -print(d) +x = 50 +days = 0 +while x < 80: + x += 10 + days += 1 +print("You can watch TV after", days, "days") diff --git a/1_beginner/chapter5/solutions/add_all_the_way.py b/1_beginner/chapter5/solutions/add_all_the_way.py index be0db267..84dc010c 100644 --- a/1_beginner/chapter5/solutions/add_all_the_way.py +++ b/1_beginner/chapter5/solutions/add_all_the_way.py @@ -1,9 +1,8 @@ # Add All the Way -# Write a program that asks for and -# reads an input from the user -# Then add all the numbers up from 0 -# to that number up. You can use a -# for or while loop. Print out the sum. +# Take a number from the user and +# add every number up from 1 to that number. +# Print the result. +# You can use a for or while loop. # for loop solution sum = 0 diff --git a/1_beginner/chapter5/solutions/alternating.py b/1_beginner/chapter5/solutions/alternating.py new file mode 100644 index 00000000..de8f197d --- /dev/null +++ b/1_beginner/chapter5/solutions/alternating.py @@ -0,0 +1,27 @@ +""" +Alternating +Ask the user for a positive integer. Then print the numbers from 1 +to that number, but alternating in sign. For example, if the input +was 5, what would be printed is 1, -1, 2, -2, 3, -3, 4, -4, 5. +(Note, DO NOT include the last negative number). +Do this with a for loop and then with a while loop. +""" + +# for loop solution +number = int(input("Enter number here: ")) +for num in range(1, number + 1): + if num == number: + print(num) + else: + print(num) + print(-num) + + +# while loop solution +number = int(input("Enter number here: ")) +current_num = 1 +while current_num < number: + print(current_num) + print(-current_num) + current_num += 1 +print(current_num) diff --git a/1_beginner/chapter5/solutions/echo_enhanced.py b/1_beginner/chapter5/solutions/echo_enhanced.py index 7ae98a4a..9e68fbe6 100644 --- a/1_beginner/chapter5/solutions/echo_enhanced.py +++ b/1_beginner/chapter5/solutions/echo_enhanced.py @@ -10,9 +10,9 @@ print("Enter a message, 'c' to cancel an echo, or 'q' to quit.") while True: message = input("Message: ") - if message == 'q': + if message == "q": break # quit - elif message == 'c': + elif message == "c": continue # cancel echo else: print(message) # echo message diff --git a/1_beginner/chapter5/solutions/fizzbuzz.py b/1_beginner/chapter5/solutions/fizzbuzz.py new file mode 100644 index 00000000..b3c9dda9 --- /dev/null +++ b/1_beginner/chapter5/solutions/fizzbuzz.py @@ -0,0 +1,30 @@ +# Fizz Buzz +""" +Credit to: https://www.youtube.com/watch?v=QPZ0pIK_wsc + +Fizz Buzz is a game played between 2 people +where they take turns counting up starting at 1. +However, if the number is divisible by 3, the person +should say "fizz" instead of the number. +If the number is divisible by 5, the person should +say "buzz" instead of the number. +If the number is divisible by both 3 and 5, +the person should say "fizzbuzz" instead of the number. +For example, this is how the first 5 results would look like: +1 +2 +fizz +4 +buzz +Write a program that outputs the first 100 results. +""" + +for i in range(1, 101): + if i % 3 == 0 and i % 5 == 0: + print("fizzbuzz") + elif i % 3 == 0: + print("fizz") + elif i % 5 == 0: + print("buzz") + else: + print(i) diff --git a/1_beginner/chapter5/solutions/multiply.py b/1_beginner/chapter5/solutions/multiply.py new file mode 100644 index 00000000..618dcd3c --- /dev/null +++ b/1_beginner/chapter5/solutions/multiply.py @@ -0,0 +1,19 @@ +""" +Multiply + +Write a program that asks the user +for 10 integers, multiplies them all +together, and displays the product at +the end. + +Use a for loop! +""" + +# Initial value is 1 +product = 1 + +# Ask the user for 10 numbers and multiply. +for i in range(10): + product *= int(input("Enter a number: ")) + +print("The product is " + str(product)) diff --git a/1_beginner/chapter5/solutions/up_2_fifty.py b/1_beginner/chapter5/solutions/up_2_fifty.py index 8e0eccb1..1f68afe7 100644 --- a/1_beginner/chapter5/solutions/up_2_fifty.py +++ b/1_beginner/chapter5/solutions/up_2_fifty.py @@ -2,7 +2,7 @@ # Write a program that takes a number from the user # and adds 2 to it until it reaches 50 or more, # then prints out how many times 2 was added. -# If the number is already greater than 50, +# If the number is already 50 or greater, # then print out ('Already there!') # prompt user for a number @@ -23,4 +23,4 @@ # once the loop is done running print(iterations) else: - print('Already there!') + print("Already there!") diff --git a/1_beginner/chapter5/solutions/virtual_pet.py b/1_beginner/chapter5/solutions/virtual_pet.py index a08048a2..ba357c08 100644 --- a/1_beginner/chapter5/solutions/virtual_pet.py +++ b/1_beginner/chapter5/solutions/virtual_pet.py @@ -22,26 +22,26 @@ and happiness variables increase and decrease, or add more actions! """ -name = 'Otto' +name = "Otto" hunger = 6 happiness = 0 -command = input('> ') -while command != 'quit': # Exits loop when user quits +command = input("> ") +while command != "quit": # Exits loop when user quits # change Otto's hunger or happiness based on user command - if command == 'feed': - hunger -= 2 # Otto is fed, hunger decreases - happiness -= 1 # Otto is not pet, happiness decreases - elif command == 'pet': - happiness += 2 # Otto is pet, happiness increases - hunger += 1 # Otto is not fed, hunger increases + if command == "feed": + hunger -= 2 # Otto is fed, hunger decreases + happiness -= 1 # Otto is not pet, happiness decreases + elif command == "pet": + happiness += 2 # Otto is pet, happiness increases + hunger += 1 # Otto is not fed, hunger increases # display Otto's status - if hunger > 5: # Otto is not fed enough - print(name + ' is hungry') - if happiness < 5: # Otto is not pet enough - print(name + ' wants more attention') + if hunger > 5: # Otto is not fed enough + print(name + " is hungry") + if happiness < 5: # Otto is not pet enough + print(name + " wants more attention") elif hunger <= 5 and happiness >= 5: # Otto is satisfied! - print(name + ' feels happy') + print(name + " feels happy") - command = input('> ') # Keep taking user input until user quits + command = input("> ") # Keep taking user input until user quits diff --git a/1_beginner/chapter6/examples/identity_operators.py b/1_beginner/chapter6/examples/identity_operators.py index 8258d111..e939fa54 100644 --- a/1_beginner/chapter6/examples/identity_operators.py +++ b/1_beginner/chapter6/examples/identity_operators.py @@ -1,13 +1,13 @@ # Identity Operators -message_1 = 'hello' -message_2 = 'hello' +message_1 = "hello" +message_2 = "hello" print(message_1 is message_2) # True print(message_1 is not message_2) # False -message_3 = 'world' -message_4 = 'tahiti' +message_3 = "world" +message_4 = "tahiti" print(message_3 is message_4) # False print(message_3 is not message_4) # True @@ -19,9 +19,9 @@ x = 5 y = 5 if x is y: - print('x is y') + print("x is y") else: - print('x is not y') + print("x is not y") # lists are objects, # so they are located in different @@ -34,13 +34,13 @@ # reference the same location # in memory if a is b: - print('a is b') + print("a is b") else: - print('a is not b') + print("a is not b") # use the equality operator # to test if content is equivalent if a == b: - print('a == b') + print("a == b") else: - print('a != b') + print("a != b") diff --git a/1_beginner/chapter6/examples/lists.py b/1_beginner/chapter6/examples/lists.py index 034955b5..da827321 100644 --- a/1_beginner/chapter6/examples/lists.py +++ b/1_beginner/chapter6/examples/lists.py @@ -12,10 +12,10 @@ my_list = [] # empty list # append() adds elements to the end of the list -my_list.append('live') -my_list.append('long') -my_list.append('and') -my_list.append('prosper') +my_list.append("live") +my_list.append("long") +my_list.append("and") +my_list.append("prosper") print(my_list) # copy() returns a copy of the list @@ -27,15 +27,15 @@ print(my_list) # remove() removes the first item with the specified value -my_list.remove('live') +my_list.remove("live") print(my_list) # index() returns the index of the first element # with the specified value -print(my_list.index('prosper')) +print(my_list.index("prosper")) # insert() adds an element at the specified position -my_list.insert(0, 'live') +my_list.insert(0, "live") print(my_list) # reverse() reverses the order of the list diff --git a/1_beginner/chapter6/examples/membership_operators.py b/1_beginner/chapter6/examples/membership_operators.py index 3f8b2270..b491948f 100644 --- a/1_beginner/chapter6/examples/membership_operators.py +++ b/1_beginner/chapter6/examples/membership_operators.py @@ -8,6 +8,6 @@ print("oh no is not an element in my_list") if 4 not in my_list: - print('4 is not an element in my_list') + print("4 is not an element in my_list") else: - print('4 is an element in my_list') + print("4 is an element in my_list") diff --git a/1_beginner/chapter6/practice/grades.py b/1_beginner/chapter6/practice/grades.py new file mode 100644 index 00000000..1bd0e054 --- /dev/null +++ b/1_beginner/chapter6/practice/grades.py @@ -0,0 +1,22 @@ +""" +Grades + +Create a list called names and a list called grades. +Ask the user to input a name, and then ask +them to input the person's grade. Add the inputs +to the corresponding lists. Use a for loop to ask +for these inputs 5 times. + +Display the info as "[name]: [grade]". + +Example lists AFTER user input: +names = ["John", "Belle", "Ria", "Steph", "Louis"] +grades = [93, 85, 100, 82, 70] + +Example output: +John: 93 +Belle: 85 +etc. +""" + +# Insert your code here. diff --git a/1_beginner/chapter6/practice/grocery_list.py b/1_beginner/chapter6/practice/grocery_list.py index 9bcff2d9..6b5ca07b 100644 --- a/1_beginner/chapter6/practice/grocery_list.py +++ b/1_beginner/chapter6/practice/grocery_list.py @@ -1,4 +1,4 @@ -''' +""" Grocery List Create a program that prompts the @@ -19,6 +19,6 @@ 2 decimals.) Demo: https://youtu.be/BmMj16Ox5iA -''' +""" # write code here diff --git a/1_beginner/chapter6/practice/indexing.py b/1_beginner/chapter6/practice/indexing.py new file mode 100644 index 00000000..b288bc67 --- /dev/null +++ b/1_beginner/chapter6/practice/indexing.py @@ -0,0 +1,22 @@ +""" +Indexing + +1. Create a list with the following names: + Mark + Arya + Paz + Lulu + Jon + Robin +2. Print the first element of the list. +3. Print the 3rd-to last name ("Lulu") WITHOUT +using people[3]. +4. Print the second element of the list. + +Don't "hard-code" the answers. +For example, don't write print("Mark"). +Instead, use list indexing to get the values +from the list. +""" + +# Insert your code here. diff --git a/1_beginner/chapter6/practice/manipulation.py b/1_beginner/chapter6/practice/manipulation.py new file mode 100644 index 00000000..43ae7e42 --- /dev/null +++ b/1_beginner/chapter6/practice/manipulation.py @@ -0,0 +1,32 @@ +# Manipulation +# Modify the following code according to +# the instructions. + +nums = [] + +""" +The following code adds the numbers 0, 10, ... 100 +to the list nums, and displays this list. +First, make a copy of nums and store it in the varible more_nums. + +Then, clear nums, and add the numbers +2, 7, 12, ... 72 to nums instead. +""" + +for i in range(0, 101, 10): + nums.append(i) +print(nums) + +""" +Write the code for the following actions: +Change the 1st element of more_nums to -100. +Change the 2nd element of nums to 0. +Remove the last element from more_nums. +Remove every element divisible by 3 from more_nums. +Insert a 21 after the 20 in more_nums (assume that +you DON'T know the index of 20 ahead of time). +Insert 15 0's in the 3rd-to-last position. + Sample list after insertions: + [..., 0, 0, ..., 0, 0, element, element] +Display nums and more_nums. +""" diff --git a/1_beginner/chapter6/practice/monty_hall.py b/1_beginner/chapter6/practice/monty_hall.py index 7b564abb..ba8106ed 100644 --- a/1_beginner/chapter6/practice/monty_hall.py +++ b/1_beginner/chapter6/practice/monty_hall.py @@ -26,7 +26,8 @@ # 'G' for the doors that have a goat, 'C' for the door that has a car. # This step has already been done for you. import random -doors = ['G', 'G', 'C'] + +doors = ["G", "G", "C"] # Make the Monty Hall game repeat 6 times. # (All of the following actions should be in your loop.) diff --git a/1_beginner/chapter6/practice/names.py b/1_beginner/chapter6/practice/names.py new file mode 100644 index 00000000..14e1f181 --- /dev/null +++ b/1_beginner/chapter6/practice/names.py @@ -0,0 +1,17 @@ +""" +Names + +Make a list called people and fill it with +at least 6 names. Make another list and use +list slicing to fill it with every other name +from the original list, starting with the 1st name. +Print both lists. +""" + +# Insert your code here. + +""" +Use a for loop to ask the user to add 4 names +to the list. After you ask for each name, print +out the last 5 names of the list. +""" diff --git a/1_beginner/chapter6/practice/restaurant.py b/1_beginner/chapter6/practice/restaurant.py new file mode 100644 index 00000000..d71be0d2 --- /dev/null +++ b/1_beginner/chapter6/practice/restaurant.py @@ -0,0 +1,94 @@ +""" +Restaurant +Write a program that asks someone +what they want to order and give them +the total cost of their meal. + +Each meal should have 3 categories +(ex. food, drinks, desserts), and the user +must order 1 item from each category. + +Make sure to include a 7% sales tax +(multiply the total by 1.07), and +round the answer to 2 decimal places + +The steps are outlined in the following code. +""" + +""" +1. Store the menu in lists. +Each of the 3 categories should have an +items menu and a costs menu. + +Example of the 6 lists you need to create: +foods, food_costs, drinks, drink_costs, +desserts, dessert_costs +""" + +# Insert your lists here. + +""" +2. Display the menu. +Iterate through the items and costs for each +category to do this. + +Example output: +Welcome to my restaurant! Here's the menu: + +Food: +Pancakes: $5 +Waffles: $3 +Toast: $100 + +Drinks: +Juice: $2 +Water: $50 +Tea: $1 + +Sugar: +Muffin: $4 +Lollipop: $20 +Brownie: $15 +""" + +# Insert the code for displaying the menu here. + +""" +3. Ask the user to order. +This code should be in a loop. After you display the +user's total at the end, ask them if they want to +order again. If they say "no", the program should end. +Otherwise, you should take their order and display the +new total again. + +As you take their order, check if what they ordered +is in the corresponding list for that category. +If it is, add the price of the item to the total. +Otherwise, display a warning message and add $1000 to the total. + +Example order (using menu above): +What food would you like? pancakes +What drink would you like? water +What sugar item would you like? candy +You didn't order a proper sugary item! Adding $1000 to tab. +""" + +# Insert the code that takes the user's order here. +# Make sure it's in a loop. + +""" +4. Finalize the total. +Add a 7% sales tax to your sum, and +round this value to 2 decimal places. +Display the total. +""" + +# Add the code to finalize and display the total here. + +""" +5. As mentioned in Step 3, ask the user if they want +to order again. If they say "no", then stop the program. +Otherwise, let them order again. +""" + +# Ask the user if they want to order again here. diff --git a/1_beginner/chapter6/practice/too_long.py b/1_beginner/chapter6/practice/too_long.py index af29a0ec..4a235299 100644 --- a/1_beginner/chapter6/practice/too_long.py +++ b/1_beginner/chapter6/practice/too_long.py @@ -4,4 +4,4 @@ greater than 4 in a given list of strings. """ # list to help you test your code -the_list = ['dragon', 'cab', 'science', 'dove', 'lime', 'river', 'pop'] +the_list = ["dragon", "cab", "science", "dove", "lime", "river", "pop"] diff --git a/1_beginner/chapter6/solutions/grades.py b/1_beginner/chapter6/solutions/grades.py new file mode 100644 index 00000000..47c9c498 --- /dev/null +++ b/1_beginner/chapter6/solutions/grades.py @@ -0,0 +1,32 @@ +""" +Grades + +Create a list called names and a list called grades. +Ask the user to input a name, and then ask +them to input the person's grade. Add the inputs +to the corresponding lists. Use a for loop to ask +for these inputs 5 times. + +Display the info as "[name]: [grade]". + +Example lists AFTER user input: +names = ["John", "Belle", "Ria", "Steph", "Louis"] +grades = [93, 85, 100, 82, 70] + +Example output: +John: 93 +Belle: 85 +etc. +""" + +names = [] +grades = [] + +# Collect inputs. +for i in range(5): + names.append(input("Enter a name: ")) + grades.append(input("Enter their grade: ")) + +# Format output correctly. +for i in range(len(names)): + print(names[i] + ": " + grades[i]) diff --git a/1_beginner/chapter6/solutions/grocery_list.py b/1_beginner/chapter6/solutions/grocery_list.py index f680c94c..1e251a2e 100644 --- a/1_beginner/chapter6/solutions/grocery_list.py +++ b/1_beginner/chapter6/solutions/grocery_list.py @@ -1,4 +1,4 @@ -''' +""" Grocery List Create a program that prompts the @@ -19,21 +19,21 @@ 2 decimals.) Demo: https://youtu.be/BmMj16Ox5iA -''' +""" -item = '' +item = "" items = [] # stores grocery items # continuously ask user for grocery items # and store them in a list -while item != 'quit': +while item != "quit": item = input("Enter a grocery item, or 'quit': ") - if item != 'quit': + if item != "quit": items.append(item) # print items in numbered format for i in range(0, len(items)): - print(str(i + 1) + '. ' + items[i]) + print(str(i + 1) + ". " + items[i]) print() @@ -41,7 +41,7 @@ # each grocery item prices = [] for i in range(0, len(items)): - price = float(input('Enter price for ' + items[i] + ': $')) + price = float(input("Enter price for " + items[i] + ": $")) prices.append(price) print() @@ -50,7 +50,7 @@ # item in the grocery list quantities = [] for i in range(0, len(items)): - quantity = int(input('Enter quantity bought for ' + items[i] + ': ')) + quantity = int(input("Enter quantity bought for " + items[i] + ": ")) quantities.append(quantity) print() @@ -62,4 +62,4 @@ # print total, formatted to 2 decimals # because it's money -print('Total: $%.2f' % total) +print("Total: $%.2f" % total) diff --git a/1_beginner/chapter6/solutions/indexing.py b/1_beginner/chapter6/solutions/indexing.py new file mode 100644 index 00000000..0b096ab2 --- /dev/null +++ b/1_beginner/chapter6/solutions/indexing.py @@ -0,0 +1,26 @@ +""" +Indexing + +1. Create a list with the following names: + Mark + Arya + Paz + Lulu + Jon + Robin +2. Print the first element of the list. +3. Print the 3rd-to last name ("Lulu") WITHOUT +using people[3]. +4. Print the second element of the list. + +Don't "hard-code" the answers. +For example, don't write print("Mark"). +Instead, use list indexing to get the values +from the list. +""" + +names = ["Mark", "Arya", "Paz", "Lulu", "Jon", "Robin"] + +print(names[0]) +print(names[-3]) +print(names[1]) diff --git a/1_beginner/chapter6/solutions/integer_info.py b/1_beginner/chapter6/solutions/integer_info.py index 9468f58c..0a9ee705 100644 --- a/1_beginner/chapter6/solutions/integer_info.py +++ b/1_beginner/chapter6/solutions/integer_info.py @@ -16,6 +16,6 @@ info = [ len(str(num)), num % 10, # mod 10 of any number will return its last digit - num % 2 == 0 + num % 2 == 0, ] print(info) diff --git a/1_beginner/chapter6/solutions/manipulation.py b/1_beginner/chapter6/solutions/manipulation.py new file mode 100644 index 00000000..77da4574 --- /dev/null +++ b/1_beginner/chapter6/solutions/manipulation.py @@ -0,0 +1,54 @@ +# Manipulation +# Modify the following code according to +# the instructions. + +nums = [] + +""" +The following code adds the numbers 0, 10, ... 100 +to the list nums, and displays this list. +First, make a copy of nums and store it in the varible more_nums. + +Then, clear nums, and add the numbers +2, 7, 12, ... 72 to nums instead. +""" + +for i in range(0, 101, 10): + nums.append(i) +print(nums) + +more_nums = nums.copy() + +nums.clear() +for i in range(2, 73, 5): + nums.append(i) + +""" +Write the code for the following actions: +Change the 1st element of more_nums to -100. +Change the 2nd element of nums to 0. +Remove the last element from more_nums. +Remove every element divisible by 3 from more_nums. +Insert a 21 after the 20 in more_nums (assume that +you DON'T know the index of 20 ahead of time). +Insert 15 0's in the 3rd-to-last position. + Sample list after insertions: + [..., 0, 0, ..., 0, 0, element, element] +Display nums and more_nums. +""" + +more_nums[0] = -100 +nums[1] = 0 +more_nums.pop(-1) + +for i in more_nums: + if i % 3 == 0: + more_nums.remove(i) + +more_nums.insert(more_nums.index(20) + 1, 21) + +for i in range(15): + more_nums.insert(-2, 0) + +print("nums:\n", nums) +print("more_nums:\n", more_nums) diff --git a/1_beginner/chapter6/solutions/monty_hall.py b/1_beginner/chapter6/solutions/monty_hall.py index cee71b8f..7d851c40 100644 --- a/1_beginner/chapter6/solutions/monty_hall.py +++ b/1_beginner/chapter6/solutions/monty_hall.py @@ -25,7 +25,8 @@ # Make a list that represents the three closed doors, # 'G' for the doors that have a goat, 'C' for the door that has a car. import random -doors = ['G', 'G', 'C'] + +doors = ["G", "G", "C"] # Make the Monty Hall game repeat 6 times. for i in range(6): @@ -46,8 +47,8 @@ # removes user's choice so that it won't be opened, # but keeps in the element to not mess up the indices - reveal_doors[choice - 1] = '-' - goat_door = reveal_doors.index('G') + 1 + reveal_doors[choice - 1] = "-" + goat_door = reveal_doors.index("G") + 1 doors_left.remove(goat_door) print("Monty opens door", goat_door, "to reveal a goat!") @@ -58,11 +59,11 @@ print("Enter 'y' to switch, or 'n' to keep your first choice.") switch = input("> ") - if switch == 'y': + if switch == "y": choice = doors_left[0] # The prize behind the user's ultimate choice is revealed! - if doors[choice - 1] == 'C': + if doors[choice - 1] == "C": print("You got... a car! Congratulations!") else: print("You got... a goat! Better luck next time!") diff --git a/1_beginner/chapter6/solutions/names.py b/1_beginner/chapter6/solutions/names.py new file mode 100644 index 00000000..ef98419a --- /dev/null +++ b/1_beginner/chapter6/solutions/names.py @@ -0,0 +1,30 @@ +""" +Names + +Make a list called people and fill it with +at least 6 names. Make another list and use +list slicing to fill it with every other name +from the original list, starting with the 1st name. +Print both lists. +""" + +people = ["Mark", "Anya", "Wan", "Jewel", "Stef", "Hank"] + +# Answers may vary. +# Some other possible answers: +# group = people[0, 5, 2] or people[0, len(people), 2] + +group = people[0 : len(people) : 2] + +print(people) +print(group) + +""" +Use a for loop to ask the user to add 4 names +to the list. After you ask for each name, print +out the last 5 names of the list. +""" + +for i in range(4): + people.append(input("Enter a name: ")) + print("Last 5 names:", people[-5:]) diff --git a/1_beginner/chapter6/solutions/restaurant.py b/1_beginner/chapter6/solutions/restaurant.py new file mode 100644 index 00000000..1da48666 --- /dev/null +++ b/1_beginner/chapter6/solutions/restaurant.py @@ -0,0 +1,126 @@ +""" +Restaurant +Write a program that asks someone +what they want to order and give them +the total cost of their meal. + +Each meal should have 3 categories +(ex. food, drinks, desserts), and the user +must order 1 item from each category. + +Make sure to include a 7% sales tax +(multiply the total by 1.07), and +round the answer to 2 decimal places + +The steps are outlined in the following code. +""" + +""" +1. Store the menu in lists. +Each of the 3 categories should have an +items menu and a costs menu. + +Example of the 6 lists you need to create: +foods, food_costs, drinks, drink_costs, +desserts, dessert_costs +""" + +foods = ["pancakes", "waffles", "toast"] +food_costs = [5, 3, 100] + +drinks = ["juice", "water", "tea"] +drink_costs = [2, 50, 1] + +sugar_foods = ["muffin", "lollipop", "brownie"] +sugar_costs = [4, 20, 15] + +""" +2. Display the menu. +Iterate through the items and costs for each +category to do this. +""" + +print("Welcome to my restaurant! Here's the menu:") +print("Foods:") +for i in range(len(foods)): + print(foods[i] + ": $" + str(food_costs[i])) +print() + +print("Drinks:") +for i in range(len(drinks)): + print(drinks[i] + ": $" + str(drink_costs[i])) +print() + +print("Sugar:") +for i in range(len(sugar_foods)): + print(sugar_foods[i] + ": $" + str(sugar_costs[i])) +print() + +print("Order in all lowercase!\n") + +""" +3. Ask the user to order. +This code should be in a loop. After you display the +user's total at the end, ask them if they want to +order again. If they say "no", the program should end. +Otherwise, you should take their order and display the +new total again. + +As you take their order, check if what they ordered +is in the corresponding list for that category. +If it is, add the price of the item to the total. +Otherwise, display a warning message and add $1000 to the total. + +4. Finalize the total. +Add a 7% sales tax to your sum, and +round this value to 2 decimal places. +Display the total. + +5. As mentioned in Step 3, ask the user if they want +to order again. If they say "no", then stop the program. +Otherwise, let them order again. +""" + +# Take the user's order. +while True: + cost = 0 + + # Foods + food = input("What food would you like? ") + + if food in foods: + cost += food_costs[foods.index(food)] + else: + print("You didn't order a proper food... Adding $1000 to tab.") + cost += 1000 + + # Drinks + drink = input("What drink would you like? ") + + if drink in drinks: + cost += drink_costs[drinks.index(drink)] + else: + print("You didn't order a proper drink... Adding $1000 to tab.") + cost += 1000 + + # Sugar + sugar = input("What sugar item would you like? ") + + if sugar in sugar_foods: + cost += sugar_costs[sugar_foods.index(sugar)] + else: + print("You didn't order a proper sugary item! Adding $1000 to tab.") + cost += 1000 + + # Sales tax + cost *= 1.07 + + # Display output + print("Your total is $%.2f." % cost) + print() + + # Ask if the user wants to order again + ans = input('Do you want to order again ("yes" or "no")? ') + print() + if ans == "no": + break diff --git a/1_beginner/chapter6/solutions/snookle_game.py b/1_beginner/chapter6/solutions/snookle_game.py index aeea2135..583f633e 100644 --- a/1_beginner/chapter6/solutions/snookle_game.py +++ b/1_beginner/chapter6/solutions/snookle_game.py @@ -25,13 +25,13 @@ while not win: for num in nums: # prompt user to add or subtract current num - print('main number is currently ' + str(main)) + print("main number is currently " + str(main)) choice = input("[add] or [subtract] " + str(num) + "?\n> ") # update main value based on choice - if choice == 'add': + if choice == "add": main += num - elif choice == 'subtract': + elif choice == "subtract": main -= num # If the main number if 12, the user has won! @@ -39,4 +39,4 @@ win = True # Exit while loop and end game break # Exit for loop -print('Congrats you won the game!') +print("Congrats you won the game!") diff --git a/1_beginner/chapter6/solutions/sum_list.py b/1_beginner/chapter6/solutions/sum_list.py index 3a5ae513..e027baeb 100644 --- a/1_beginner/chapter6/solutions/sum_list.py +++ b/1_beginner/chapter6/solutions/sum_list.py @@ -10,4 +10,4 @@ for num in numbers: sum += num -print('Sum of elements in list:', sum) +print("Sum of elements in list:", sum) diff --git a/1_beginner/chapter6/solutions/too_long.py b/1_beginner/chapter6/solutions/too_long.py index a32b2097..3c17d7e3 100644 --- a/1_beginner/chapter6/solutions/too_long.py +++ b/1_beginner/chapter6/solutions/too_long.py @@ -3,9 +3,13 @@ Print and remove all elements with length greater than 4 in a given list of strings. """ -the_list = ['dragon', 'cab', 'science', 'dove', 'lime', 'river', 'pop'] +the_list = ["dragon", "cab", "science", "dove", "lime", "river", "pop"] -for x in the_list: # iterates through every element in the_list - if len(x) > 4: # if element length is greater than 4 - print(x) # prints element - the_list.remove(x) # removes element +to_remove = [] +for x in the_list: # iterates through every element in the list + if len(x) > 4: # if the element length is greater than 4 + print(x) # prints the element + to_remove.append(x) # appends element to remove list + +for y in to_remove: # iterates through every element meant to be removed + the_list.remove(y) # removes element from list diff --git a/1_beginner/chapter7/examples/string_manipulation.py b/1_beginner/chapter7/examples/string_manipulation.py index efeab443..99c3a6e5 100644 --- a/1_beginner/chapter7/examples/string_manipulation.py +++ b/1_beginner/chapter7/examples/string_manipulation.py @@ -44,6 +44,9 @@ my_string = "hello" print(my_string[2]) # prints 'l' print(my_string[2:4]) # prints 'll' +# start: 2 (inclusive), stop: 4 (exclusive), default step of 1 +print(my_string[-1:-3:-1]) # prints 'ol' +# start: -1 (inclusive), stop: -3 (exclusive), step of -1 for char in my_string: print(char) # prints each character on its own line diff --git a/1_beginner/chapter7/practice/capital.py b/1_beginner/chapter7/practice/capital.py new file mode 100644 index 00000000..56372834 --- /dev/null +++ b/1_beginner/chapter7/practice/capital.py @@ -0,0 +1,14 @@ +""" +Capital + +Write a program that takes a string as input, +makes every other letter capital, sets the rest +of the characters to be lowercase, and displays +the new string. + +Hint: Make sure you don't count non-alphabetic +characters. + +Example input: I love Zee the Cat. +Example output: I lOvE zEe ThE cAt. +""" diff --git a/1_beginner/chapter7/practice/every_other_word.py b/1_beginner/chapter7/practice/every_other_word.py new file mode 100644 index 00000000..dd6fffa1 --- /dev/null +++ b/1_beginner/chapter7/practice/every_other_word.py @@ -0,0 +1,8 @@ +""" +Every Other Word + +Write a program that takes a sentence +as input and prints every other word. +""" + +# Insert your code here. diff --git a/1_beginner/chapter7/practice/first_three_words.py b/1_beginner/chapter7/practice/first_three_words.py index d8c7e4b1..53205f94 100644 --- a/1_beginner/chapter7/practice/first_three_words.py +++ b/1_beginner/chapter7/practice/first_three_words.py @@ -1,10 +1,10 @@ -''' +""" First Three Words Write a program which asks the user to enter a sentence. Print the first three words in the sentence. (Assume the user enters at least 3 words.) -''' +""" # write code here diff --git a/1_beginner/chapter7/practice/ingly.py b/1_beginner/chapter7/practice/ingly.py index aed54ccc..6f8f9abe 100644 --- a/1_beginner/chapter7/practice/ingly.py +++ b/1_beginner/chapter7/practice/ingly.py @@ -1,4 +1,4 @@ -''' +""" Ingly Write a Python program to add 'ing' @@ -9,6 +9,6 @@ Adapted from W3Resource, problem 6: https://www.w3resource.com/python-exercises/string/ -''' +""" # write code here diff --git a/1_beginner/chapter7/practice/phone_number.py b/1_beginner/chapter7/practice/phone_number.py new file mode 100644 index 00000000..425f458e --- /dev/null +++ b/1_beginner/chapter7/practice/phone_number.py @@ -0,0 +1,22 @@ +""" +Phone Number + +Write a program that asks the user to input a phone number. +Strip their input to get rid of any accidental spaces. + +If the input has anything besides digits or the input +isn’t exactly 10 digits long, The program should keep asking them +for a phone number until the input is formatted correctly. + +Display the phone number at the end. + +Example program run: +Enter a phone number (10 digits): 732-000-0000 +Enter a phone number (10 digits): abcdeabcde +Enter a phone number (10 digits): (908)9999999 +Enter a phone number (10 digits): 732000000 +Enter a phone number (10 digits): 1234567891 +Your number is 1234567891 +""" + +# Insert your code here. diff --git a/1_beginner/chapter7/practice/replace.py b/1_beginner/chapter7/practice/replace.py index a76ebc8a..86338be9 100644 --- a/1_beginner/chapter7/practice/replace.py +++ b/1_beginner/chapter7/practice/replace.py @@ -1,15 +1,17 @@ -''' +""" Replace -Write a Python program to print a string -from a given string where all occurrences -of its first char have been changed to '$', +Write a Python program that asks the user for a string +and then prints a version of that string +where all occurrences of its first char +have been changed to '$', except the first char itself. -Sample String : 'restart' -Expected Result : 'resta$t' + +Sample Input: 'restart' +Expected Output: 'resta$t' Adapted from W3Resource, problem 4: https://www.w3resource.com/python-exercises/string/ -''' +""" # write code here diff --git a/1_beginner/chapter7/practice/reverse_alphabet.py b/1_beginner/chapter7/practice/reverse_alphabet.py new file mode 100644 index 00000000..3bb59eea --- /dev/null +++ b/1_beginner/chapter7/practice/reverse_alphabet.py @@ -0,0 +1,14 @@ +""" +Reverse Alphabet (Challenge Problem) + +Create a list of strings by asking the user +to provide 10 inputs. Sort these in reverse +alphabetical order, and display the result. + +Note: "Cat" will come before "dog" because of ASCII values. + +To sort while IGNORING case, you might want to create +another list, make the elements all uppercase or all lowercase, +sort this list, and figure out how to use this list to +sort the original list. +""" diff --git a/1_beginner/chapter7/practice/upper.py b/1_beginner/chapter7/practice/upper.py index 2894d162..18ea29b9 100644 --- a/1_beginner/chapter7/practice/upper.py +++ b/1_beginner/chapter7/practice/upper.py @@ -1,6 +1,7 @@ # Upper # Continuously ask a user to enter words. -# (Make sure that the input given is actually just 1 word.) +# You should remove leading/trailing whitespace, and then +# make sure that the word is only made up of letters. # Store the words in a list. # Stop asking the user for words if they enter an empty string # (the string has no characters or is completely whitespace). diff --git a/1_beginner/chapter7/practice/vowels.py b/1_beginner/chapter7/practice/vowels.py index 7bb9d437..f98230f2 100644 --- a/1_beginner/chapter7/practice/vowels.py +++ b/1_beginner/chapter7/practice/vowels.py @@ -1,9 +1,9 @@ -''' +""" Vowels Create a program which takes a string from the user and prints the number of vowels that are in the string. -''' +""" # write code here diff --git a/1_beginner/chapter7/solutions/capital.py b/1_beginner/chapter7/solutions/capital.py new file mode 100644 index 00000000..6202367f --- /dev/null +++ b/1_beginner/chapter7/solutions/capital.py @@ -0,0 +1,31 @@ +""" +Capital + +Write a program that takes a string as input, +makes every other letter capital, sets the rest +of the characters to be lowercase, and displays +the new string. + +Hint: Make sure you don't count non-alphabetic +characters. + +Example input: I love Zee the Cat. +Example output: I lOvE zEe ThE cAt. +""" + +str = input("Enter a string: ") + +new_str = "" +letter_count = 0 # Used to avoid counting non-alpha characters. + +for c in str: + if c.isalpha(): + if letter_count % 2 == 0: + new_str += c.upper() + else: + new_str += c.lower() + letter_count += 1 + else: + new_str += c + +print(new_str) diff --git a/1_beginner/chapter7/solutions/every_other_word.py b/1_beginner/chapter7/solutions/every_other_word.py new file mode 100644 index 00000000..45e11a82 --- /dev/null +++ b/1_beginner/chapter7/solutions/every_other_word.py @@ -0,0 +1,17 @@ +""" +Every Other Word + +Write a program that takes a sentence +as input and prints every other word. + +Example input: I like cats, dogs, and pizza. +Example output: +I +cats, +and +""" + +sentence = input("Enter a sentence: ") +words = sentence.split() +for i in range(0, len(words), 2): + print(words[i]) diff --git a/1_beginner/chapter7/solutions/first_three_words.py b/1_beginner/chapter7/solutions/first_three_words.py index f9c20694..d8454e30 100644 --- a/1_beginner/chapter7/solutions/first_three_words.py +++ b/1_beginner/chapter7/solutions/first_three_words.py @@ -1,13 +1,13 @@ -''' +""" First Three Words Write a program which asks the user to enter a sentence. Print the first three words in the sentence. (Assume the user enters at least 3 words.) -''' +""" -sentence = input('Enter a sentence: ') +sentence = input("Enter a sentence: ") words = sentence.split() diff --git a/1_beginner/chapter7/solutions/ingly.py b/1_beginner/chapter7/solutions/ingly.py index 32991574..2c018ea0 100644 --- a/1_beginner/chapter7/solutions/ingly.py +++ b/1_beginner/chapter7/solutions/ingly.py @@ -1,4 +1,4 @@ -''' +""" Ingly Write a Python program to add 'ing' @@ -9,14 +9,14 @@ Adapted from W3Resource, problem 6: https://www.w3resource.com/python-exercises/string/ -''' +""" -string = input('Enter a string: ') +string = input("Enter a string: ") if len(string) >= 3: - if string[-3:] != 'ing': - string += 'ing' + if string[-3:] != "ing": + string += "ing" else: - string += 'ly' + string += "ly" print(string) diff --git a/1_beginner/chapter7/solutions/phone_number.py b/1_beginner/chapter7/solutions/phone_number.py new file mode 100644 index 00000000..951e4c3e --- /dev/null +++ b/1_beginner/chapter7/solutions/phone_number.py @@ -0,0 +1,26 @@ +""" +Phone Number + +Write a program that asks the user to input a phone number. +Strip their input to get rid of any accidental spaces. + +If the input has anything besides digits or the input +isn’t exactly 10 digits long, The program should keep asking them +for a phone number until the input is formatted correctly. + +Display the phone number at the end. + +Example program run: +Enter a phone number (10 digits): 732-000-0000 +Enter a phone number (10 digits): abcdeabcde +Enter a phone number (10 digits): (908)9999999 +Enter a phone number (10 digits): 732000000 +Enter a phone number (10 digits): 1234567891 +Your number is 1234567891 +""" + +number = "" +while len(number) != 10 or not number.isdigit(): + number = input("Enter a phone number (10 digits): ") + +print("Your number is", number) diff --git a/1_beginner/chapter7/solutions/replace.py b/1_beginner/chapter7/solutions/replace.py index 3058adf6..68bf0b37 100644 --- a/1_beginner/chapter7/solutions/replace.py +++ b/1_beginner/chapter7/solutions/replace.py @@ -1,26 +1,27 @@ -''' +""" Replace -Write a Python program to print a string -from a given string where all occurrences -of its first char have been changed to '$', +Write a Python program that asks the user for a string +and then prints a version of that string +where all occurrences of its first char +have been changed to '$', except the first char itself. -Sample String: 'restart' -Expected Result: 'resta$t' +Sample Input: 'restart' +Expected Output: 'resta$t' Adapted from W3Resource, problem 4: https://www.w3resource.com/python-exercises/string/ -''' +""" -string = input('Enter a string: ') +string = input("Enter a string: ") first_char = string[0] result = first_char for i in range(1, len(string)): if string[i] == first_char: - result += '$' + result += "$" else: result += string[i] diff --git a/1_beginner/chapter7/solutions/reverse_alphabet.py b/1_beginner/chapter7/solutions/reverse_alphabet.py new file mode 100644 index 00000000..13b1170b --- /dev/null +++ b/1_beginner/chapter7/solutions/reverse_alphabet.py @@ -0,0 +1,38 @@ +""" +Reverse Alphabet (Challenge Problem) + +Create a list of strings by asking the user +to provide 10 inputs. Sort these in reverse +alphabetical order, and display the result. + +Note: "Cat" will come before "dog" because of ASCII values. + +To sort while IGNORING case, you might want to create +another list, make the elements all uppercase or all lowercase, +sort this list, and figure out how to use this list to +sort the original list. + +""" + +strings = [] + +# Get user input. +for i in range(10): + strings.append(input("Enter a string: ")) + +# Create a lowercase version of strings. +lower_strings = [] +for str in strings: + lower_strings.append(str.lower()) +lower_strings.sort() + +# Set the position of each string in strings to the +# position of the lowercase string in lower_strings. +sorted_strings = strings.copy() +for str in strings: + # i is the goal index of str. + i = lower_strings.index(str.lower()) + sorted_strings[i] = str + +# Display the sorted list. +print(sorted_strings) diff --git a/1_beginner/chapter7/solutions/upper.py b/1_beginner/chapter7/solutions/upper.py index 1d10b83b..6594205f 100644 --- a/1_beginner/chapter7/solutions/upper.py +++ b/1_beginner/chapter7/solutions/upper.py @@ -1,6 +1,7 @@ # Upper # Continuously ask a user to enter words. -# (Make sure that the input given is actually just 1 word.) +# You should remove leading/trailing whitespace, and then +# make sure that the word is only made up of letters. # Store the words in a list. # Stop asking the user for words if they enter an empty string # (the string has no characters or is completely whitespace). diff --git a/1_beginner/chapter7/solutions/vowels.py b/1_beginner/chapter7/solutions/vowels.py index 10b413ed..9ded1707 100644 --- a/1_beginner/chapter7/solutions/vowels.py +++ b/1_beginner/chapter7/solutions/vowels.py @@ -1,14 +1,14 @@ -''' +""" Vowels Create a program which takes a string from the user and prints the number of vowels that are in the string. -''' -VOWELS = 'aeiou' +""" +VOWELS = "aeiou" # Ask user for a string -string = input('Enter a string: ') +string = input("Enter a string: ") # Count the number of vowels in the string number_of_vowels = 0 @@ -17,4 +17,4 @@ number_of_vowels += 1 # Print number of vowels -print('Number of vowels:', number_of_vowels) +print("Number of vowels:", number_of_vowels) diff --git a/2_intermediate/chapter10/examples/2d_lists.py b/2_intermediate/chapter10/examples/2d_lists.py index 51f68b34..8f53ef52 100644 --- a/2_intermediate/chapter10/examples/2d_lists.py +++ b/2_intermediate/chapter10/examples/2d_lists.py @@ -1,10 +1,10 @@ # 2D Lists my_list = [ - ['hello', 'world', 'code'], - ['docs', 'slides', 'sheets'], - ['google', 'amazon', 'facebook'], - ['this', 'is', 'python'] + ["hello", "world", "code"], + ["docs", "slides", "sheets"], + ["google", "amazon", "facebook"], + ["this", "is", "python"], ] print(my_list[1][2]) # prints 'sheets' diff --git a/2_intermediate/chapter10/examples/nested_loop.py b/2_intermediate/chapter10/examples/nested_loop.py index f4a5db5f..dd2a3d15 100644 --- a/2_intermediate/chapter10/examples/nested_loop.py +++ b/2_intermediate/chapter10/examples/nested_loop.py @@ -2,10 +2,10 @@ # Traversing 2D Lists my_list = [ - ['hello', 'world', 'code'], - ['docs', 'slides', 'sheets'], - ['google', 'amazon', 'facebook'], - ['this', 'is', 'python'] + ["hello", "world", "code"], + ["docs", "slides", "sheets"], + ["google", "amazon", "facebook"], + ["this", "is", "python"], ] # print each element in my_list diff --git a/2_intermediate/chapter10/practice/address.py b/2_intermediate/chapter10/practice/address.py new file mode 100644 index 00000000..3234b99e --- /dev/null +++ b/2_intermediate/chapter10/practice/address.py @@ -0,0 +1,17 @@ +""" +Address + +Create a 2D list where each row represents a +person and has 3 elements: their name, their age, +and their address. + +The entire list should have 4 such entries (4 people), +so it will be a 4x3 list. + +Display the name and address of the 2nd person in the list. + +Then, display the entire list with the format: +name (age): address +""" + +# Insert your code here. diff --git a/2_intermediate/chapter10/practice/img_avg.py b/2_intermediate/chapter10/practice/img_avg.py new file mode 100644 index 00000000..2b71c3b3 --- /dev/null +++ b/2_intermediate/chapter10/practice/img_avg.py @@ -0,0 +1,83 @@ +""" +Image Average + +Here is the challenge problem for nested loops: +Images are often represented as 3D lists. +The outer list is the entire image. +The 1st level inner list is a row of pixels. +The 2nd level inner list is the RGB values for that pixel. +RGB (red, green, blue) values determine the color of the pixel. + +The interesting thing is that we can iterate over images. +The challenge is: given an image, create a program that +will return a different image where each pixel is the average +of the pixels surrounding it in the original image. + +To find the average value of all of a pixels neighbors, you must +calculate the average of the red values, blue values, and green values. +For example, if the neighbors of a pixel with value [1, 2, 3] +were [20, 30, 40] and [10, 120, 30], the new pixel that would replace the +original one would be [15, 75, 35] (since the average of 20 and 10 is 15, +the average of 30 and 120 is 75, and the average of 40 and 30 is 35). + +EXAMPLE: An image with 9 pixels may look like: +[ + [ + [31, 41, 42], [51, 1, 101], [24, 141, 33] + ], + + [ + [50, 21, 28], [31, 49, 201], [90, 54, 33] + ], + + [ + [12, 81, 3], [22, 8, 91], [101, 141, 132] + ] +] + +HINT: Don't forget that a pixel may have varying amount of neighboring +pixels. A pixel at the edge, for example, has 3 neighboring pixels while +a pixel at the center of the image has 8 neighboring pixels (one on each +of its 4 sides, and then one at each of its 4 corners). +""" + +# Import libraries needed to run the program +# Before importing the libraries, you must have them installed. +# This problem requires the following libraries: +# pillow, requests, numpy, and matplotlib +# If you don't already have them installed, open your command prompt or terminal +# and please do +# this: pip install -U (library) (any other libraries, each separated by a space) +# ex: pip install -U numpy matplotlib requests pillow +# Note: on some windows machines, you may need to +# do: py -m pip install -U (library) (any other libraries, each separated by a space) + +from PIL import Image +import requests +import numpy +import matplotlib.pyplot as plt + +# Code that grabs the image from the internet and makes it into an array +IMAGE_URL = ( + "https://images.dog.ceo/breeds/waterdog-spanish/20180723_185544.jpg" +) +img = numpy.array( + Image.open(requests.get(IMAGE_URL, stream=True).raw) +).tolist() + +# create newimg as an empty list so that we'll know if something went wrong +# ie. if we try to display it and the function didn't run, we'd get an +# invalid shape error +newimg = [[[] for column in row] for row in img] + +# Code that displays the original image +print("now displaying the original image") +plt.imshow(img) +plt.show() + +# Write code to create newimg here + +# Code that displays the new image at the end +print("now displaying the new image") +plt.imshow(newimg) +plt.show() diff --git a/2_intermediate/chapter10/practice/odd_sum.py b/2_intermediate/chapter10/practice/odd_sum.py new file mode 100644 index 00000000..a07d215b --- /dev/null +++ b/2_intermediate/chapter10/practice/odd_sum.py @@ -0,0 +1,11 @@ +# Odd Sum +# Given a 2D list, find the sum of all elements at odd indexes for all +# the lists at odd indexes. Print this sum times the sum of all +# first element of all the 1D lists in the 2D list. +# +# Ex:[[1,2,3,6],[2,41,2,1]]should have print 42 after the program runs. +# +# Write the code below. + +two_d_list = [[1, 2, 3, 5, 2], [2, 3, 1, 4], [2, 3, 1, 2, 21], [21, 3, 1, 41]] +# two_d_list should print 51 after the program runs. diff --git a/2_intermediate/chapter10/practice/print_even.py b/2_intermediate/chapter10/practice/print_even.py index 425767a5..60e873c9 100644 --- a/2_intermediate/chapter10/practice/print_even.py +++ b/2_intermediate/chapter10/practice/print_even.py @@ -6,12 +6,12 @@ # if you did it right! my_list = [ - ['awesome', 'hello', 'job', 'world'], - ['you', 'words', 'got', 'books'], - ['it', 'python', 'right'], - ['keep', 'plant', 'learning'], - ['how', 'school', 'to'], - ['code'] + ["awesome", "hello", "job", "world"], + ["you", "words", "got", "books"], + ["it", "python", "right"], + ["keep", "plant", "learning"], + ["how", "school", "to"], + ["code"], ] # write code here diff --git a/2_intermediate/chapter10/practice/random_grid.py b/2_intermediate/chapter10/practice/random_grid.py new file mode 100644 index 00000000..d579d720 --- /dev/null +++ b/2_intermediate/chapter10/practice/random_grid.py @@ -0,0 +1,40 @@ +""" +Random Grid + +Create a 2D list with 4 rows and a randomly +determined number of columns. The column +number should be a random EVEN number between +2 and 16 (inclusive). + +All the even column numbers (including 0) should +be filled with asterisks (*). The odd numbered +columns should be filled with underscores (_). + +Display the grid at the end by printing out +elements individually: don't use print(list). +Assume that you don't know the size of the grid +beforehand. In other words, if you wanted to display +the 2D list without knowing the number of rows and +columns in it, how would you code this? + +For example, a 4x6 grid would display this: +*_*_*_ +*_*_*_ +*_*_*_ + +This might be useful: +print("a") +print("a") +would display the "a"s with newlines: +a +a + +print("a", end=" ") +print("a") +changes the end of the first "a" from a newline to a space. +The output is this: +a a + +""" + +# Insert your code here. diff --git a/2_intermediate/chapter10/practice/smooth_max.py b/2_intermediate/chapter10/practice/smooth_max.py new file mode 100644 index 00000000..6530e8ae --- /dev/null +++ b/2_intermediate/chapter10/practice/smooth_max.py @@ -0,0 +1,9 @@ +# Given a 2D list, let's call a element "smooth" if index of the +# element in its 1D list plus the element is even. For example, +# given the 2D list [[0,4][2,6]], the 1st element of each of the +# 1D list is considered "smooth" because 0 + 0 is 0 and 0 + 2 is 2 +# (both are even numbers). Find the maximum "smooth" element and +# print it. Using the example [[0,4][2,6]] again, the maximum +# "smooth" element is 2 because 2 is bigger than 0. + +two_d_list = [[425, 214, 412, 123], [312, 214, 123, 343]] diff --git a/2_intermediate/chapter10/solutions/address.py b/2_intermediate/chapter10/solutions/address.py new file mode 100644 index 00000000..50e69f13 --- /dev/null +++ b/2_intermediate/chapter10/solutions/address.py @@ -0,0 +1,30 @@ +""" +Address + +Create a 2D list where each row represents a +person and has 3 elements: their name, their age, +and their address. + +The entire list should have 4 such entries (4 people), +so it will be a 4x3 list. + +Display the name and address of the 2nd person in the list. + +Then, display the entire list with the format: +name (age): address +""" + +contacts = [ + ["Jeremy", 10, "45 Pancake Road"], + ["Nicey", 18, "111 Cupcake Street"], + ["Hawthorne", 15, "19 Sinister Avenue"], + ["Nilah", 14, "Banks of the Nile River"], +] + +# 2nd person +print(contacts[1][0] + ": " + contacts[1][2]) +print() + +# Display the entire list. +for contact in contacts: + print(contact[0] + " (%d): " % contact[1] + contact[2]) diff --git a/2_intermediate/chapter10/solutions/img_avg.py b/2_intermediate/chapter10/solutions/img_avg.py new file mode 100644 index 00000000..66077ed6 --- /dev/null +++ b/2_intermediate/chapter10/solutions/img_avg.py @@ -0,0 +1,162 @@ +""" +Image Average + +Here is the challenge problem for nested loops: +Images are often represented as 3D lists. +The outer list is the entire image. +The 1st level inner list is a row of pixels. +The 2nd level inner list is the RGB values for that pixel. +RGB (red, green, blue) values determine the color of the pixel. + +The interesting thing is that we can iterate over images. +The challenge is: given an image, create a program that +will return a different image where each pixel is the average +of the pixels surrounding it in the original image. + +To find the average value of all of a pixels neighbors, you must +calculate the average of the red values, blue values, and green values. +For example, if the neighbors of a pixel with value [1, 2, 3] +were [20, 30, 40] and [10, 120, 30], the new pixel that would replace the +original one would be [15, 75, 35] (since the average of 20 and 10 is 15, +the average of 30 and 120 is 75, and the average of 40 and 30 is 35). + +EXAMPLE: An image with 9 pixels may look like: +[ + [ + [31, 41, 42], [51, 1, 101], [24, 141, 33] + ], + + [ + [50, 21, 28], [31, 49, 201], [90, 54, 33] + ], + + [ + [12, 81, 3], [22, 8, 91], [101, 141, 132] + ] +] + +HINT: Don't forget that a pixel may have varying amount of neighboring +pixels. A pixel at the edge, for example, has 3 neighboring pixels while +a pixel at the center of the image has 8 neighboring pixels (one on each +of its 4 sides, and then one at each of its 4 corners). +""" + +# Import libraries needed to run the program +# Before importing the libraries, you must have them installed. +# This problem requires the following libraries: +# pillow, requests, numpy, and matplotlib +# If you don't already have them installed, open your command prompt or terminal +# and please do +# this: pip install -U (library) (any other libraries, each separated by a space) +# ex: pip install -U numpy matplotlib requests pillow +# Note: on some windows machines, you may need to +# do: py -m pip install -U (library) (any other libraries, each separated by a space) + + +from PIL import Image +import requests +import numpy +import matplotlib.pyplot as plt + +# Code that grabs the image from the internet and makes it into an array +IMAGE_URL = ( + "https://images.dog.ceo/breeds/waterdog-spanish/20180723_185544.jpg" +) +img = numpy.array( + Image.open(requests.get(IMAGE_URL, stream=True).raw) +).tolist() + +# create newimg as an empty list so that we'll know if something went wrong +# ie. if we try to display it and the function didn't run, we'd get an +# invalid shape error +newimg = [[[] for column in row] for row in img] + +# Code that displays the original image +print("now displaying the original image") +plt.imshow(img) +plt.show() + + +def distort(original_image, new_image): + """ + Modifies new_image so that each pixel in new_image + will be the average of the surrounding + DISTORTION_RADIUS pixels. + DISTORTION_RADIUS can be changed for more/less distortion. + Arguments: + original_image (list or tuple) - the reference image. + new_image (list) - the image to modify. + """ + DISTORTION_RADIUS = 1 # this should be a positive integer + # Note that each increase of DISTORTION_RADIUS increases + # run time amazingly. Slower PC's should stick to values like + # 1 or 2 for DISTORTION_RADIUS + + for row in range(len(original_image)): + for column in range(len(original_image[0])): + # we set these to empty lists because the for loops + # will iterate through all valid relative indexes + # (including 0) and append them to these lists. + x_relative_indexes = [] + y_relative_indexes = [] + + # handle y relative indexes + # +1 to DISTORTION_RADIUS because stop is exclusive + for relative_y in range(-DISTORTION_RADIUS, DISTORTION_RADIUS + 1): + if ( + row + relative_y < 0 + or row + relative_y > len(original_image) - 1 + ): + # ignore relative indexes that are out of range of the + # original image + continue + # if it isn't out of range, it's valid and should be appended + y_relative_indexes.append(relative_y) + + # handle x relative indexes + # +1 to DISTORTION_RADIUS because stop is exclusive + for relative_x in range(-DISTORTION_RADIUS, DISTORTION_RADIUS + 1): + if ( + column + relative_x < 0 + or column + relative_x > len(original_image[0]) - 1 + ): + # ignore relative indexes that are out of range of the + # original image + continue + # if it isn't out of range, it's valid and should be appended + x_relative_indexes.append(relative_x) + + # at this point, x_relative_indexes and y_relative_indexes are + # complete, so now we use them. + r_total = g_total = b_total = counter = 0 # initialize variables + for x in x_relative_indexes: + for y in y_relative_indexes: + # since images are 'rgb': + # red is the first val + r_total += original_image[row + y][column + x][0] + + # green is the second val + g_total += original_image[row + y][column + x][1] + + # blue is third val + b_total += original_image[row + y][column + x][2] + + counter += 1 + + # round because images don't deal w/ floats, only integers + r_avg = round(r_total / counter) + g_avg = round(g_total / counter) + b_avg = round(b_total / counter) + + # update the pixel in newimg to match the average of its + # surrounding pixels + new_image[row][column] = [r_avg, g_avg, b_avg] + + +print("now modifying file. Depending on your pc, this may take a while.") +distort(img, newimg) + +# Code that displays the new image at the end +print("now displaying the new image") +plt.imshow(newimg) +plt.show() diff --git a/2_intermediate/chapter10/solutions/odd_sum.py b/2_intermediate/chapter10/solutions/odd_sum.py new file mode 100644 index 00000000..eff7cc7e --- /dev/null +++ b/2_intermediate/chapter10/solutions/odd_sum.py @@ -0,0 +1,22 @@ +# Odd Sum +# Given a 2D list, find the sum of all elements at odd indexes for all +# the lists at odd indexes. Print this sum times the sum of all +# first element of all the 1D lists in the 2D list. +# +# Ex:[[1,2,3,6],[2,41,2,1]]should have print 42 after the program runs. +# +# Write the code below. + +two_d_list = [[1, 2, 3, 5, 2], [2, 3, 1, 4], [2, 3, 1, 2, 21], [21, 3, 1, 41]] +# two_d_list should print 51 after the program runs. + +odd_sum = 0 +for outer_idx in range(1, len(two_d_list), 2): + for inner_idx in range(1, len(two_d_list[outer_idx]), 2): + odd_sum += two_d_list[outer_idx][inner_idx] + +first_sum = 0 +for inner_list in range(len(two_d_list)): + first_sum += two_d_list[inner_list][0] + +print(odd_sum * first_sum) diff --git a/2_intermediate/chapter10/solutions/print_even.py b/2_intermediate/chapter10/solutions/print_even.py index 92ed7a4e..29a4969f 100644 --- a/2_intermediate/chapter10/solutions/print_even.py +++ b/2_intermediate/chapter10/solutions/print_even.py @@ -6,12 +6,12 @@ # if you did it right! my_list = [ - ['awesome', 'hello', 'job', 'world'], - ['you', 'words', 'got', 'books'], - ['it', 'python', 'right'], - ['keep', 'plant', 'learning'], - ['how', 'school', 'to'], - ['code'] + ["awesome", "hello", "job", "world"], + ["you", "words", "got", "books"], + ["it", "python", "right"], + ["keep", "plant", "learning"], + ["how", "school", "to"], + ["code"], ] for words in my_list: diff --git a/2_intermediate/chapter10/solutions/random_grid.py b/2_intermediate/chapter10/solutions/random_grid.py new file mode 100644 index 00000000..934122d9 --- /dev/null +++ b/2_intermediate/chapter10/solutions/random_grid.py @@ -0,0 +1,54 @@ +""" +Random Grid + +Create a 2D list with 4 rows and a randomly +determined number of columns. The column +number should be a random EVEN number between +2 and 16 (inclusive). + +All the even column numbers (including 0) should +be filled with asterisks (*). The odd numbered +columns should be filled with underscores (_). + +Display the grid at the end by printing out +elements individually: don't use print(list). +Assume that you don't know the size of the grid +beforehand. In other words, if you wanted to display +the 2D list without knowing the number of rows and +columns in it, how would you code this? + +For example, a 4x6 grid would display this: +*_*_*_ +*_*_*_ +*_*_*_ + +This might be useful: +print("a") +print("a") +would display the "a"s with newlines: +a +a + +print("a", end=" ") +print("a") +changes the end of the first "a" from a newline to a space. +The output is this: +a a + +""" +import random + +grid = [] +cols = random.randint(1, 8) * 2 + +# Fill the grid 2D list. +for row in range(4): + grid.append([]) + for col in range(cols): + grid[row].append("*" if (col % 2 == 0) else "_") + +# Display the grid without knowing the size beforehand. +for row in grid: + for col in row: + print(col, end="") + print() diff --git a/2_intermediate/chapter10/solutions/smooth_max.py b/2_intermediate/chapter10/solutions/smooth_max.py new file mode 100644 index 00000000..a61465f6 --- /dev/null +++ b/2_intermediate/chapter10/solutions/smooth_max.py @@ -0,0 +1,20 @@ +# Given a 2D list, let's call a element "smooth" if index of the +# element in its 1D list plus the element is even. For example, +# given the 2D list [[0,4][2,6]], the 1st element of each of the +# 1D list is considered "smooth" because 0 + 0 is 0 and 0 + 2 is 2 +# (both are even numbers). Find the maximum "smooth" element and +# print it. Using the example [[0,4][2,6]] again, the maximum +# "smooth" element is 2 because 2 is bigger than 0. + +two_d_list = [[425, 214, 412, 123], [312, 214, 123, 343]] +curr_max = None + +for outer_idx in range(len(two_d_list)): + for inner_idx in range(len(two_d_list[outer_idx])): + curr_elem = two_d_list[outer_idx][inner_idx] + to_check = curr_elem + inner_idx + if to_check % 2 == 0: + if curr_max is None or curr_elem > curr_max: + curr_max = curr_elem + +print(curr_max) diff --git a/2_intermediate/chapter11/examples/define_function.py b/2_intermediate/chapter11/examples/define_function.py new file mode 100644 index 00000000..552421cc --- /dev/null +++ b/2_intermediate/chapter11/examples/define_function.py @@ -0,0 +1,8 @@ +# This is how you define a new function +# "scoop_ice_cream" is the function name +# and "flavor" is a parameter + + +def scoop_ice_cream(flavor): + # write function code here + pass diff --git a/2_intermediate/chapter11/examples/parameters.py b/2_intermediate/chapter11/examples/parameters.py new file mode 100644 index 00000000..90539b69 --- /dev/null +++ b/2_intermediate/chapter11/examples/parameters.py @@ -0,0 +1,43 @@ +# when using regular parameters, remember that order matters +def scoop_ice_cream(param1, param2, param3): + pass + + +scoop_ice_cream("chocolate", "vanilla", "sprinkles") + + +# keyword arguments can be used to input parameter out of order +def func(p1, p2, p3): + print(p1) # prints 2 + print(p2) # prints 3 + print(p3) # prints 1 + + +func(p3=1, p1=2, p2=3) + + +# keyword arguments can also be used to make parameters optional +def car(speed=100): # if no speed is given, 100 is defaulted + print("Car speed:", speed) + + +car(speed=150) # prints "Car speed: 150" +car() # prints "Car speed: 100" + + +# *args can take in an unknown number of regular parameters +def function_name(param1, *args): + print(param1) # prints "p1" + print(args) # prints (1, 2, 3, 4) + + +function_name("p1", 1, 2, 3, 4) + + +# **kwargs can take in an unknown number of keyword parameters +def function_name(param1, **kwargs): + print(param1) # prints "p1" + print(kwargs) # prints {"a":1, "b":2, "c":3} + + +function_name("p1", a=1, b=2, c=3) diff --git a/2_intermediate/chapter11/examples/return.py b/2_intermediate/chapter11/examples/return.py new file mode 100644 index 00000000..2f50f2b1 --- /dev/null +++ b/2_intermediate/chapter11/examples/return.py @@ -0,0 +1,14 @@ +# The return statement "hands back" a value +# to where the function itself was called + + +def average(numbers): + # returns the average of a given list + return sum(numbers) / len(numbers) + + +numbers = [1, 2, 3] + +# assigns average of "numbers" to "avg" and prints it +avg = average(numbers) +print(avg) diff --git a/2_intermediate/chapter11/practice/case.py b/2_intermediate/chapter11/practice/case.py new file mode 100644 index 00000000..e5f9622d --- /dev/null +++ b/2_intermediate/chapter11/practice/case.py @@ -0,0 +1,24 @@ +""" +Case + +Display the string "Apple" in the following formats: +1) normally +2) all uppercase +3) all lowercase + +Display the string "mRoWiE" in the same 3 formats. + +Ask the user to input a sentence, and display this +input in the same 3 formats. + +Do this in AT MOST 8 lines of code. +By the end of the program, 9 lines should have been +displayed (3 formats for each of the 3 strings). + +Example of the 3 formats for one string: +Apple +APPLE +apple +""" + +# Insert your code here. diff --git a/2_intermediate/chapter11/practice/cashier_job.py b/2_intermediate/chapter11/practice/cashier_job.py new file mode 100644 index 00000000..c1e5dfa4 --- /dev/null +++ b/2_intermediate/chapter11/practice/cashier_job.py @@ -0,0 +1,12 @@ +# Cashier Job +# Write a function called calculate_total +# that will take the number of pennies, nickels, dimes, +# quarters, and discount rate (i.e. 15 for 15% discount). +# Return the total amount of money after discount. +# +# Print what is returned by the function after it is run with 97 pennies, +# 13 nickels, 18 dimes, 54 quarters, and 20% discount. +# Print what is returned by the function after it is run with 32 pennies, +# 19 nickels, 22 dimes, 71 quarters, and 51% discount. + +# write code here diff --git a/2_intermediate/chapter11/practice/count_magical.py b/2_intermediate/chapter11/practice/count_magical.py new file mode 100644 index 00000000..114698b2 --- /dev/null +++ b/2_intermediate/chapter11/practice/count_magical.py @@ -0,0 +1,13 @@ +# Write a function called count_magical +# that returns the number of even numbers +# in a given list. In the function, +# if the number of evens is greater than +# half of the length of the list, print "Magical" +# Else, print "Not Magical" +# +# Write a function called main which tests +# the count_magical function on at least +# 3 different lists of integers. Use the main +# function to test count_magical by calling main(). + +# write code here diff --git a/2_intermediate/chapter11/practice/number_mystery_1.py b/2_intermediate/chapter11/practice/number_mystery_1.py new file mode 100644 index 00000000..5b01f798 --- /dev/null +++ b/2_intermediate/chapter11/practice/number_mystery_1.py @@ -0,0 +1,12 @@ +# Number Mystery 1 +# Write a function called num_mystery that takes in 3 integers. +# The function should calculate the sum of the 3 integers and +# the difference between the largest integer and the smallest integer. +# The function should return the product of these two integers you calculated. +# +# Hint: You may find it useful to use the max() and min() functions. +# +# Use the num_mystery function on 1, 2, 3 and print the result. +# Use the num_mystery function on 5, 13, 7 and print the result. + +# write code here diff --git a/2_intermediate/chapter11/practice/nutrition_facts.py b/2_intermediate/chapter11/practice/nutrition_facts.py new file mode 100644 index 00000000..cfb4c4e8 --- /dev/null +++ b/2_intermediate/chapter11/practice/nutrition_facts.py @@ -0,0 +1,75 @@ +""" +Write a function that provides the nutrition facts of an item +within the provided dictionary 'nutrition_facts'. It should +provide the calories by default. It should accept the other +keys within the item's dictionary as keyword arguments. Use **. +If that keyword argument is True, then print out the value +stored by the key in addition to the default string that +says the number of calories. If the user entered in an +invalid specific, it should tell the user about this. If the +user entered in an invalid food, it should ignore the user +completely. + +---Example 1--- +parameters: "lays potato chips", allergens=True + +output: +"Lays potato chips have/has 220 calories" +"allergens" : ["processed on equipment that also processes peanuts", +"contains milk ingredients"] + +---Example 2--- +parameters: "lays potato chips" + +output: +"Lays potato chips have/has 220 calories" + +---Example 3--- +parameters: "lays potato chips", main_ingredients= True + +output: +"Lays potato chips have/has 220 calories" +"main_ingredients" : ["potato", "salt", "canola oil"] +""" + +nutrition_facts = { + "lays potato chips": { + "item": "Lays potato chips", + "calories": 220, + "all_ingredients": [ + "potato", + "salt", + "canola oil", + "msg", + "yeast extract", + "onion extract", + "milk protein concentrate", + "sour cream", + "xantham gum", + "maltodextrin", + "sunflower oil", + ], + "main_ingredients": ["potato", "salt", "canola oil"], + "description": "Sour Cream and Onion Flavor", + "allergens": [ + "processed on equipment that also processes peanuts", + "contains milk ingredients", + ], + }, + "nutella": { + "item": "Nutella", + "calories": 200, + "all_ingredients": [ + "sugar", + "palm oil", + "hazelnuts", + "skim milk", + "cocoa", + "lecithin", + "vanillin (artificial flavor)", + ], + "main_ingredients": ["sugar", "palm oil", "hazelnuts"], + "description": "Hazelnut spread with cocoa", + "allergens": ["Contains Tree Nuts", "Contains milk", "Contains soy"], + }, +} diff --git a/2_intermediate/chapter11/practice/product.py b/2_intermediate/chapter11/practice/product.py new file mode 100644 index 00000000..8e8ee4d7 --- /dev/null +++ b/2_intermediate/chapter11/practice/product.py @@ -0,0 +1,16 @@ +""" +Product + +Write a function that takes a list +of numbers as input and returns +the product of all the numbers in +the list. + +Use it to print the products of the +following sets of numbers: +-1, 5, 3, 2, 8 +2.5, 3, 0 +4, 3, 7, 10 +""" + +# Insert your code here. diff --git a/2_intermediate/chapter11/practice/rect.py b/2_intermediate/chapter11/practice/rect.py new file mode 100644 index 00000000..78461ada --- /dev/null +++ b/2_intermediate/chapter11/practice/rect.py @@ -0,0 +1,30 @@ +""" +Rect + +Write a function that takes in 2 integer +parameters: length, and width. + +The function should print out a rectangle of +asterisks (*) with that length and width. + +Example, if the length is 5 and the width is 3, +the function should print: +***** +***** +***** + +Useful information: +1) print("a", end="") + removes the newline from the end of the print statement. +2) print("a" * 5) displays "aaaaa". + +Use the function to display rectangles with +the following dimensions (with a linebreak +between each one): +2x6 +7x4 +3x5 + +""" + +# Insert your code here. diff --git a/2_intermediate/chapter11/practice/remove_duplicates.py b/2_intermediate/chapter11/practice/remove_duplicates.py new file mode 100644 index 00000000..54a7f5a3 --- /dev/null +++ b/2_intermediate/chapter11/practice/remove_duplicates.py @@ -0,0 +1,15 @@ +# Write a function called remove_duplicates +# The sole parameter of the function should be a list +# The function should look through a list, +# Find all duplicate elements, and remove them +# Sort the resulting list +# YOU MAY NOT USE THE set() function IN PYTHON. +# Hint: To sort a list, use sorted(list) +# Another hint: Use dict.removekeys(list) +# To take the elements from a list, +# and convert them to keys in a dictionary + +# Example: array = [1,1,2,5,4,6,12,3,4,6] +# Result should print [1,2,3,4,5,6,12] + +# Write code here diff --git a/2_intermediate/chapter11/practice/shopping.py b/2_intermediate/chapter11/practice/shopping.py new file mode 100644 index 00000000..9f3635e4 --- /dev/null +++ b/2_intermediate/chapter11/practice/shopping.py @@ -0,0 +1,22 @@ +""" +Code a function named shopping that will print the number +of items that a customer would like to buy. It will take in +an unknown number of parameters, each representing +one item. After that, the function will ask the customer, +"Are you sure you would like to buy" and stating the number +of items the customer wants to purchase.Your function does +not need to respond to a yes/no answer from the user; +it just needs to print the output (the question). + + +===Example 1=== +# Parameters: "soap", "brush", "comb" +# Output: "Are you sure you would like to buy 3 items?" + +===Example 2=== +# Parameters: "lotion", "shoes", "pencil", "crayon" +# Output: "Are you sure you would like to buy 4 items?" +""" + + +# Insert your code here diff --git a/2_intermediate/chapter11/solutions/case.py b/2_intermediate/chapter11/solutions/case.py new file mode 100644 index 00000000..0fe9c1f5 --- /dev/null +++ b/2_intermediate/chapter11/solutions/case.py @@ -0,0 +1,34 @@ +""" +Case + +Display the string "Apple" in the following formats: +1) normally +2) all uppercase +3) all lowercase + +Display the string "mRoWiE" in the same 3 formats. + +Ask the user to input a sentence, and display this +input in the same 3 formats. + +Do this in AT MOST 8 lines of code. +By the end of the program, 9 lines should have been +displayed (3 formats for each of the 3 strings). + +Example of the 3 formats for one string: +Apple +APPLE +apple +""" + + +# Define a function that prints the 3 formats. +def display(str): + print(str) + print(str.upper()) + print(str.lower()) + + +display("Apple") +display("mRoWiE") +display(input("Enter a sentence: ")) diff --git a/2_intermediate/chapter11/solutions/cashier_job.py b/2_intermediate/chapter11/solutions/cashier_job.py new file mode 100644 index 00000000..24cb95ab --- /dev/null +++ b/2_intermediate/chapter11/solutions/cashier_job.py @@ -0,0 +1,25 @@ +# Cashier Job +# Write a function called calculate_total +# that will take the number of pennies, nickels, dimes, +# quarters, and discount rate (i.e. 15 for 15% discount). +# Return the total amount of money after discount. +# +# Print what is returned by the function after it is run with 97 pennies, +# 13 nickels, 18 dimes, 54 quarters, and 20% discount. +# Print what is returned by the function after it is run with 32 pennies, +# 19 nickels, 22 dimes, 71 quarters, and 51% discount. + + +def calculate_total(penny, nickel, dime, quarter, discount): + before_discount = ( + 0.01 * penny + 0.05 * nickel + 0.1 * dime + 0.25 * quarter + ) + discount_multiplier = 1 - discount * 0.01 + + # Round to 2 decimals since it is money + return round(before_discount * discount_multiplier, 2) + + +print(calculate_total(97, 13, 18, 54, 20)) + +print(calculate_total(32, 19, 22, 71, 51)) diff --git a/2_intermediate/chapter11/solutions/count_magical.py b/2_intermediate/chapter11/solutions/count_magical.py new file mode 100644 index 00000000..b9989882 --- /dev/null +++ b/2_intermediate/chapter11/solutions/count_magical.py @@ -0,0 +1,38 @@ +# Write a function called count_magical +# that returns the number of even numbers +# in a given list. In the function, +# if the number of evens is greater than +# half of the length of the list, print "Magical" +# Else, print "Not Magical" +# +# Write a function called main which tests +# the count_magical function on at least +# 3 different lists of integers. Use the main +# function to test count_magical by calling main(). + + +def count_magical(my_list): + number_of_evens = 0 + for n in my_list: + if n % 2 == 0: + number_of_evens += 1 + + if number_of_evens > len(my_list) / 2: + print("Magical") + else: + print("Not Magical") + + return number_of_evens + + +def main(): + list_1 = [1, 2, 3, 4, 5, 6] # not magical, 3 evens + list_2 = [0, 35, 1, 35, 2, 4] # not magical, 3 evens + list_3 = [10, 20, 12, 3, -9] # magical, 3 evens + + print("Number of evens in list 1:", count_magical(list_1)) + print("Number of evens in list 2:", count_magical(list_2)) + print("Number of evens in list 3:", count_magical(list_3)) + + +main() diff --git a/2_intermediate/chapter11/solutions/number_mystery_1.py b/2_intermediate/chapter11/solutions/number_mystery_1.py new file mode 100644 index 00000000..5ec847dc --- /dev/null +++ b/2_intermediate/chapter11/solutions/number_mystery_1.py @@ -0,0 +1,27 @@ +# Number Mystery 1 +# Write a function called num_mystery that takes in 3 integers. +# The function should calculate the sum of the 3 integers and +# the difference between the largest integer and the smallest integer. +# The function should return the product of these two integers you calculated. +# +# Hint: You may find it useful to use the max() and min() functions. +# +# Use the num_mystery function on 1, 2, 3 and print the result. +# Use the num_mystery function on 5, 13, 7 and print the result. + + +def num_mystery(first_int, second_int, third_int): + # calculate the sum of the 3 numbers + sum_of_three = first_int + second_int + third_int + + # calculate the difference between the max and min + largest = max(first_int, second_int, third_int) + smallest = min(first_int, second_int, third_int) + difference = largest - smallest + + # return the product + return sum_of_three * difference + + +print(num_mystery(1, 2, 3)) # prints 12 +print(num_mystery(5, 13, 7)) # prints 200 diff --git a/2_intermediate/chapter11/solutions/nutrition_facts.py b/2_intermediate/chapter11/solutions/nutrition_facts.py new file mode 100644 index 00000000..b8b52605 --- /dev/null +++ b/2_intermediate/chapter11/solutions/nutrition_facts.py @@ -0,0 +1,97 @@ +""" +Write a function that provides the nutrition facts of an item +within the provided dictionary 'nutrition_facts'. It should +provide the calories by default. It should accept the other +keys within the item's dictionary as keyword arguments. Use **. +If that keyword argument is True, then print out the value +stored by the key in addition to the default string that +says the number of calories. If the user entered in an +invalid specific, it should tell the user about this. If the +user entered in an invalid food, it should ignore the user +completely. + +---Example 1--- +parameters: "lays potato chips", allergens=True + +output: +"Lays potato chips have/has 220 calories" +"allergens": ["processed on equipment that also processes peanuts", +"contains milk ingredients"] + +---Example 2--- +parameters: "lays potato chips" + +output: +"Lays potato chips have/has 220 calories" + +---Example 3--- +parameters: "lays potato chips", main_ingredients= True + +output: +"Lays potato chips have/has 220 calories" +"main_ingredients" : ["potato", "salt", "canola oil"] +""" + +nutrition_facts = { + "lays potato chips": { + "item": "Lays potato chips", + "calories": 220, + "all_ingredients": [ + "potato", + "salt", + "canola oil", + "msg", + "yeast extract", + "onion extract", + "milk protein concentrate", + "sour cream", + "xantham gum", + "maltodextrin", + "sunflower oil", + ], + "main_ingredients": ["potato", "salt", "canola oil"], + "description": "Sour Cream and Onion Flavor", + "allergens": [ + "processed on equipment that also processes peanuts", + "contains milk ingredients", + ], + }, + "nutella": { + "item": "Nutella", + "calories": 200, + "all_ingredients": [ + "sugar", + "palm oil", + "hazelnuts", + "skim milk", + "cocoa", + "lecithin", + "vanillin (artificial flavor)", + ], + "main_ingredients": ["sugar", "palm oil", "hazelnuts"], + "description": "Hazelnut spread with cocoa", + "allergens": ["Contains Tree Nuts", "Contains milk", "Contains soy"], + }, +} + + +def food_info(item, **specifics): + item = item.lower() + if item in nutrition_facts: + print( + nutrition_facts[item]["item"], + "have/has", + nutrition_facts[item]["calories"], + "calories", + ) + for specific in specifics: + if specific in nutrition_facts[item] and specifics[specific] is True: + print(f"{specific} : {nutrition_facts[item][specific]}") + else: + print( + f"{specific} isn't a valid specific about the nutrition facts" + ) + + +food_info("lays potato chips", allergens=True) +food_info("nutella", allergens=True) diff --git a/2_intermediate/chapter11/solutions/product.py b/2_intermediate/chapter11/solutions/product.py new file mode 100644 index 00000000..3318d52e --- /dev/null +++ b/2_intermediate/chapter11/solutions/product.py @@ -0,0 +1,29 @@ +""" +Product + +Write a function that takes a list +of numbers as input and returns +the product of all the numbers in +the list. + +Use it to print the products of the +following sets of numbers: +-1, 5, 3, 2, 8 +2.5, 3, 0 +4, 3, 7, 10 +""" + + +# Define a product() function with a list parameter. +def product(list): + product = 1 + for i in list: + product *= i + return product + + +# Use the function to display products, where +# each set of numbers is given as a list. +print(product([-1, 5, 3, 2, 8])) +print(product([2.5, 3, 0])) +print(product([4, 3, 7, 10])) diff --git a/2_intermediate/chapter11/solutions/rect.py b/2_intermediate/chapter11/solutions/rect.py new file mode 100644 index 00000000..41f48d5e --- /dev/null +++ b/2_intermediate/chapter11/solutions/rect.py @@ -0,0 +1,41 @@ +""" +Rect + +Write a function that takes in 2 integer +parameters: length, and width. + +The function should print out a rectangle of +asterisks (*) with that length and width. + +Example, if the length is 5 and the width is 3, +the function should print: +***** +***** +***** + +Useful information: +1) print("a", end="") + removes the newline from the end of the print statement. +2) print("a" * 5) displays "aaaaa". + +Use the function to display rectangles with +the following dimensions (with a linebreak +between each one): +2x6 +7x4 +3x5 + +""" + + +# Define a function with length and width parameters. +def draw_rect(length, width): + for row in range(width): + print("*" * length) + print() + + +# Use the function to draw rectangles of various sizes. +draw_rect(2, 6) +draw_rect(7, 4) +draw_rect(3, 5) diff --git a/2_intermediate/chapter11/solutions/remove_duplicates.py b/2_intermediate/chapter11/solutions/remove_duplicates.py new file mode 100644 index 00000000..3e382b27 --- /dev/null +++ b/2_intermediate/chapter11/solutions/remove_duplicates.py @@ -0,0 +1,32 @@ +# Write a function called remove_duplicates +# The sole parameter of the function should be a list +# The function should look through a list, +# Find all duplicate elements, and remove them +# Sort the resulting list +# YOU MAY NOT USE THE set() function IN PYTHON. +# Hint: To sort a list, use sorted(list) +# Another hint: Use dict.fromkeys(list) +# To take the elements from a list, +# and convert them to keys in a dictionary + +# Example: array = [1,1,2,5,4,6,12,3,4,6] +# Result should print [1,2,3,4,5,6,12] + +# Write code here + +list1 = [1, 1, 2, 5, 4, 6, 12, 3, 4, 6] # Define your list + + +# Define your Function +def remove_duplicates(array): + my_list = list(dict.fromkeys(array)) + # Converts the list into a dictionary. + # Fromkeys(array) turns each item into a key + # There cannot be multiple keys, + # So all the duplicate keys are removed + # Convert the keys back into a list + return sorted(my_list) + # Returns the sorted list of keys that are not duplicate. + + +print(remove_duplicates(list1)) # Call the function diff --git a/2_intermediate/chapter11/solutions/shopping.py b/2_intermediate/chapter11/solutions/shopping.py new file mode 100644 index 00000000..ca6526c5 --- /dev/null +++ b/2_intermediate/chapter11/solutions/shopping.py @@ -0,0 +1,27 @@ +""" +Code a function named shopping that will print the number +of items that a customer would like to buy. It will take in +an unknown number of parameters, each representing +one item. After that, the function will ask the customer, +"Are you sure you would like to buy" and stating the number +of items the customer wants to purchase. Your function does not +need to respond to a yes/no answer from the user; it just +needs to print the output (the question). + + +===Example 1=== +# Parameters: "soap", "brush", "comb" +# Output: "Are you sure you would like to buy 3 items?" + +===Example 2=== +# Parameters: "lotion", "shoes", "pencil", "crayon" +# Output: "Are you sure you would like to buy 4 items?" +""" + + +def shopping(*args): + item_number = len(args) + print("Are you sure you would like to buy", item_number, "items?") + + +shopping("soap", "brush", "comb") diff --git a/2_intermediate/chapter12/examples/class.py b/2_intermediate/chapter12/examples/class.py new file mode 100644 index 00000000..06cbdfcf --- /dev/null +++ b/2_intermediate/chapter12/examples/class.py @@ -0,0 +1,18 @@ +class dot_example: # use 'class' keyword followed by your class' name + # classes can store functions and data; we call functions "methods" + # we call data "attributes" + + # below are dot_example's attributes + fun = True + difficult = False + + +our_example = dot_example() # instantiate the class; make sure to use () + +# would print True +print(our_example.fun) # our_example is the object, fun is the attribute + +# would print False +print( + our_example.difficult +) # our_example is the object, difficult is the attribute diff --git a/2_intermediate/chapter12/examples/inheritance.py b/2_intermediate/chapter12/examples/inheritance.py new file mode 100644 index 00000000..8e1de605 --- /dev/null +++ b/2_intermediate/chapter12/examples/inheritance.py @@ -0,0 +1,22 @@ +# Inheritance in coding is when one "child" class receives +# all of the methods and attributes of another "parent" class + + +class Test: + def __init__(self): + self.x = 0 + + +# class Derived_Test inherits from class Test +class Derived_Test(Test): + def __init__(self): + Test.__init__(self) # do Test's __init__ method + # Test's __init__ gives Derived_Test the attribute 'x' + self.y = 1 + + +b = Derived_Test() + +# Derived_Test now has an attribute "x", even though +# it originally didn't +print(b.x, b.y) diff --git a/2_intermediate/chapter12/examples/init_function.py b/2_intermediate/chapter12/examples/init_function.py new file mode 100644 index 00000000..d98dc6bc --- /dev/null +++ b/2_intermediate/chapter12/examples/init_function.py @@ -0,0 +1,22 @@ +# The __init__ function is automatically called when +# a new object is created. It is good to use this method +# when there are certain values that are required beforehand +# for the object to work properly. + + +class Tesla: + def __init__(self, maxSpeed=120, color="red"): + # the init function always needs the self keyword + # if no maxSpeed is entered, maxSpeed will default to 120 + # if no color is entered, color will default to "red" + + # set the class' attribute maxSpeed to the provided maxSpeed + self.maxSpeed = maxSpeed + + # set the class' attribute color to the provided color + self.color = color + + +p1 = Tesla(140, "blue") +print(p1.maxSpeed) # will print 140 +print(p1.color) # will print "blue" diff --git a/2_intermediate/chapter12/examples/methods.py b/2_intermediate/chapter12/examples/methods.py new file mode 100644 index 00000000..5c570652 --- /dev/null +++ b/2_intermediate/chapter12/examples/methods.py @@ -0,0 +1,12 @@ +class Tesla: + def __init__(self, maxSpeed=120, color="red"): + self.maxSpeed = maxSpeed + self.color = color + + # a method: acts just like a function, but needs the self keyword + def drive(self): + print("The car is now driving") + + +p1 = Tesla(140, "blue") +p1.drive() # will execute the drive method from class Tesla diff --git a/2_intermediate/chapter12/examples/self_word.py b/2_intermediate/chapter12/examples/self_word.py new file mode 100644 index 00000000..f09e7d70 --- /dev/null +++ b/2_intermediate/chapter12/examples/self_word.py @@ -0,0 +1,28 @@ +# The self keyword is used when you want a method or +# attribute to be for a specific object. This means that, +# down below, each Tesla object can have different maxSpeed +# and colors from each other. + + +class Tesla: + def __init__(self, maxSpeed=120, color="red"): + self.maxSpeed = maxSpeed + self.color = color + + def change(self, c): + self.color = c + + +p1 = Tesla(140, "blue") +p2 = Tesla(100, "blue") + + +# Notice how, when we use the self keyword, each object can +# have different attributes even though they are from the +# same class. + +p1.change("green") +print(p1.color) # prints "green" + +p2.change("yellow") +print(p2.color) # prints "yellow" diff --git a/2_intermediate/chapter12/practice/buildings.py b/2_intermediate/chapter12/practice/buildings.py new file mode 100644 index 00000000..92169829 --- /dev/null +++ b/2_intermediate/chapter12/practice/buildings.py @@ -0,0 +1,21 @@ +# Create a class called 'building' +# It should have a build method that prints: +# "under construction..." +# "built" +# It should also have an __init__ method that runs the build method +# (basically, the __init__ method should call the build method) +# The __init__ method should also set an attribute 'built' to True + +# Create a class 'library' +# It should be a child class from 'building'. +# Its init method should run building's init method. It should also +# create an empty list called 'books' +# 'library' should also have a 'restock' method +# that asks the user for a book to buy and prints "bought %s" where +# %s is the bookname. The 'restock' method should also append the +# book's name to the library's list 'books' +# Lastly, the library class should have a method 'catalog' that prints +# all the books in the library on separate lines + +# Finally, instantiate the library class +# (you should see "under construction..." and "built" if you did it right diff --git a/2_intermediate/chapter12/practice/food_class.py b/2_intermediate/chapter12/practice/food_class.py new file mode 100644 index 00000000..868eeef3 --- /dev/null +++ b/2_intermediate/chapter12/practice/food_class.py @@ -0,0 +1,34 @@ +""" +Food + +Create a Food class with 4 instance +attributes: name. calories, grams of +protein, and grams of fat. + +It should have 2 methods: an eat method +that prints "You are eating " and the name +of the food, and a burn method that prints +"You burned [x] calories." where [x] is +the number of calories in the food. + +Create a JunkFood subclass and a Meal +subclass. Both subclasses should carry +over the attributes and methods of the +Food class. +The JunkFood subclass should have an +additional attribute for the grams of +sugar contained in the food, and the Meal +subclass should have an additional attribute +for the mg of sodium it contains. + +Create a list called snacks and fill it with at +least 3 junk foods, and create a list called +meals and fill it with at least 3 meals. +Then, use Python to show that you ate all the +foods in both lists, and burned off one meal +(pick this meal randomly). +Display the total number of calories, +grams of protein, grams of fat, grams of +sugar, and mg of sodium that you ate (the total +for all the foods in both lists). +""" diff --git a/2_intermediate/chapter12/practice/student_class.py b/2_intermediate/chapter12/practice/student_class.py new file mode 100644 index 00000000..30033517 --- /dev/null +++ b/2_intermediate/chapter12/practice/student_class.py @@ -0,0 +1,5 @@ +# Create a class called Student with instance attributes: name and age. +# The user can input the name and age. Add 2 methods to the class: +# 1. A raise_hand method which prints out the student's name followed +# by "is now raising their hand." +# 2. A grow_older method that makes the student older by 1 year. diff --git a/2_intermediate/chapter12/practice/teacher_class.py b/2_intermediate/chapter12/practice/teacher_class.py new file mode 100644 index 00000000..0c7e422c --- /dev/null +++ b/2_intermediate/chapter12/practice/teacher_class.py @@ -0,0 +1,20 @@ +# Create a class called Teacher. Add 3 instance variables to this +# class: name, age, and students (a list of Student objects). +# Add 2 Methods to the class: A display_students method that +# prints out the names of all the students, each on their own line, and +# a graduate_students method that increments the age of all of the +# teacher's Students by 1. Then it should print out all their ages. + +# Student class implemented below. Teacher class uses it. + + +class Student: + def __init__(self, name, age): + self.name = name + self.age = age + + def raise_hand(self): + print(self.name + " is now raising their hand.") + + def grow_older(self): + self.age += 1 diff --git a/2_intermediate/chapter12/solutions/buildings.py b/2_intermediate/chapter12/solutions/buildings.py new file mode 100644 index 00000000..3b345cce --- /dev/null +++ b/2_intermediate/chapter12/solutions/buildings.py @@ -0,0 +1,50 @@ +# Create a class called 'building' +# It should have a build method that prints: +# "under construction..." +# "built" +# It should also have an __init__ method that runs the build method +# (basically, the __init__ method should call the build method) +# The __init__ method should also set an attribute 'built' to True + +# Create a class 'library' +# It should be a child class from 'building'. +# Its init method should run building's init method. It should also +# create an empty list called 'books' +# 'library' should also have a 'restock' method +# that asks the user for a book to buy and prints "bought %s" where +# %s is the bookname. The 'restock' method should also append the +# book's name to the library's list 'books' +# Lastly, the library class should have a method 'catalog' that prints +# all the books in the library on separate lines + +# Finally, instantiate the library class +# (you should see "under construction..." and "built" if you did it right + + +class building: + def __init__(self): + self.build() + self.built = True + + def build(self): + print("under construction...") + print("built") + + +class library(building): + def __init__(self): + super().__init__() + self.books = [] + + def restock(self): + book = input("What book should we buy? ") + print("Bought %s" % book) + self.books.append(book) + + def catalog(self): + print("Here are our books:") + for book in self.books: + print(book) + + +oak_library = library() diff --git a/2_intermediate/chapter12/solutions/food_class.py b/2_intermediate/chapter12/solutions/food_class.py new file mode 100644 index 00000000..5500c123 --- /dev/null +++ b/2_intermediate/chapter12/solutions/food_class.py @@ -0,0 +1,101 @@ +""" +Food + +Create a Food class with 4 instance +attributes: name. calories, grams of +protein, and grams of fat. + +It should have 2 methods: an eat method +that prints "You are eating " and the name +of the food, and a burn method that prints +"You burned [x] calories." where [x] is +the number of calories in the food. + +Create a JunkFood subclass and a Meal +subclass. Both subclasses should carry +over the attributes and methods of the +Food class. +The JunkFood subclass should have an +additional attribute for the grams of +sugar contained in the food, and the Meal +subclass should have an additional attribute +for the mg of sodium it contains. + +Create a list called snacks and fill it with at +least 3 junk foods, and create a list called +meals and fill it with at least 3 meals. +Then, use Python to show that you ate all the +foods in both lists, and burned off one meal +(pick this meal randomly). +Display the total number of calories, +grams of protein, grams of fat, grams of +sugar, and mg of sodium that you ate (the total +for all the foods in both lists). +""" +import random + + +class Food: + def __init__(self, name, cals, protein, fat): + self.name = name + self.cals = cals + self.protein = protein + self.fat = fat + + def eat(self): + print("You are eating " + self.name + ".") + + def burn(self): + print("You burned %d calories." % self.cals) + + +class JunkFood(Food): + def __init__(self, name, cals, protein, fat, sugar): + super().__init__(name, cals, protein, fat) + self.sugar = sugar + + +class Meal(Food): + def __init__(self, name, cals, protein, fat, sodium): + super().__init__(name, cals, protein, fat) + self.sodium = sodium + + +snacks = [ + JunkFood("Oreo", 55, 0.5, 2.2, 4.1), + JunkFood("Brownie", 70, 2, 3, 2), + JunkFood("Chips", 160, 2, 10, 0), +] + +meals = [ + Meal("Rice and beans", 400, 10, 5, 15), + Meal("Burrito", 350, 8, 9, 100), + Meal("Pizza", 500, 20, 15, 150), +] + +cals, protein, fat, sugar, sodium = 0, 0, 0, 0, 0 + +for snack in snacks: + snack.eat() + cals += snack.cals + protein += snack.protein + fat += snack.fat + sugar += snack.sugar + +for meal in meals: + meal.eat() + cals += meal.cals + protein += meal.protein + fat += meal.fat + sodium += meal.sodium + +# Choose a random meal to burn off. +meals[random.randrange(len(meals))].burn() + +# Display totals +print("Totals eaten:") +print("Calories:", cals) +print("Protein (g):", protein) +print("Fat (g):", fat) +print("Sugar (g):", sugar) +print("Sodium (mg):", sodium) diff --git a/2_intermediate/chapter12/solutions/student_class.py b/2_intermediate/chapter12/solutions/student_class.py new file mode 100644 index 00000000..fee7f937 --- /dev/null +++ b/2_intermediate/chapter12/solutions/student_class.py @@ -0,0 +1,17 @@ +# Create a class called Student with instance attributes: name and age. +# The user can input the name and age. Add 2 methods to the class: +# 1. A raise_hand method which prints out the student's name followed +# by "is now raising their hand." +# 2. A grow_older method that makes the student older by 1 year. + + +class Student: + def __init__(self, name, age): + self.name = name + self.age = age + + def raise_hand(self): + print(self.name + " is now raising their hand.") + + def grow_older(self): + self.age += 1 diff --git a/2_intermediate/chapter12/solutions/teacher_class.py b/2_intermediate/chapter12/solutions/teacher_class.py new file mode 100644 index 00000000..b774f7e5 --- /dev/null +++ b/2_intermediate/chapter12/solutions/teacher_class.py @@ -0,0 +1,36 @@ +# Create a class called Teacher. Add 3 instance variables to this +# class: name, age, and students (a list of Student objects). +# Add 2 Methods to the class: A display_students method that +# prints out the names of all the students, each on their own line, and +# a graduate_students method that increments the age of all of the +# teacher's Students by 1. Then it should print out all their ages. + +# Student class implemented below. Teacher class uses it. + + +class Teacher: + def __init__(self, name, age, students): + self.name = name + self.age = age + self.students = students + + def display_students(self): + for student in self.students: + print(student.name) + + def graduate_students(self): + for student in self.students: + student.grow_older() + print(student.age) + + +class Student: + def __init__(self, name, age): + self.name = name + self.age = age + + def raise_hand(self): + print(self.name + " is now raising their hand.") + + def grow_older(self): + self.age += 1 diff --git a/2_intermediate/chapter13/examples/bankAccount.py b/2_intermediate/chapter13/examples/bankAccount.py new file mode 100644 index 00000000..5c6248ca --- /dev/null +++ b/2_intermediate/chapter13/examples/bankAccount.py @@ -0,0 +1,45 @@ +class bankAccount: + def __init__(self, owner: str, balance: float): + self.owner = owner + self.balance = balance + + def __getitem__(self, item: str): + if item == "owner": + return self.owner + elif item == "balance": + return self.balance + else: + # if the attribute isn't a valid attribute, you should + # raise an AttributeError + raise AttributeError + + def __setitem__(self, item: str, value): + if item == "owner": + self.owner = value + elif item == "balance": + self.balance = value + else: + # if the attribute isn't a valid attribute, you should + # raise an AttributeError + raise AttributeError + + def __bool__(self): + """ + If we wanted the bank account to return True if the person + is not bankrupt and False if they are bankrupt, we could do: + """ + return self.balance > 0 + + +account = bankAccount("John", 100) +print(account["owner"]) +print(account["balance"]) +account["balance"] = 200 +print(account["balance"]) +account["owner"] = "John Jr." +print(account["owner"]) + + +print(bool(account)) +if account: + print("not bankrupt") diff --git a/2_intermediate/chapter13/examples/coordinateGrid.py b/2_intermediate/chapter13/examples/coordinateGrid.py new file mode 100644 index 00000000..6f0d00b4 --- /dev/null +++ b/2_intermediate/chapter13/examples/coordinateGrid.py @@ -0,0 +1,52 @@ +class coordinateGrid: + def __init__( + self, + x_start: int = 0, + x_end: int = 10, + y_start: int = 0, + y_end: int = 10, + ): + """ + Creates a list of coordinates similar to a coordinate grid. + Each item in self.coordinates is a list representing one row in a + coordinate grid. + each item within that row is a point (tuple) of x, y + ex: coordinateGrid(0, 1, -1, 1)'s coordinates would be + [ + [(0, 1), (1, 1)], + [(0, 0), (1, 0)], + [(0, -1), (1, -1)] + ] + Arguments: + x_start, x_end, y_start, and y_end are all inclusive + """ + self.coordinates = [ + [(x, y) for x in range(x_start, x_end + 1)] + for y in range(y_end, y_start - 1, -1) + ] + + def __contains__(self, item: tuple) -> bool: + """ + Checks to see if the provided tuple (or list) + of length 2 (the tuple/list represents a point of x,y) + is in self.coordinates. + """ + return True in [item in row for row in self.coordinates] + + def __len__(self) -> bool: + """ + In this case, we're saying that the length of the coordinateGrid + is its area. Thus, we do height * width + height = len(self.coordinates) and + width = len(self.coordinates[0]) (or any row's length) + """ + return len(self.coordinates) * len(self.coordinates[0]) + + +grid1 = coordinateGrid(-1, 1, -1, 1) +grid2 = coordinateGrid(-10, 10, -10, 10) +point1 = (10, 10) +print(point1 in grid1) +print(point1 in grid2) +print(len(grid1)) +print(len(grid2)) diff --git a/2_intermediate/chapter13/examples/vector.py b/2_intermediate/chapter13/examples/vector.py new file mode 100644 index 00000000..6038aad3 --- /dev/null +++ b/2_intermediate/chapter13/examples/vector.py @@ -0,0 +1,26 @@ +class Vector: + """ + Constructor + + self: a reference to the object we are creating + vals: a list of integers which are the contents of our vector + """ + + def __init__(self, vals): + self.vals = ( + vals # We're using the keyword self to create a field/property + ) + print("Assigned values ", vals, " to vector.") + + """ + String Function + + Converts the object to a string in readable format for programmers + """ + + def __str__(self): + return str(self.vals) # Returns the contents of the vector + + +vec = Vector([2, 3, 2]) +print(str(vec)) # [2, 3, 2] diff --git a/2_intermediate/chapter13/examples/vector2.py b/2_intermediate/chapter13/examples/vector2.py new file mode 100644 index 00000000..224ccd01 --- /dev/null +++ b/2_intermediate/chapter13/examples/vector2.py @@ -0,0 +1,59 @@ +class Vector: + """ + Constructor + + self: a reference to the object we are creating + vals: a list of integers which are the contents of our vector + """ + + def __init__(self, vals): + self.vals = vals + # print("Assigned values ", vals, " to vector.") + + """ + String Function + + Converts the object to a string in readable format for programmers + """ + + def __str__(self): + return str(self.vals) + + """ + Elementwise power: raises each element in our vector to the given power + """ + + def __pow__(self, power): + return Vector([i**power for i in self.vals]) + + """ + Addition: adds each element to corresponding element in other vector + """ + + def __add__(self, vec): + return Vector( + [self.vals[i] + vec.vals[i] for i in range(len(self.vals))] + ) + + """ + Multiplies each element in the vector by a specified constant + """ + + def __mul__(self, constant): + return Vector([self.vals[i] * constant for i in range(len(self.vals))]) + + """ + Elementwise subtraction: does same as addition, just subtraction instead + """ + + def __sub__(self, vec): + return self + (vec * (-1)) + + +vec = Vector([2, 3, 2]) +otherVec = Vector([3, 4, 5]) +print(str(vec)) # [2, 3, 2] +print(vec**2) # [4, 9, 4] +print(vec - otherVec) # [-1, -1, -3] +print(vec + otherVec) # [5, 7, 7] +print(vec * 5) # [10, 15, 10] diff --git a/2_intermediate/chapter13/examples/vector3.py b/2_intermediate/chapter13/examples/vector3.py new file mode 100644 index 00000000..25307216 --- /dev/null +++ b/2_intermediate/chapter13/examples/vector3.py @@ -0,0 +1,68 @@ +class Vector: + """ + Constructor + + self: a reference to the object we are creating + vals: a list of integers which are the contents of our vector + """ + + def __init__(self, vals): + self.vals = vals + # print("Assigned values ", vals, " to vector.") + + """ + String Function + + Converts the object to a string in readable format for programmers + """ + + def __str__(self): + return str(self.vals) + + def __pow__(self, power): + return Vector([i**power for i in self.vals]) + + # Calculates Euclidean norm + def norm(self): + return sum((self**2).vals) ** 0.5 + + # __lt__: implements the less than operator (<) + def __lt__(self, other): + return self.norm() < other.norm() + + # __gt__: implements the greater than operator (>) + def __gt__(self, other): + return self.norm() > other.norm() + + # __le__: implements the less than equal to operator (<=) + def __le__(self, other): + return self.norm() <= other.norm() + + # __ge__: implements the greater than equal to operator (>=) + def __ge__(self, other): + return self.norm() >= other.norm() + + # __eq__: implements the equals operator (==) + def __eq__(self, other): + return self.norm() == other.norm() + + # __ne__:implements the not equals operator (!=) + def __ne__(self, other): + return self.norm() != other.norm() + + +vec = Vector([2, 3, 2]) +vec2 = Vector([3, 4, 5]) +print(vec < vec2) # True +print(vec > vec2) # False + +print(vec <= vec2) # True +print(vec >= vec2) # False +print(vec <= vec) # True +print(vec >= vec) # True + +print(vec == vec2) # False +print(vec == vec) # True + +print(vec != vec2) # True +print(vec != vec) # False diff --git a/2_intermediate/chapter13/practice/car.py b/2_intermediate/chapter13/practice/car.py new file mode 100644 index 00000000..dd972e70 --- /dev/null +++ b/2_intermediate/chapter13/practice/car.py @@ -0,0 +1,31 @@ +""" +A new car is said to devalue 20% in the first year. Assuming that +this trend continues and that mileage divided by 100 is all you +subtract from this adjusted price, make a class "car" that has at +least the attributes "year, original price (aka og price), and +mileage." Also, follow these guidelines. + +--When using str() on a car, it should return the year, original + price, mileage, and adjusted price. +--When adding, it should add the value to its mileage before + adjusting the adjusted price. +--When multiplying, it should multiply the mileage by the value + before adjusting the adjusted price +--(While subtracting or dividing mileage on a car to sell it is + totally unethical,) When subtracting or dividing, it should + subtract the value from its mileage or divide its mileage by + the value before adjusting the adjusted price. +--When checking gt(which means greater than), lt, ge, le, ne, + and eq, it should compare the price with the other value. +--You should be able to compare cars (prices) but not add cars + together + +If you need help with modeling the equation for the adjusted price, +this may help + +self.adjustedprice=self.ogprice * (0.8**(2020-self.year))) +self.adjustedprice=round((self.adjustedprice),2)-self.mileage/100 + +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/filler b/2_intermediate/chapter13/practice/filler new file mode 100644 index 00000000..17725cff --- /dev/null +++ b/2_intermediate/chapter13/practice/filler @@ -0,0 +1 @@ +#This is filler. Remove later diff --git a/2_intermediate/chapter13/practice/lexicographical_vector.py b/2_intermediate/chapter13/practice/lexicographical_vector.py new file mode 100644 index 00000000..43a8f202 --- /dev/null +++ b/2_intermediate/chapter13/practice/lexicographical_vector.py @@ -0,0 +1,12 @@ +""" +Reimplement the __lt__ and __gt__ in the given Vector +class(the one in this section) so that we are comparing +the vector's contents based on lexicographical ordering. +Think of lexicographical ordering as how you arrange words +in a dictionary. For instance, by lexicographical ordering, +'a' < 'ab', 'ab' < 'ad', 'bcd' > 'a'. It works analogously +for numbers, but instead, each character has been substituted +by a number. +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/line.py b/2_intermediate/chapter13/practice/line.py new file mode 100644 index 00000000..6bfca643 --- /dev/null +++ b/2_intermediate/chapter13/practice/line.py @@ -0,0 +1,9 @@ +""" +Write a class called Line which will take the arguments slope +and intercept in its constructor. When we print the class, +the __str__ method should return a string with the line expressed +in the form "y=mx+b" where m and b are the slope and intercept +respectively. +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/matrix.py b/2_intermediate/chapter13/practice/matrix.py new file mode 100644 index 00000000..91ba119a --- /dev/null +++ b/2_intermediate/chapter13/practice/matrix.py @@ -0,0 +1,10 @@ +""" +Build a class called Matrix which will take a list of lists +(containing integers) and store it as a field. Add an assertion +using the keyword assert to ensure that the list of lists is +rectangular (i.e. assert len(list_0) = len(list_i) for i in range(n)) +You should also implement a __str__ method so that we can print +the contents of the matrix using print without having to access its field. +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/matrix_add_subtract.py b/2_intermediate/chapter13/practice/matrix_add_subtract.py new file mode 100644 index 00000000..8aa83fe2 --- /dev/null +++ b/2_intermediate/chapter13/practice/matrix_add_subtract.py @@ -0,0 +1,25 @@ +""" +Write a modified version of the Matrix class(that was defined in +one of the example problems in this section) with an __add__ +operation as well as a __sub__ operation. It should add matrices, +assuming that they will be of the same length. Also, the unmodified +Matrix class code will be given. +""" + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items])==list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things])==int + + def __str__(self): + return str(self.thelist) +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/matrix_frobenius_norm.py b/2_intermediate/chapter13/practice/matrix_frobenius_norm.py new file mode 100644 index 00000000..f7689fd1 --- /dev/null +++ b/2_intermediate/chapter13/practice/matrix_frobenius_norm.py @@ -0,0 +1,26 @@ +""" +Write a modified version of the Matrix class(that was defined in +one of the example problems in this section) so that the __str__ +method instead returns a string containing a single number: the +matrix's Frobenius norm. The formula for the Frobenius norm will +be the square root of the sum of all the elements squared in the +matrix. Also, the unmodified Matrix class code will be given. +""" + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items])==list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things])==int + + def __str__(self): + return str(self.thelist) +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/matrix_less_greater.py b/2_intermediate/chapter13/practice/matrix_less_greater.py new file mode 100644 index 00000000..1d928dae --- /dev/null +++ b/2_intermediate/chapter13/practice/matrix_less_greater.py @@ -0,0 +1,25 @@ +""" +Implement the less than and greater than operators for +the Matrix class(from a previous example problem) so that +we compare them based on their Frobenius norms which we +have implemented in the earlier section as an exercise. +Also, the unmodified Matrix class code will be given. +""" + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items])==list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things])==int + + def __str__(self): + return str(self.thelist) +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/polar_coordinates.py b/2_intermediate/chapter13/practice/polar_coordinates.py new file mode 100644 index 00000000..98e23c30 --- /dev/null +++ b/2_intermediate/chapter13/practice/polar_coordinates.py @@ -0,0 +1,10 @@ +""" +Write a class called PolarCoordinates which will take a +value called radius and angle. When we print this class, +we want the coordinates in Cartesian coordinates, or we want +you to print two values: x and y. (If you don't know the +conversion formula, x = radius * cos(angle), y = radius * sin(angle). +Use Python's built-in math library for the cosine and sine operators) +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/triangle.py b/2_intermediate/chapter13/practice/triangle.py new file mode 100644 index 00000000..61ec4f28 --- /dev/null +++ b/2_intermediate/chapter13/practice/triangle.py @@ -0,0 +1,15 @@ +""" +Write a class called Triangle which will take three tuples +(each tuple contains two integers: the x and y coordinates +of a vertex). Then, define an __add__ operation that acts as +a translation operation. Its input argument will be a tuple +of two integers that will indicate the x and y translations +that will be applied to each coordinate. (basically, add the +tuple to each coordinate of the triangle). Also, define a +vertical and horizontal transformation tool in the form +of __mul__ which will also take a tuple of two integers that +will be multiplied to the x and y coordinates of each vertex +respectively. +""" + +# write your code below diff --git a/2_intermediate/chapter13/practice/vector.py b/2_intermediate/chapter13/practice/vector.py new file mode 100644 index 00000000..c3107c1f --- /dev/null +++ b/2_intermediate/chapter13/practice/vector.py @@ -0,0 +1,10 @@ +""" +Define a Vector class so that the multiply operation is with +another Vector instead. The multiply operation should be the +inner or dot product of the two vectors. That means that each +element in the vector should be multiplied with its +corresponding element in the other vector, and then summed. +A scalar (regular number) should be returned. +""" + +# write your code below diff --git a/2_intermediate/chapter13/solutions/car.py b/2_intermediate/chapter13/solutions/car.py new file mode 100644 index 00000000..5f5c6717 --- /dev/null +++ b/2_intermediate/chapter13/solutions/car.py @@ -0,0 +1,124 @@ +""" +A new car is said to devalue 20% in the first year. Assuming that +this trend continues and that mileage divided by 100 is all you +subtract from this adjusted price, make a class "car" that has at +least the attributes "year, original price (aka og price), and +mileage." Also, follow these guidelines. + +--When using str() on a car, it should return the year, original + price, mileage, and adjusted price. +--When adding, it should add the value to its mileage before + adjusting the adjusted price. +--When multiplying, it should multiply the mileage by the value + before adjusting the adjusted price +--(While subtracting or dividing mileage on a car to sell it is + totally unethical,) When subtracting or dividing, it should + subtract the value from its mileage or divide its mileage by + the value before adjusting the adjusted price. +--When checking gt(which means greater than), lt, ge, le, ne, + and eq, it should compare the price with the other value. +--You should be able to compare cars (prices) but not add cars + together + +If you need help with modeling the equation for the adjusted price, +this may help + +self.adjustedprice=self.ogprice * (0.8**(2020-self.year))) +self.adjustedprice=round((self.adjustedprice),2)-self.mileage/100 + +""" + +# write your code below + + +class car: + def __init__(self, year, brand, ogprice, mileage): + self.year = year + self.brand = brand + self.ogprice = ogprice + self.mileage = mileage + self.adjustedprice = self.adjustprice() + + def adjustprice(self): + self.adjustedprice = float(self.ogprice * (0.8 ** (2020 - self.year))) + self.adjustedprice = ( + round((self.adjustedprice), 2) - self.mileage / 100 + ) + return self.adjustedprice + + def __str__(self): + return "This car is a {} model from {}. It was originally worth ${} and \ + has driven {} miles. It is now worth {}".format( + self.year, + self.brand, + self.ogprice, + self.mileage, + self.adjustedprice, + ) + + def __lt__(self, value): + if type(value) == car: + return self.adjustedprice < value.adjustedprice + elif type(value) != object: + return self.adjustedprice < value + + def __gt__(self, value): + if type(value) == car: + return self.adjustedprice > value.adjustedprice + elif type(value) != object: + return self.adjustedprice > value + + def __eq__(self, value): + if type(value) == car: + return self.adjustedprice == value.adjustedprice + elif type(value) != object: + return self.adjustedprice == value + + def __ne__(self, value): + if type(value) == car: + return self.adjustedprice != value.adjustedprice + elif type(value) != object: + return self.adjustedprice != value + + def __le__(self, value): + if type(value) == car: + return self.adjustedprice <= value.adjustedprice + elif type(value) != object: + return self.adjustedprice <= value + + def __ge__(self, value): + if type(value) == car: + return self.adjustedprice >= value.adjustedprice + elif type(value) != object: + return self.adjustedprice >= value + + def __add__(self, value): + if type(value) == car: + return None + elif type(value) != object: + self.mileage += value + self.adjustedprice = self.adjustprice() + + def __sub__(self, value): + if type(value) == car: + return None + elif type(value) != object: + self.mileage -= value + self.adjustedprice = self.adjustprice() + + def __truediv__(self, value): + if type(value) == car: + return None + elif type(value) != object: + self.mileage = self.mileage / value + self.adjustedprice = self.adjustprice() + + def __mul__(self, value): + if type(value) == car: + return None + elif type(value) != object: + self.mileage = self.mileage * value + self.adjustedprice = self.adjustprice() + + +Maserati = car(2009, "porsche", 30000, 14000) diff --git a/2_intermediate/chapter13/solutions/filler b/2_intermediate/chapter13/solutions/filler new file mode 100644 index 00000000..17725cff --- /dev/null +++ b/2_intermediate/chapter13/solutions/filler @@ -0,0 +1 @@ +#This is filler. Remove later diff --git a/2_intermediate/chapter13/solutions/lexicographical_vector.py b/2_intermediate/chapter13/solutions/lexicographical_vector.py new file mode 100644 index 00000000..de8faafd --- /dev/null +++ b/2_intermediate/chapter13/solutions/lexicographical_vector.py @@ -0,0 +1,72 @@ +""" +Reimplement the __lt__ and __gt__ in the given Vector +class(the one in this section) so that we are comparing +the vector's contents based on lexicographical ordering. +Think of lexicographical ordering as how you arrange words +in a dictionary. For instance, by lexicographical ordering, +'a' < 'ab', 'ab' < 'ad', 'bcd' > 'a'. It works analogously +for numbers, but instead, each character has been substituted +by a number. +""" + +# write your code below + + +class Vector: + def __init__(self, vals): + self.vals = vals + self.length = len(self.vals) + self.scalar = 0 + + def __mul__(self, vec): + ... # see above example + + def morecheck(self, vec, shorter): + for i in range(shorter.length): + if self.vals[i] > vec.vals[i]: + return True + if self.vals[i] < vec.vals[i]: + return False + + def __gt__(self, vec): + assert type(vec) == Vector + if self.length > vec.length: + a = self.morecheck(vec, vec) + if a is not None: + return a + return True # if all other values ==, self = longer/greater + if self.length < vec.length: + a = self.morecheck(vec, self) + if a is not None: + return a + return False # if all other values ==, self = shorter/smaller + if self.length == vec.length: + a = self.morecheck(vec, self) + if a is not None: + return a + return False # if all other values ==, self = equal/not greater + + def lesscheck(self, vec, shorter): + for i in range(shorter.length): + if self.vals[i] < vec.vals[i]: + return True + if self.vals[i] > vec.vals[i]: + return False + + def __lt__(self, vec): + assert type(vec) == Vector + if self.length > vec.length: + a = self.lesscheck(vec, vec) + if a is not None: + return a + return False # if all other values ==, self = longer/greater + if self.length < vec.length: + a = self.lesscheck(vec, self) + if a is not None: + return a + return True # if all other values ==, self = shorter/smaller + if self.length == vec.length: + a = self.lesscheck(vec, self) + if a is not None: + return a + return False # if all other values ==, self = equal/not less diff --git a/2_intermediate/chapter13/solutions/line.py b/2_intermediate/chapter13/solutions/line.py new file mode 100644 index 00000000..a524ff83 --- /dev/null +++ b/2_intermediate/chapter13/solutions/line.py @@ -0,0 +1,23 @@ +""" +Write a class called Line which will take the arguments slope +and intercept in its constructor. When we print the class, +the __str__ method should return a string with the line expressed +in the form "y=mx+b" where m and b are the slope and intercept +respectively. +""" + +# write your code below + + +class Line: + def __init__(self, slope, intercept): + self.slope = slope + self.intercept = intercept + + def __str__(self): + self.equation = "y={}x+{}".format(self.slope, self.intercept) + return self.equation + + +myline = Line(3, 1) +print(str(myline)) diff --git a/2_intermediate/chapter13/solutions/matrix.py b/2_intermediate/chapter13/solutions/matrix.py new file mode 100644 index 00000000..fd1ba70f --- /dev/null +++ b/2_intermediate/chapter13/solutions/matrix.py @@ -0,0 +1,27 @@ +""" +Build a class called Matrix which will take a list of lists +(containing integers) and store it as a field. Add an assertion +using the keyword assert to ensure that the list of lists is +rectangular (i.e. assert len(list_0) = len(list_i) for i in range(n)) +You should also implement a __str__ method so that we can print +the contents of the matrix using print without having to access its field. +""" + +# write your code below + + +class Matrix: + def __init__(self, thelist: list): + self.thelist = thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + + def __str__(self): + return str(self.thelist) + + +mymatrix = Matrix([[3, 4], [7, 8], [4, 8]]) +print(str(mymatrix)) diff --git a/2_intermediate/chapter13/solutions/matrix_add_subtract.py b/2_intermediate/chapter13/solutions/matrix_add_subtract.py new file mode 100644 index 00000000..d2e24973 --- /dev/null +++ b/2_intermediate/chapter13/solutions/matrix_add_subtract.py @@ -0,0 +1,57 @@ +""" +Write a modified version of the Matrix class(that was defined in +one of the example problems in this section) with an __add__ +operation as well as a __sub__ operation. It should add matrices, +assuming that they will be of the same length. Also, the unmodified +Matrix class code will be given. +""" + +# write your code below + + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + + def __str__(self): + return str(self.thelist) +""" + + +class Matrix: + def __init__(self, thelist: list): + self.thelist = thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + + def __str__(self): + return str(self.thelist) + + def __add__(self, other): + assert type(other) == Matrix + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.thelist[items][things] += other.thelist[items][things] + + def __sub__(self, other): + assert type(other) == Matrix + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.thelist[items][things] -= other.thelist[items][things] + + +mymatrix = Matrix([[3, 4], [7, 8]]) +othermatrix = Matrix([[5, 6], [7, 8]]) +mymatrix - othermatrix +print(mymatrix.thelist) diff --git a/2_intermediate/chapter13/solutions/matrix_frobenius_norm.py b/2_intermediate/chapter13/solutions/matrix_frobenius_norm.py new file mode 100644 index 00000000..09be9792 --- /dev/null +++ b/2_intermediate/chapter13/solutions/matrix_frobenius_norm.py @@ -0,0 +1,53 @@ +""" +Write a modified version of the Matrix class(that was defined in +one of the example problems in this section) so that the __str__ +method instead returns a string containing a single number: the +matrix's Frobenius norm. The formula for the Frobenius norm will +be the square root of the sum of all the elements squared in the +matrix. Also, the unmodified Matrix class code will be given. +""" + +# write your code below + +import math + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + + def __str__(self): + return str(self.thelist) +""" + + +class Matrix: + def __init__(self, thelist: list): + self.thelist = thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + self.froebiannorm() + + def froebiannorm(self): + self.squared = 0 + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.squared += self.thelist[items][things] ** 2 + self.norm = math.sqrt(self.squared) + + def __str__(self): + return str(self.norm) + + +mymatrix = Matrix([[3, 4], [7, 8]]) +print(str(mymatrix)) diff --git a/2_intermediate/chapter13/solutions/matrix_less_greater.py b/2_intermediate/chapter13/solutions/matrix_less_greater.py new file mode 100644 index 00000000..5521a3c6 --- /dev/null +++ b/2_intermediate/chapter13/solutions/matrix_less_greater.py @@ -0,0 +1,74 @@ +""" +Implement the less than and greater than operators for +the Matrix class(from a previous example problem) so that +we compare them based on their Frobenius norms which we +have implemented in the earlier section as an exercise. +Also, the unmodified Matrix class code will be given. +""" + +# write your code below + +import math + +""" +This is the unmodified Matrix class code. + +class Matrix: + def __init__(self,thelist: list): + self.thelist=thelist + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + + def __str__(self): + return str(self.thelist) +""" + + +class Matrix: + def __init__(self, thelist: list): + self.thelist = thelist + self.norm = 0 + for items in range(len(self.thelist)): + assert type(self.thelist[items]) == list + assert len(self.thelist[0]) == len(self.thelist[items]) + for things in range(len(self.thelist[items])): + assert type(self.thelist[items][things]) == int + self.froebiannorm() + + def froebiannorm(self): + self.squared = 0 + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.squared += self.thelist[items][things] ** 2 + self.norm = math.sqrt(self.squared) + + def __str__(self): + return str(self.norm) + + def __add__(self, other): + assert type(other) == Matrix + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.thelist[items][things] += other.thelist[items][things] + + def __sub__(self, other): + assert type(other) == Matrix + for items in range(len(self.thelist)): + for things in range(len(self.thelist[items])): + self.thelist[items][things] -= other.thelist[items][things] + + def __lt__(self, other): + assert type(other) == Matrix + return self.norm < other.norm + + def __gt__(self, other): + assert type(other) == Matrix + return self.norm > other.norm + + +mymatrix = Matrix([[3, 4], [7, 8]]) +othermatrix = Matrix([[5, 6], [7, 8]]) +print(mymatrix > othermatrix) diff --git a/2_intermediate/chapter13/solutions/polar_coordinates.py b/2_intermediate/chapter13/solutions/polar_coordinates.py new file mode 100644 index 00000000..ff743831 --- /dev/null +++ b/2_intermediate/chapter13/solutions/polar_coordinates.py @@ -0,0 +1,27 @@ +""" +Write a class called PolarCoordinates which will take a +value called radius and angle. When we print this class, +we want the coordinates in Cartesian coordinates, or we want +you to print two values: x and y. (If you don't know the +conversion formula, x = radius * cos(angle), y = radius * sin(angle). +Use Python's built-in math library for the cosine and sine operators) +""" + +# write your code below + +import math + + +class PolarCoordinates: + def __init__(self, radius, angle): + self.radius = radius + self.angle = angle + + def __str__(self): + self.x = self.radius * math.cos(self.angle) + self.y = self.radius * math.sin(self.angle) + return "{},{}".format(self.x, self.y) + + +group = PolarCoordinates(2, math.pi) +print(str(group)) diff --git a/2_intermediate/chapter13/solutions/triangle.py b/2_intermediate/chapter13/solutions/triangle.py new file mode 100644 index 00000000..31043ab8 --- /dev/null +++ b/2_intermediate/chapter13/solutions/triangle.py @@ -0,0 +1,45 @@ +""" +Write a class called Triangle which will take three tuples +(each tuple contains two integers: the x and y coordinates +of a vertex). Then, define an __add__ operation that acts as +a translation operation. Its input argument will be a tuple +of two integers that will indicate the x and y translations +that will be applied to each coordinate. (basically, add the +tuple to each coordinate of the triangle). Also, define a +vertical and horizontal transformation tool in the form +of __mul__ which will also take a tuple of two integers that +will be multiplied to the x and y coordinates of each vertex +respectively. +""" + +# write your code below + + +class Triangle: + def __init__(self, pair1, pair2, pair3): + self.coordinatelist = [pair1, pair2, pair3] + for i in range(len(self.coordinatelist)): + assert ( + type(self.coordinatelist[i]) == tuple + and len(self.coordinatelist[i]) == 2 + ) + self.coordinatelist[i] = list(self.coordinatelist[i]) + + def __add__(self, other): + assert type(other) == tuple and len(other) == 2 + for i in range(len(self.coordinatelist)): + self.coordinatelist[i][0] += other[0] + self.coordinatelist[i][1] += other[1] + return tuple(self.coordinatelist) + + def __mul__(self, other): + assert type(other) == tuple and len(other) == 2 + for i in range(len(self.coordinatelist)): + self.coordinatelist[i][0] *= other[0] + self.coordinatelist[i][1] *= other[1] + return tuple(self.coordinatelist) + + +mytriangle = Triangle((0, 0), (1, 0), (0, 1)) +print(mytriangle + (1, 1)) +print(mytriangle * (2, 2)) diff --git a/2_intermediate/chapter13/solutions/vector.py b/2_intermediate/chapter13/solutions/vector.py new file mode 100644 index 00000000..95c90664 --- /dev/null +++ b/2_intermediate/chapter13/solutions/vector.py @@ -0,0 +1,39 @@ +""" +Define a Vector class so that the multiply operation is with +another Vector instead. The multiply operation should be the +inner or dot product of the two vectors. That means that each +element in the vector should be multiplied with its +corresponding element in the other vector, and then summed. +A scalar (regular number) should be returned. +""" + +# write your code below + + +class Vector: + def __init__(self, vals): + self.vals = vals + self.length = len(self.vals) + self.scalar = 0 + + def __mul__(self, vec): + assert type(vec) == Vector + a = 0 + if self.length >= vec.length: + for i in range(vec.length): + self.scalar += self.vals[i] * vec.vals[i] + while a + vec.length < self.length: + self.scalar += self.vals[i] + a += 1 + if self.length < vec.length: + for i in range(self.length): + self.scalar += self.vals[i] * vec.vals[i] + while (a + self.length) < vec.length: + self.scalar += self.vals[i] + a += 1 + return self.scalar + + +vector1 = Vector([2, 3, 2]) +vector2 = Vector([3, 4, 5]) +print(vector1 * vector2) # should give 28 diff --git a/2_intermediate/chapter8/practice/food.py b/2_intermediate/chapter8/practice/food.py new file mode 100644 index 00000000..7530aa12 --- /dev/null +++ b/2_intermediate/chapter8/practice/food.py @@ -0,0 +1,11 @@ +""" +Food +Start with an empty list called food. +Ask the user to either enter a fruit, a vegetable, +or a junk food item. Do this 10 times, and each time, +the question you ask should be selected randomly. + +Add each of their answers to the list, sort the list +alphabetically, and then display the final list +by printing each item on a separate line. +""" diff --git a/2_intermediate/chapter8/practice/fortune.py b/2_intermediate/chapter8/practice/fortune.py new file mode 100644 index 00000000..4fc4e49d --- /dev/null +++ b/2_intermediate/chapter8/practice/fortune.py @@ -0,0 +1,10 @@ +""" +Fortune + +Store 6 fortunes cookie messages, and display a +random one each time the user runs the program. + +Assume that you DON'T know how many messages are in the list. + +(Hint: You’re randomly choosing the index to access.) +""" diff --git a/2_intermediate/chapter8/solutions/food.py b/2_intermediate/chapter8/solutions/food.py new file mode 100644 index 00000000..9416d970 --- /dev/null +++ b/2_intermediate/chapter8/solutions/food.py @@ -0,0 +1,30 @@ +""" +Food +Start with an empty list called food. +Ask the user to either enter a fruit, a vegetable, +or a junk food item. Do this 10 times, and each time, +the question you ask should be selected randomly. + +Add each of their answers to the list, sort the list +alphabetically, and then display the final list +by printing each item on a separate line. +""" +import random + +foods = [] +prompts = [ + "Enter a fruit: ", + "Enter a vegetable: ", + "Enter a junk food item: ", +] + +# Choose a random prompt and collect input. +for i in range(10): + i = random.randrange(len(prompts)) + item = input(prompts[i]) + foods.append(item) +print() + +foods.sort() +for food in foods: + print(food) diff --git a/2_intermediate/chapter8/solutions/fortune.py b/2_intermediate/chapter8/solutions/fortune.py new file mode 100644 index 00000000..417fd1c1 --- /dev/null +++ b/2_intermediate/chapter8/solutions/fortune.py @@ -0,0 +1,22 @@ +""" +Fortune + +Store 6 fortunes cookie messages, and display a +random one each time the user runs the program. + +Assume that you DON'T know how many messages are in the list. + +(Hint: You’re randomly choosing the index to access.) +""" +import random + +messages = [ + "You will meet the love of your life today.", + "You will turn into a fish.", + "It will rain diamonds today.", + "You will encounter a field of mangoes.", + "Look for the light. Underneath it, there will be a chess board.", + "You'll run a sub-6:00 mile today.", +] + +print(messages[random.randrange(len(messages))]) diff --git a/2_intermediate/chapter9/examples/dict_values.py b/2_intermediate/chapter9/examples/dict_values.py index 195abdca..ac1a9d0a 100644 --- a/2_intermediate/chapter9/examples/dict_values.py +++ b/2_intermediate/chapter9/examples/dict_values.py @@ -3,7 +3,7 @@ contacts = { "John Doe": "1234 Main St", "Jane Smith": "5678 Market St", - "Daisy Johnson": "1357 Wall St" + "Daisy Johnson": "1357 Wall St", } daisy_address = contacts["Daisy Johnson"] diff --git a/2_intermediate/chapter9/examples/initialize_dict.py b/2_intermediate/chapter9/examples/initialize_dict.py index 2411e087..d29066f5 100644 --- a/2_intermediate/chapter9/examples/initialize_dict.py +++ b/2_intermediate/chapter9/examples/initialize_dict.py @@ -3,7 +3,7 @@ contacts = { "John Doe": "1234 Main St", "Jane Smith": "5678 Market St", - "Daisy Johnson": "1357 Wall St" + "Daisy Johnson": "1357 Wall St", } print(contacts) diff --git a/2_intermediate/chapter9/examples/iterate_dict.py b/2_intermediate/chapter9/examples/iterate_dict.py index 80728a5d..dd979854 100644 --- a/2_intermediate/chapter9/examples/iterate_dict.py +++ b/2_intermediate/chapter9/examples/iterate_dict.py @@ -1,6 +1,6 @@ # Iterating Through Dictionaries -contacts = {'Daisy Johnson': '2468 Park Ave', 'Leo Fitz': '1258 Monkey Dr'} +contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"} # iterate through each key for name in contacts: diff --git a/2_intermediate/chapter9/examples/key_value_membership.py b/2_intermediate/chapter9/examples/key_value_membership.py index bec05c8c..4a95c9f3 100644 --- a/2_intermediate/chapter9/examples/key_value_membership.py +++ b/2_intermediate/chapter9/examples/key_value_membership.py @@ -1,6 +1,6 @@ # Check Key/Value Membership in a Dictionary -contacts = {'Daisy Johnson': '2468 Park Ave', 'Leo Fitz': '1258 Monkey Dr'} +contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"} if "Daisy Johnson" in contacts: print("Daisy Johnson is a key in contacts") diff --git a/2_intermediate/chapter9/examples/manipulate_dict.py b/2_intermediate/chapter9/examples/manipulate_dict.py index 9baef544..cb3e205f 100644 --- a/2_intermediate/chapter9/examples/manipulate_dict.py +++ b/2_intermediate/chapter9/examples/manipulate_dict.py @@ -4,7 +4,7 @@ "John Doe": "1234 Main St", "Jane Smith": "5678 Market St", "Daisy Johnson": "2468 Park Ave", - "Leo Fitz": "1258 Monkey Dr" + "Leo Fitz": "1258 Monkey Dr", } # get - retrieves the value at a specified key diff --git a/2_intermediate/chapter9/examples/why_dict.py b/2_intermediate/chapter9/examples/why_dict.py index 8b8fd210..66268626 100644 --- a/2_intermediate/chapter9/examples/why_dict.py +++ b/2_intermediate/chapter9/examples/why_dict.py @@ -1,16 +1,19 @@ # Why Dictionaries # dictionaries as an alternative to parallel lists -names = ['Jane Doe', 'John Williams', ] -addresses = ['1234 Main St', '5678 Market Pl', '1357 Wall St'] +names = [ + "Jane Doe", + "John Williams", +] +addresses = ["1234 Main St", "5678 Market Pl", "1357 Wall St"] # better solution: make a dictionary to # explicitly associate a name with an address # this is also called mapping a key to a value contacts = { - 'Jane Doe': '1234 Main St', - 'John Williams': '5678 Market Pl', - 'Alex Summers': '1357 Wall St' + "Jane Doe": "1234 Main St", + "John Williams": "5678 Market Pl", + "Alex Summers": "1357 Wall St", } # implementation 1 using if statements diff --git a/2_intermediate/chapter9/practice/catalog.py b/2_intermediate/chapter9/practice/catalog.py new file mode 100644 index 00000000..3b3938f3 --- /dev/null +++ b/2_intermediate/chapter9/practice/catalog.py @@ -0,0 +1,36 @@ +""" +Catalog + +Write a program that takes asks the +user whether they'd like to add, delete, +or clear the entries in a store catalog. + +After they perform some action, the program +should display the updated dictionary in the +format: + item1: price1 + item2: price2 + etc. + +Keep asking them if they'd like to add, delete, +or clear entries until they enter "q". + +Possible actions: +If they enter "add": + Ask them to enter an item. + Ask them to enter a price. + The item should be the key, and the price + should be the value in the dictionary. + +If they enter "delete": + Ask them to to enter which item + they'd like to delete. + +If they enter "clear": + Clear all the entries from the dictionary. + +If they enter "q": + Display the final dictionary and end the program. +""" + +# Insert your code here. diff --git a/2_intermediate/chapter9/practice/participation_grade.py b/2_intermediate/chapter9/practice/participation_grade.py new file mode 100644 index 00000000..8ecad6af --- /dev/null +++ b/2_intermediate/chapter9/practice/participation_grade.py @@ -0,0 +1,51 @@ +# Warning: can be challenging +# +# A teacher is given a list of students.The number of occurences of a student's +# name in the list is the number of times the student participated this week. +# If a student has 8 or more participations, they get an A. If a student has +# between 4 and 7 participations, they get a B. If a student has more than +# 0 but less than 4, the student gets a C. +# +# Make a dictionary with the keys as the students' name and the values as the +# corresponding student's letter grade. Print the dictionary +# +# Write your code below + + +participation_occurences = [ + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", + "Bob", + "Dan", + "Dan", + "Ivan", + "Ivan", + "Ray", + "Sam", + "Sam", + "Dan", + "Ivan", + "Ivan", + "Ray", + "Dan", + "Ivan", + "Ivan", + "Sam", + "Dan", + "Ray", + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", +] diff --git a/2_intermediate/chapter9/practice/word.py b/2_intermediate/chapter9/practice/word.py new file mode 100644 index 00000000..a11cec0e --- /dev/null +++ b/2_intermediate/chapter9/practice/word.py @@ -0,0 +1,19 @@ +""" +Word + +Store words (keys) and definitions (values) +in a dictionary in a random order. + +Then, ask the user to input a word. +If the word is in the dictionary, +use it to display the definition. +Otherwise, print out a message saying +that the word is not there. + +Display the entire dictionary at the end in the format: +word1: definition1 +word2: definition2 +etc. +""" + +# Insert your code here. diff --git a/2_intermediate/chapter9/solutions/catalog.py b/2_intermediate/chapter9/solutions/catalog.py new file mode 100644 index 00000000..abb304cd --- /dev/null +++ b/2_intermediate/chapter9/solutions/catalog.py @@ -0,0 +1,65 @@ +""" +Catalog + +Write a program that takes asks the +user whether they'd like to add, delete, +or clear the entries in a store catalog. + +After they perform some action, the program +should display the updated dictionary in the +format: + item1: price1 + item2: price2 + etc. + +Keep asking them if they'd like to add, delete, +or clear entries until they enter "q". + +Possible actions: +If they enter "add": + Ask them to enter an item. + Ask them to enter a price. + The item should be the key, and the price + should be the value in the dictionary. + +If they enter "delete": + Ask them to to enter which item + they'd like to delete. + +If they enter "clear": + Clear all the entries from the dictionary. + +If they enter "q": + Display the final dictionary and end the program. +""" + +catalog = {} + +while True: + # Display catalog + print("Current catalog:") + if len(catalog) != 0: + for item, price in catalog.items(): + print(item + ": $" + price) + else: + print("Your catalog is empty.") + print() + + ans = input( + "Would you like to add, delete, " + "or clear entries from your catalog? " + ) + + # Perform actions depending on input + if ans == "q": + break + elif ans == "add": + item = input("Enter an item to add: ") + price = input("Enter the price: $") + catalog[item] = price + elif ans == "delete": + item = input("Enter an item to delete: ") + del catalog[item] + elif ans == "clear": + catalog.clear() + print() diff --git a/2_intermediate/chapter9/solutions/participation_grade.py b/2_intermediate/chapter9/solutions/participation_grade.py new file mode 100644 index 00000000..dd4dde72 --- /dev/null +++ b/2_intermediate/chapter9/solutions/participation_grade.py @@ -0,0 +1,68 @@ +# Warning: can be challenging +# +# A teacher is given a list of students.The number of occurences of a student's +# name in the list is the number of times the student participated this week. +# If a student has 8 or more participations, they get an A. If a student has +# between 4 and 7 participations, they get a B. If a student has more than +# 0 but less than 4, the student gets a C. +# +# Make a dictionary with the keys as the students' name and the values as the +# corresponding student's letter grade. Print the dictionary +# +# Write your code below + + +participation_occurences = [ + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", + "Bob", + "Dan", + "Dan", + "Ivan", + "Ivan", + "Ray", + "Sam", + "Sam", + "Dan", + "Ivan", + "Ivan", + "Ray", + "Dan", + "Ivan", + "Ivan", + "Sam", + "Dan", + "Ray", + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", + "Dan", + "Bob", + "Dan", + "Sam", + "Sam", +] + +grade_dict = {} +for student in participation_occurences: + if student not in grade_dict: + grade_dict[student] = 1 + else: + grade_dict[student] += 1 + +for student in grade_dict.keys(): + if grade_dict[student] > 7: + grade_dict[student] = "A" + elif grade_dict[student] > 3: + grade_dict[student] = "B" + else: + grade_dict[student] = "C" + +print(grade_dict) diff --git a/2_intermediate/chapter9/solutions/word.py b/2_intermediate/chapter9/solutions/word.py new file mode 100644 index 00000000..14a61180 --- /dev/null +++ b/2_intermediate/chapter9/solutions/word.py @@ -0,0 +1,37 @@ +""" +Word + +Store words (keys) and definitions (values) +in a dictionary in a random order. + +Then, ask the user to input a word. +If the word is in the dictionary, +use it to display the definition. +Otherwise, print out a message saying +that the word is not there. + +Display the entire dictionary at the end in the format: +word1: definition1 +word2: definition2 +etc. +""" + +dictionary = { + "monkey": "a cute human", + "banana": "sustenance for cute humans", + "neha": "a really strange human", + "phone": "magic communication device", + "cookie": "heaven on Earth", +} + +# Show definition +word = input("Enter a word: ") +if word in dictionary: + print("Definition:", dictionary.get(word)) +else: + print("This word cannot be found.") +print() + +# Display formatted dictionary +for key, value in dictionary.items(): + print(key + ": " + value) diff --git a/3_advanced/chapter14/examples/enumerate.py b/3_advanced/chapter14/examples/enumerate.py new file mode 100644 index 00000000..53023364 --- /dev/null +++ b/3_advanced/chapter14/examples/enumerate.py @@ -0,0 +1,19 @@ +# The enumerate function assigns numbers to every element +# in an iterable, starting with zero. +# it returns an enumerate object, so you have to do list or tuple +# to access the enumerated values. + + +countries = ["Japan", "America", "South Korea", "China"] +numerated_list = list(enumerate(countries)) +print(numerated_list) +# prints [(0, ' Japan'), (1, 'America'), (2, 'South Korea'), (3, ' China')] + + +# This code gets all the countries with even indexes greater than 1 +answer_list = [] +for index, country in enumerate(countries): + if index % 2 == 0 and index > 1: + answer_list.append(country) +print(answer_list) +# prints ['South Korea'] diff --git a/3_advanced/chapter14/examples/list_comp.py b/3_advanced/chapter14/examples/list_comp.py new file mode 100644 index 00000000..1d066806 --- /dev/null +++ b/3_advanced/chapter14/examples/list_comp.py @@ -0,0 +1,32 @@ +# List comprehensions are a faster and more +# elegant way to create a new list +# based on an existing list + + +# squares each number from 0 to 9 and adds to 'listL' +listL = [] +for i in range(10): + listL.append(i * i) +print(listL) +# prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + + +# does the same thing as above, but in shorter, cleaner code +squares = [i * i for i in range(10)] +print(squares) +# also prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + + +# squares all numbers in list 'a' IF they are greater than 5 +a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +squares = [i * i for i in a if i > 5] +print(squares) +# prints [36, 49, 64, 81, 100] + + +# converts all letters in 'word' to uppercase and adds to list 'ask' +word = " Hey how are you" +asks = [i.upper() for i in word] +print(asks) +# prints [' ', 'H', 'E', 'Y', ' ', 'H', 'O', 'W', +# ' ', 'A', 'R', 'E', ' ', 'Y', 'O', 'U'] diff --git a/3_advanced/chapter14/examples/swapping_vars.py b/3_advanced/chapter14/examples/swapping_vars.py new file mode 100644 index 00000000..3ed76f03 --- /dev/null +++ b/3_advanced/chapter14/examples/swapping_vars.py @@ -0,0 +1,33 @@ +# Normally, when switching the values of two variables, +# you need a third, temporary variable. With python, +# you can ignore that step using tuple unpacking. + + +""" Switching two variables with a temporary variable """ +# Switching 2 and 3 +list1 = [1, 2, 3, 4, 5] + +temp = list1[1] +list1[1] = list1[2] +list1[2] = temp + +print(list1) +# prints [1, 3, 2, 4, 5] + + +""" Switching two variables without a temporary variable """ +list1 = [1, 2, 3, 4, 5] + +list1[1], list1[2] = list1[2], list1[1] + +print(list1) +# also prints [1, 3, 2, 4, 5] + + +""" Switching many variables without a temporary variable """ +list1 = [1, 2, 3, 4, 5] + +list1[0], list1[1], list1[2] = list1[1], list1[2], list1[0] + +print(list1) +# prints [2, 3, 1, 4, 5] diff --git a/3_advanced/chapter14/examples/tuple_unpack.py b/3_advanced/chapter14/examples/tuple_unpack.py new file mode 100644 index 00000000..2404891e --- /dev/null +++ b/3_advanced/chapter14/examples/tuple_unpack.py @@ -0,0 +1,27 @@ +# Extracting values from "countries" + + +""" Typical way to extract values """ +countries = ("china", "mexico", "brazil", "USA") + +a = countries[0] +b = countries[1] +c = countries[2] +d = countries[3] + +print(a, b, c, d) # prints "china mexico brazil USA" + + +""" Extracting values with tuple unpacking """ +a, b, c, d = countries + +print(a, b, c, d) # prints "china mexico brazil USA" + + +""" Special feature for tuple unpacking """ +# Using the * says that you want all values +# in the middle of the tuple to be put together +# in a list. +a, *b, c = countries + +print(a, b, c) # prints "china ["mexico", "brazil"] USA" diff --git a/3_advanced/chapter14/examples/zip.py b/3_advanced/chapter14/examples/zip.py new file mode 100644 index 00000000..34f51221 --- /dev/null +++ b/3_advanced/chapter14/examples/zip.py @@ -0,0 +1,27 @@ +# The zip function groups elements from different +# iterables into tuples by their index + + +a = [1, 2, 3] +b = ["a", "b", "c"] +c = ["!", "@", "#"] + +G = zip(a, b, c) + +print(list(G)) +# prints [(1, 'a', '!'), (2, 'b', '@'), (3, 'c', '#')] + + +list_one = [1, 2] +list_two = [41] + +for pair in zip(list_one, list_two): + print(pair) +# this would only print (1, 41) because list_two has only one element + + +countries = [" Japan", "America", "South Korea", " China"] +numbers = [1, 2, 3, 4] +dict1 = dict(zip(countries, numbers)) +print(dict1) +# prints {' China': 4, ' Japan': 1, 'America': 2, 'South Korea': 3} diff --git a/3_advanced/chapter14/practice/add_10.py b/3_advanced/chapter14/practice/add_10.py new file mode 100644 index 00000000..ad466151 --- /dev/null +++ b/3_advanced/chapter14/practice/add_10.py @@ -0,0 +1,13 @@ +# Problem name: add_10 +# A messy teacher named Bob would like to add 10 points to each +# student’s recent test score. +# There are four students, and going from highest score to lowest +# score, it is Mike, Dan, Stan, and Ban. +# Add 10 to each score and assign those values to the correct student. +# Solve this problem by adding no more than 2 lines of code. +# Hint: Use tuple unpacking and list comprehension. + +# the scores are given +scores = (100, 90, 80, 70) + +# write your code below diff --git a/3_advanced/chapter14/practice/bob_selection.py b/3_advanced/chapter14/practice/bob_selection.py new file mode 100644 index 00000000..24b0e826 --- /dev/null +++ b/3_advanced/chapter14/practice/bob_selection.py @@ -0,0 +1,22 @@ +""" +Problem Name: bob_selection +Bob is choosing a person to go to the moon with him. The way he +chooses is quite strange. He will choose the first person from a +list given to him whose age is divisible by 5 and whose index +within the list is divisible by 5. If he does find such a person, +print the person’s name. If he doesn’t, don’t print anything. The +list given to him contains lists which contain the person’s name +and age. Use enumerate to solve this problem. +""" + +# the list is given to him +people_list = [ + ("Ana", 22), + ("Mark", 41), + ("Dan", 10), + ("Jack", 14), + ("Ben", 51), + ("Jorge", 65), +] + +# write your code below diff --git a/3_advanced/chapter14/practice/darwin_raccoon.py b/3_advanced/chapter14/practice/darwin_raccoon.py new file mode 100644 index 00000000..4ca34dc3 --- /dev/null +++ b/3_advanced/chapter14/practice/darwin_raccoon.py @@ -0,0 +1,16 @@ +""" +Problem Name: darwin_raccoon +Darwin is observing raccoons’ growths on an unnamed island. He spends 7 days +in total on this island, and on every day, he would record the average growth +of raccoons in inches. He loses data on day 7, so he decides to make the data +on that day to be the maximum of the previous 6 days. He needs to make a +dictionary for use later where the key is the day number and the value is the +average growth of raccoons on that day. You help him make the dictionary. +Use zip to solve this problem. +""" + +# The lists are already given to you +days_list = ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"] +growths_list = [1.4, 2.1, 1.3, 0.1, 0.4, 1.9] + +# write your code below diff --git a/3_advanced/chapter14/practice/even_words.py b/3_advanced/chapter14/practice/even_words.py new file mode 100644 index 00000000..ea46e178 --- /dev/null +++ b/3_advanced/chapter14/practice/even_words.py @@ -0,0 +1,11 @@ +# Problem name: even_words +# Given a string that the user inputs create a list that contains the +# square of the lengths of words with an even amount of characters. +# +# For example, if the string is "I am cool", the list would be [4, 16]. +# Use a list comprehension to solve it. + +# The user inputs the string +string = input() + +# write your code below diff --git a/3_advanced/chapter14/practice/odd_squares.py b/3_advanced/chapter14/practice/odd_squares.py new file mode 100644 index 00000000..50d63c21 --- /dev/null +++ b/3_advanced/chapter14/practice/odd_squares.py @@ -0,0 +1,12 @@ +# Problem name: odd_squares +# Given a list of integers, create a list of all the squares of the odd +# integers within the list. +# Use a list comprehension to solve it. + +# the given code takes an input and makes it a list of numbers +# for example, entering “1 23 4” as the input will result in the list [1,23,4] +ex_list = input().split() +for idx in range(len(ex_list)): + ex_list[idx] = int(ex_list[idx]) + +# write your code below diff --git a/3_advanced/chapter14/practice/pokemon_presentation.py b/3_advanced/chapter14/practice/pokemon_presentation.py new file mode 100644 index 00000000..a471120b --- /dev/null +++ b/3_advanced/chapter14/practice/pokemon_presentation.py @@ -0,0 +1,17 @@ +""" +Problem Name: pokemon_presentation +You’re a teacher giving a presentation on the types +(https://pokemon.fandom.com/wiki/Types) of pokemons +(https://www.pokemon.com/us/pokedex/). You have a list pokemons_list, +and you have another list types_list(this has the types of the +pokemons in pokemons_lists in the same order). Since you are +presenting, print “[insert pokemon] is a [insert type] type” for all +the pokemons in pokemons_list with their corresponding types in +types_list. Use zip to solve this problem. +""" + +# the lists are already given to you +pokemons_list = ["Charmander", "Squirtle", "Bulbasaur", "Pikachu"] +types_list = ["Fire", "Water", "Grass and Poison", "Electric"] + +# write your code below diff --git a/3_advanced/chapter14/practice/square_root_list.py b/3_advanced/chapter14/practice/square_root_list.py new file mode 100644 index 00000000..353209ab --- /dev/null +++ b/3_advanced/chapter14/practice/square_root_list.py @@ -0,0 +1,16 @@ +""" +Problem Name: square_root_list +Take a user given list of numbers and make a list of all the +square roots of the numbers using list comprehension. Use a +list comprehension to solve it. +Hint: The square root of a number is the same as taking the one half +power of a number. +""" + +# The given code takes an input and makes it a list of numbers. +# For example, entering “1 23 4” as the input will result in the list [1,23,4] +ex_list = input().split() +for idx in range(len(ex_list)): + ex_list[idx] = int(ex_list[idx]) + +# write your code below diff --git a/3_advanced/chapter14/practice/update_score.py b/3_advanced/chapter14/practice/update_score.py new file mode 100644 index 00000000..4b666dde --- /dev/null +++ b/3_advanced/chapter14/practice/update_score.py @@ -0,0 +1,20 @@ +# Problem name: update_score +# A hacker named Dan wishes to hack into a competition where +# they judge participants in three categories on a scale of 10. +# Dan wants his friend Bob to win. +# Bob will only win if he has all 10s while the +# other competitors, Jo and Stan, don’t. + +# Judges will store the scoring within a tuple ([...], [...], [...]). +# The scores before Dan hacked are given. +# Bob will be located as the first person the judges scored and will +# have the lowest points out of any participant. + +# Create a program to help Dan help Bob win. +# Also, print Bob’s score at the end. +# Use tuple unpacking to solve this problem. + +# the scores are given +scores = ([1, 1, 1], [2, 2, 2], [3, 3, 3]) + +# write your code below diff --git a/3_advanced/chapter14/practice/worried_josh.py b/3_advanced/chapter14/practice/worried_josh.py new file mode 100644 index 00000000..75e477e7 --- /dev/null +++ b/3_advanced/chapter14/practice/worried_josh.py @@ -0,0 +1,18 @@ +# Problem Name: worried_josh + +""" +Josh is worried about his test score. He wants to score in the top n, +where n is a positive integer that the user inputs. Given a list of +student names where the student with the highest score is the 0th index +and the score goes down from there, print “YES!” if Josh scores in the top n, +and “NO :(“ if he doesn’t. Assume n will not be greater than the number of +students. Use enumerate to solve this problem. +""" + +# the list of student names is given and the n is a user input +# remember the +# leftmost student = highest score, rightmost student = lowest score +students = ["Dan", "Isaac", "Jo", "Josh", "Dennis", "Erwin", "Ivan", "Penny"] +n = int(input()) + +# write your code below diff --git a/3_advanced/chapter14/solutions/add_10.py b/3_advanced/chapter14/solutions/add_10.py new file mode 100644 index 00000000..3c7bf125 --- /dev/null +++ b/3_advanced/chapter14/solutions/add_10.py @@ -0,0 +1,15 @@ +# Problem name: add_10 +# A messy teacher named Bob would like to add 10 points to each +# student’s recent test score. +# There are four students, and going from highest score to lowest +# score, it is Mike, Dan, Stan, and Ban. +# Add 10 to each score and assign those values to the correct student. +# Solve this problem by adding no more than 2 lines of code. +# Hint: Use tuple unpacking and list comprehension. + +# the scores are given +scores = (100, 90, 80, 70) + +# write your code below +scores_added = [n + 10 for n in scores] +Mike, Dan, Stan, Ban = scores_added diff --git a/3_advanced/chapter14/solutions/bob_selection.py b/3_advanced/chapter14/solutions/bob_selection.py new file mode 100644 index 00000000..63714617 --- /dev/null +++ b/3_advanced/chapter14/solutions/bob_selection.py @@ -0,0 +1,26 @@ +""" +Problem Name: bob_selection +Bob is choosing a person to go to the moon with him. The way he +chooses is quite strange. He will choose the first person from a +list given to him whose age is divisible by 5 and whose index +within the list is divisible by 5. If he does find such a person, +print the person’s name. If he doesn’t, don’t print anything. The +list given to him contains lists which contain the person’s name +and age. Use enumerate to solve this problem. +""" + +# the list is given to him +people_list = [ + ("Ana", 22), + ("Mark", 41), + ("Dan", 10), + ("Jack", 14), + ("Ben", 51), + ("Jorge", 65), +] + +# write your code below +for index, person_data in enumerate(people_list): + if person_data[1] % 5 == 0 and index % 5 == 0: + print(person_data[0]) + break diff --git a/3_advanced/chapter14/solutions/darwin_raccoon.py b/3_advanced/chapter14/solutions/darwin_raccoon.py new file mode 100644 index 00000000..5083c40c --- /dev/null +++ b/3_advanced/chapter14/solutions/darwin_raccoon.py @@ -0,0 +1,17 @@ +""" +Problem Name: darwin_raccoon +Darwin is observing raccoons’ growths on an unnamed island. He spends 7 days +in total on this island, and on every day, he would record the average growth +of raccoons in inches. He loses data on day 7, so he decides to make the data +on that day to be the maximum of the previous 6 days. He needs to make a +dictionary for use later where the key is the day number and the value is the +average growth of raccoons on that day. You help him make the dictionary. +Use zip to solve this problem. +""" + +# The lists are already given to you +days_list = ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"] +growths_list = [1.4, 2.1, 1.3, 0.1, 0.4, 1.9] + +# write your code below +data_dictionary = dict(zip(days_list, growths_list + [max(growths_list)])) diff --git a/3_advanced/chapter14/solutions/even_words.py b/3_advanced/chapter14/solutions/even_words.py new file mode 100644 index 00000000..4cc6bd57 --- /dev/null +++ b/3_advanced/chapter14/solutions/even_words.py @@ -0,0 +1,12 @@ +# Problem name: even_words +# Given a string that the user inputs create a list that contains the +# square of the lengths of words with an even amount of characters. +# +# For example, if the string is "I am cool", the list would be [4, 16]. +# Use a list comprehension to solve it. + +# The user inputs the string +string = input() + +# write your code below +evenwords = [len(word) ** 2 for word in string.split() if len(word) % 2 == 0] diff --git a/3_advanced/chapter14/solutions/odd_squares.py b/3_advanced/chapter14/solutions/odd_squares.py new file mode 100644 index 00000000..4a4dfd74 --- /dev/null +++ b/3_advanced/chapter14/solutions/odd_squares.py @@ -0,0 +1,13 @@ +# Problem name: odd_squares +# Given a list of integers, create a list of all the squares of the odd +# integers within the list. +# Use a list comprehension to solve it. + +# the given code takes an input and makes it a list of numbers +# for example, entering “1 23 4” as the input will result in the list [1,23,4] +ex_list = input().split() +for idx in range(len(ex_list)): + ex_list[idx] = int(ex_list[idx]) + +# write your code below +odds_quares = [n**2 for n in list if n % 2 == 1] diff --git a/3_advanced/chapter14/solutions/pokemon_presentation.py b/3_advanced/chapter14/solutions/pokemon_presentation.py new file mode 100644 index 00000000..ff9cb3fc --- /dev/null +++ b/3_advanced/chapter14/solutions/pokemon_presentation.py @@ -0,0 +1,19 @@ +""" +Problem Name: pokemon_presentation +You’re a teacher giving a presentation on the types +(https://pokemon.fandom.com/wiki/Types) of pokemons +(https://www.pokemon.com/us/pokedex/). You have a list pokemons_list, +and you have another list types_list(this has the types of the +pokemons in pokemons_lists in the same order). Since you are +presenting, print “[insert pokemon] is a [insert type] type” for all +the pokemons in pokemons_list with their corresponding types in +types_list. Use zip to solve this problem. +""" + +# the lists are already given to you +pokemons_list = ["Charmander", "Squirtle", "Bulbasaur", "Pikachu"] +types_list = ["Fire", "Water", "Grass and Poison", "Electric"] + +# write your code below +for pokemon, tp in zip(pokemons_list, types_list): + print(pokemon + " is a " + tp + " type") diff --git a/3_advanced/chapter14/solutions/square_root_list.py b/3_advanced/chapter14/solutions/square_root_list.py new file mode 100644 index 00000000..862835c8 --- /dev/null +++ b/3_advanced/chapter14/solutions/square_root_list.py @@ -0,0 +1,17 @@ +""" +Problem Name: square_root_list +Take a user given list of numbers and make a list of all the +square roots of the numbers using list comprehension. Use a +list comprehension to solve it. +Hint: The square root of a number is the same as taking the one half +power of a number. +""" + +# The given code takes an input and makes it a list of numbers. +# For example, entering "1 23 4" as the input will result in the list [1,23,4] +ex_list = input().split() +for idx in range(len(ex_list)): + ex_list[idx] = int(ex_list[idx]) + +# write your code below +new_list = [number ** (1 / 2) for number in ex_list] diff --git a/3_advanced/chapter14/solutions/update_score.py b/3_advanced/chapter14/solutions/update_score.py new file mode 100644 index 00000000..76e6ade5 --- /dev/null +++ b/3_advanced/chapter14/solutions/update_score.py @@ -0,0 +1,25 @@ +# Problem name: update_score +# A hacker named Dan wishes to hack into a competition where +# they judge participants in three categories on a scale of 10. +# Dan wants his friend Bob to win. +# Bob will only win if he has all 10s while the +# other competitors, Jo and Stan, don’t. + +# Judges will store the scoring within a tuple ([...], [...], [...]). +# The scores before Dan hacked are given. +# Bob will be located as the first person the judges scored and will +# have the lowest points out of any participant. + +# Create a program to help Dan help Bob win. +# Also, print Bob’s score at the end. +# Use tuple unpacking to solve this problem. + +# the scores are given +scores = ([1, 1, 1], [2, 2, 2], [3, 3, 3]) + +# write your code below +scores[0][0] = 10 +scores[0][1] = 10 +scores[0][2] = 10 +(Bob, Jo, Stan) = scores +print(Bob) diff --git a/3_advanced/chapter14/solutions/worried_josh.py b/3_advanced/chapter14/solutions/worried_josh.py new file mode 100644 index 00000000..8af9207e --- /dev/null +++ b/3_advanced/chapter14/solutions/worried_josh.py @@ -0,0 +1,26 @@ +# Problem Name: worried_josh + +""" +Josh is worried about his test score. He wants to score in the top n, +where n is a positive integer that the user inputs. Given a list of +student names where the student with the highest score is the 0th index +and the score goes down from there, print “YES!” if Josh scores in the top n, +and “NO :(“ if he doesn’t. Assume n will not be greater than the number of +students. Use enumerate to solve this problem. +""" + +# the list of student names is given and the n is a user input +# remember the +# leftmost student = highest score, rightmost student = lowest score +students = ["Dan", "Isaac", "Jo", "Josh", "Dennis", "Erwin", "Ivan", "Penny"] +n = int(input()) + +# write your code below + +said_yes = False +for index, name in enumerate(students): + if name == "Josh" and index + 1 <= n: + print("YES!") + said_yes = True +if not said_yes: + print("NO :(") diff --git a/3_advanced/chapter15/examples/calculate_time.py b/3_advanced/chapter15/examples/calculate_time.py new file mode 100644 index 00000000..a2e01338 --- /dev/null +++ b/3_advanced/chapter15/examples/calculate_time.py @@ -0,0 +1,13 @@ +# This code will get all the odd birthdays and print it +birthdays = [12, 4, 21, 11, 24] # O(1) + +odd_birthdays = [] # O(1) +for birthday in birthdays: # O(n) + if birthday % 2 == 1: # O(1)*O(n) = O(n) + odd_birthdays.append(birthday) # O(1)*O(n) = O(n) + +print(odd_birthdays) # O(1) + +# Sum = O(1) + O(1) + O(n) + O(n) + O(n) + O(1) +# Sum = 3*O(1) + 3*O(n) +# Final Running Time = O(n) diff --git a/3_advanced/chapter15/examples/running_time.py b/3_advanced/chapter15/examples/running_time.py new file mode 100644 index 00000000..2f06c596 --- /dev/null +++ b/3_advanced/chapter15/examples/running_time.py @@ -0,0 +1,32 @@ +""" O(1) """ +# Any assignments +x = 1 # O(1) +x += 1 # O(1) + +# If statement structure +# Condition and code inside not always O(1) +if 1 == 1: # O(1) + print(1) # O(1) +else: # O(1) + print(2) # O(1) + +# Some list operations +x = [1, 2, 4, 213] +x.append(14) # O(1) +x[0] = 11 # O(1) + + +""" O(n) """ +# "Most" for loops are O(n) +for number in [123, 4, 21, 312, 41]: # O(n) + print(number) # O(1) + + +""" O(n^2), O(n^3), etc. """ +# "Most" of the time, every extra for loop +# increases running time by a factor of n + +example_list = [12, 3, 214, 5, 12] +for num1 in example_list: # O(n) + for num2 in example_list: # O(n) + print(num1, num2) # O(1) diff --git a/3_advanced/chapter15/examples/tricky.py b/3_advanced/chapter15/examples/tricky.py new file mode 100644 index 00000000..1406a8a6 --- /dev/null +++ b/3_advanced/chapter15/examples/tricky.py @@ -0,0 +1,17 @@ +# Tricky if statements +ex_list = [1, 23, 421, 32] +if 1 == 2: + for num in ex_list: + print(num) +else: + print(ex_list) + + +# Loops ending prematurely +ex_list = [1, 23, 421, 32] +counter = 0 +for num in ex_list: + counter += 1 + print(num) + if counter == 1: + break diff --git a/3_advanced/chapter15/practice/ch15_practice1.py b/3_advanced/chapter15/practice/ch15_practice1.py new file mode 100644 index 00000000..d605dbe0 --- /dev/null +++ b/3_advanced/chapter15/practice/ch15_practice1.py @@ -0,0 +1,17 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it has +n elements. At the end, put the total running time of +code. + + +ex_list = [?,?,?...] #Input,O(1) +num_even = 0 #O(1) +for num in ex_list: + if num % 2 == 0: + num_even += 1 +print(num_even) +""" diff --git a/3_advanced/chapter15/practice/ch15_practice2.py b/3_advanced/chapter15/practice/ch15_practice2.py new file mode 100644 index 00000000..9e886b2e --- /dev/null +++ b/3_advanced/chapter15/practice/ch15_practice2.py @@ -0,0 +1,19 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it has +n elements. At the end, put the total running time of +code. + + +# ex_list = [?,?,?,...]#Input,O(1) +for i in range(2): # O(1) + ex_list.insert(0, 1) + ex_list.append(1) +for number in ex_list: + for number in ex_list: + break + break +""" diff --git a/3_advanced/chapter15/practice/ch15_practice3.py b/3_advanced/chapter15/practice/ch15_practice3.py new file mode 100644 index 00000000..582bf665 --- /dev/null +++ b/3_advanced/chapter15/practice/ch15_practice3.py @@ -0,0 +1,20 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it +has n elements. At the end, put the total running +time of code. + + +ex_list = [?,?,?,...]#Input,O(1) +for i in range(len(ex_list)):#O(n) + if i%2 == 0: + print(1) + else: + print(2) + for j in range(len(ex_list)): + for k in range(len(ex_list)): + print(j,k) +""" diff --git a/3_advanced/chapter15/practice/ch15_practice4.py b/3_advanced/chapter15/practice/ch15_practice4.py new file mode 100644 index 00000000..ebf66abd --- /dev/null +++ b/3_advanced/chapter15/practice/ch15_practice4.py @@ -0,0 +1,18 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it +has n elements. At the end, put the total running +time of code. Note: You will be surprised! + + +ex_list = [?,?,?,...]#Input,O(1) +for i in range(len(ex_list)):#O(n) + print(i) + ex_list.append(i) +for i in ex_list: + print(i) + ex_list.append(i) +""" diff --git a/3_advanced/chapter15/practice/ch15_practice5.py b/3_advanced/chapter15/practice/ch15_practice5.py new file mode 100644 index 00000000..8e456b10 --- /dev/null +++ b/3_advanced/chapter15/practice/ch15_practice5.py @@ -0,0 +1,18 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +At the end, put the total running time of code. +The input of the problem is ex_2d_list, and assume +it has n numbers. This problem assumes you have the +knowledge of 2D Lists. + + +ex_2d_list = [[?,?,?],[?,?]...]#Input,O(1) +list_sum = 0#O(1) +for ex_1d_list in ex_2d_list: + for element in ex_1d_list: + list_sum += element +print(list_sum) +""" diff --git a/3_advanced/chapter15/solutions/ch15_practice1.py b/3_advanced/chapter15/solutions/ch15_practice1.py new file mode 100644 index 00000000..b324171b --- /dev/null +++ b/3_advanced/chapter15/solutions/ch15_practice1.py @@ -0,0 +1,18 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it has +n elements. At the end, put the total running time of +code. + + +ex_list = [?,?,?...] #Input,O(1) +num_even = 0 #O(1) +for num in ex_list: #O(n) + if num % 2 == 0: #O(1) + num_even += 1 #O(1) +print(num_even) #O(1) +#Total running time = O(n) +""" diff --git a/3_advanced/chapter15/solutions/ch15_practice2.py b/3_advanced/chapter15/solutions/ch15_practice2.py new file mode 100644 index 00000000..d193e4e5 --- /dev/null +++ b/3_advanced/chapter15/solutions/ch15_practice2.py @@ -0,0 +1,20 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it has +n elements. At the end, put the total running time of +code. + + +ex_list = [?,?,?,...]#Input,O(1) +for i in range(2):#O(1) + ex_list.insert(0,1)#O(n) + ex_list.append(1)#O(1) +for number in ex_list:#O(1) + for number in ex_list:#O(1) + break#O(1) + break#O(1) +#Total running time = O(n) +""" diff --git a/3_advanced/chapter15/solutions/ch15_practice3.py b/3_advanced/chapter15/solutions/ch15_practice3.py new file mode 100644 index 00000000..94f6739d --- /dev/null +++ b/3_advanced/chapter15/solutions/ch15_practice3.py @@ -0,0 +1,21 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it +has n elements. At the end, put the total running +time of code. + + +ex_list = [?,?,?,...]#Input,O(1) +for i in range(len(ex_list)):#O(n) + if i%2 == 0:#O(1) + print(1)#O(1) + else:#O(1) + print(2)#O(1) + for j in range(len(ex_list)):#O(n) + for k in range(len(ex_list)):#O(n) + print(j,k)#O(1) +#Total running time = O(n^3) +""" diff --git a/3_advanced/chapter15/solutions/ch15_practice4.py b/3_advanced/chapter15/solutions/ch15_practice4.py new file mode 100644 index 00000000..29e88c25 --- /dev/null +++ b/3_advanced/chapter15/solutions/ch15_practice4.py @@ -0,0 +1,28 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +The input of the problem is ex_list, and assume it +has n elements. At the end, put the total running +time of code. Note: You will be surprised! + + +ex_list = [?,?,?,...]#Input,O(1) +for i in range(len(ex_list)):#O(n) + print(i)#O(1) + ex_list.append(i)#O(1) +for i in ex_list:#No Big-O. Runs forever. + print(i)#O(1) + ex_list.append(i)#O(1) +#Total running time = There is no upper bound, so +#no Big-O. +# +#Explanation: The second for loop will keep looping +#since ex_list will keep increasing in size each time +#you loop. You may ask why doesn't the first for loop do +#the same? That is because the number of times the first +#for loop loops is set at the very start of the loop, +#whereas for the second for loop will keep looping until +#every element is checked. +""" diff --git a/3_advanced/chapter15/solutions/ch15_practice5.py b/3_advanced/chapter15/solutions/ch15_practice5.py new file mode 100644 index 00000000..a56efd4d --- /dev/null +++ b/3_advanced/chapter15/solutions/ch15_practice5.py @@ -0,0 +1,23 @@ +""" +The following code is not meant to be run because +there's no input. Instead, analyze it's running time +in terms of Big-O. The first two lines are already +analyzed for you. Do the same for all the other lines. +At the end, put the total running time of code. +The input of the problem is ex_2d_list, and assume +it has n numbers. This problem assumes you have the +knowledge of 2D Lists. + + +ex_2d_list = [[?,?,?],[?,?]...]#Input,O(1) +list_sum = 0#O(1) +for ex_1d_list in ex_2d_list:#This line and next line combined = O(n) + for element in ex_1d_list: + list_sum += element#O(1) +print(list_sum)#O(1) +#Total running time = O(n) +# +#Explanation: We are finding the running time in terms of the input. +#The whole 2d list has n elements so the double for loop will loop +#n times in total. +""" diff --git a/3_advanced/chapter16/examples/Selection Sort Code.py b/3_advanced/chapter16/examples/Selection Sort Code.py new file mode 100644 index 00000000..dc919a08 --- /dev/null +++ b/3_advanced/chapter16/examples/Selection Sort Code.py @@ -0,0 +1,9 @@ +arr = [1, 4, 2, 7, 7, 6] # change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx + 1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +print(arr) diff --git a/3_advanced/chapter16/examples/Selection_Sort_analyzed.py b/3_advanced/chapter16/examples/Selection_Sort_analyzed.py new file mode 100644 index 00000000..a37ce68a --- /dev/null +++ b/3_advanced/chapter16/examples/Selection_Sort_analyzed.py @@ -0,0 +1,18 @@ +arr = [int, int, int] # this is the input, so we're not analyzing it + +for first_idx in range(len(arr)): # O(n) + min_idx = first_idx # O(1) * O(n) = O(n) + + for second_idx in range(first_idx + 1, len(arr)): # O(n) * O(n) = O(n^2) + if arr[second_idx] < arr[min_idx]: # O(1) * O(n) * O(n) = O(n^2) + min_idx = second_idx # O(1) * O(n) * O(n) = O(n^2) + + arr[first_idx], arr[min_idx] = ( + arr[min_idx], + arr[first_idx], + ) # O(1) * O(n) = O(n) + + +# Sum = O(n) + O(n) + O(n^2) + O(n^2) + O(n^2) + O(n) +# Sum = 3*O(n) + 3*O(n^2) +# Final Running Time = O(n^2) diff --git a/3_advanced/chapter16/practice/selection_sort_even.py b/3_advanced/chapter16/practice/selection_sort_even.py new file mode 100644 index 00000000..2be5473c --- /dev/null +++ b/3_advanced/chapter16/practice/selection_sort_even.py @@ -0,0 +1,18 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify this code so that the code sorts only the elements at the even +indexes, ignoring elements at odd indexes. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below diff --git a/3_advanced/chapter16/practice/selection_sort_f3.py b/3_advanced/chapter16/practice/selection_sort_f3.py new file mode 100644 index 00000000..3fb8c4d5 --- /dev/null +++ b/3_advanced/chapter16/practice/selection_sort_f3.py @@ -0,0 +1,18 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify this code so that the code sorts only the first three elements +of an array. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below diff --git a/3_advanced/chapter16/practice/selection_sort_gtl.py b/3_advanced/chapter16/practice/selection_sort_gtl.py new file mode 100644 index 00000000..52459438 --- /dev/null +++ b/3_advanced/chapter16/practice/selection_sort_gtl.py @@ -0,0 +1,17 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify the code so that the code sorts an array from greatest to least. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below diff --git a/3_advanced/chapter16/solutions/selection_sort_even.py b/3_advanced/chapter16/solutions/selection_sort_even.py new file mode 100644 index 00000000..5e23944e --- /dev/null +++ b/3_advanced/chapter16/solutions/selection_sort_even.py @@ -0,0 +1,28 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify this code so that the code sorts only the elements at the even +indexes, ignoring elements at odd indexes. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below + +arr = [4, 1, 2, 5, 123, 98, 23] +for first_idx in range(0, len(arr), 2): # range(start, stop, step) + min_idx = first_idx + for second_idx in range(first_idx, len(arr), 2): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +print(arr) diff --git a/3_advanced/chapter16/solutions/selection_sort_f3.py b/3_advanced/chapter16/solutions/selection_sort_f3.py new file mode 100644 index 00000000..8fabd885 --- /dev/null +++ b/3_advanced/chapter16/solutions/selection_sort_f3.py @@ -0,0 +1,30 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify this code so that the code sorts only the first three elements +of an array. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below + +arr = [4, 1, 2, 5, 123, 98, 23] +f3_arr = arr[:3] # this will contains the elements before the 3rd index. +remaining_arr = arr[3:] # this will be [] if original arr <= 3 +for first_idx in range(len(f3_arr)): + min_idx = first_idx + for second_idx in range(first_idx + 1, len(f3_arr)): + if f3_arr[second_idx] < f3_arr[min_idx]: + min_idx = second_idx + f3_arr[first_idx], f3_arr[min_idx] = f3_arr[min_idx], f3_arr[first_idx] + +print(f3_arr + remaining_arr) # adding lists will combine the lists diff --git a/3_advanced/chapter16/solutions/selection_sort_gtl.py b/3_advanced/chapter16/solutions/selection_sort_gtl.py new file mode 100644 index 00000000..425e064b --- /dev/null +++ b/3_advanced/chapter16/solutions/selection_sort_gtl.py @@ -0,0 +1,26 @@ +""" +The Selection Sort code we saw sorts an array from least to greatest. +Modify the code so that the code sorts an array from greatest to least. + +Selection Sort Code: + +arr = [?,?,?]#change this array to the array you want to sort +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx+1, len(arr)): + if arr[second_idx] < arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] + +""" + +# write your code below + +arr = [1, 27, 412, 3, 12, 4] +for first_idx in range(len(arr)): + min_idx = first_idx + for second_idx in range(first_idx + 1, len(arr)): + if arr[second_idx] > arr[min_idx]: + min_idx = second_idx + arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx] +print(arr) diff --git a/3_advanced/chapter17/examples/Maybe Not a Set.py b/3_advanced/chapter17/examples/Maybe Not a Set.py new file mode 100644 index 00000000..04383cf9 --- /dev/null +++ b/3_advanced/chapter17/examples/Maybe Not a Set.py @@ -0,0 +1,2 @@ +maybe_not_a_set = {} +print(type(maybe_not_a_set)) diff --git a/3_advanced/chapter17/examples/sets.py b/3_advanced/chapter17/examples/sets.py new file mode 100644 index 00000000..7cb86a04 --- /dev/null +++ b/3_advanced/chapter17/examples/sets.py @@ -0,0 +1,54 @@ +# initialize a set with the following syntax +myset = {"item 1", "item 2", "any type besides list and dict", 5, 8, 3} +# or +myothset = set() # creates an empty set +notaset = {} # doesn't create a set; creates a dict; remember that + +# sets don't always print the same way +# try it +print(myset) +print(myset) +print(myset) +# for this reason, indexing won't work with sets +# try it +anotherset = {"this", "might", "not", "be", "in", "order"} +for i in anotherset: + print(i) + +# subsets and supersets +# a superset is a set that has all the items that a subset has +oursuperset = {1, 3, 5, 7, 9} +oursubset = {1, 5, 3} + +# should print True since oursuperset has 1,5, and 3 +print(oursuperset.issuperset(oursubset)) +# should print True since oursuperset has 1,5, and 3 +print(oursubset.issubset(oursuperset)) +# should print False since oursubset doesn't have 7 or 9 +print(oursubset.issuperset(oursuperset)) + +# set methods +# includes .intersection , .union , .difference , .symettricdifference +set1 = {1, 2, 3, 4, 5} +set2 = {3, 4, 5, 6, 7} + +# will print 3,4,5 which is the common items (the 'intersection') +print(set1.intersection(set2)) +# will print 1,2 which is the different items in set 1 (the 'difference') +print(set1.difference(set2)) +# will print 6,7 which is the difference items in set 2 (the 'difference') +print(set2.difference(set1)) +# will print 1,2,6,7 since those are the different items in both +print(set1.symmetric_difference(set2)) +# will print 1,2,3,4,5,6,7 since those are the unique items +print(set1.union(set2)) + +# set methods (cont.) +# also includes .add , .discard , .remove , .pop , .update +# note: .discard and .remove are similar; check the comments +a_set = set() +a_set.add(2) # can only add 1 element +a_set.update([8, 9, 7]) # is a union between a_set and {8,9,7} +a_set.remove(8) # removes 8; if 8 isn't there, raises a key error +a_set.discard(9) # removes 9; if 9 isn't there, do nothing (no error) +a_set.pop() # removes the first element; in this case 2 diff --git a/3_advanced/chapter17/examples/tuples.py b/3_advanced/chapter17/examples/tuples.py new file mode 100644 index 00000000..cc41a975 --- /dev/null +++ b/3_advanced/chapter17/examples/tuples.py @@ -0,0 +1,33 @@ +# initializing a tuple +mytuple = () # is an empty tuple +mytuple = tuple() # also an empty tuple +myothtuple = (1,) # tuples with just 1 item need a comma at the end +moretuple = (4, 6, 3, {5, 6}, [7]) # valid; tuples accept all types + + +# these all work and will run with no error +tup = tuple([2, 4, 6, 8]) # creates a tuple out of the list +tup = tuple("tuple") # creates a tuple out of the string +tup = tuple({"a": "A", "b": "B"}) # creates a tuple out of the dict +# note: it creates the tuple out of the dict's keys, not values +tup = tuple({2, 4, 6, 8}) # creates a tuple out of the set +tup = 2, 4, 6, 8 # you don't even need parentheses +# however, you need at least one element in the tuple to do this + + +# modifying a tuple +# you can't modify a tuple's main elements +anothtuple = (4, 56, 7, [4, 6, 8]) +# what won't work: anothtuple[2] = 3 +# will produce an error +# what will work: +anothtuple[3][0] = 6 +# this works since you you're modifying the list's elements, not the tuple's + + +# tuple methods +# includes .index and .count +lasttupexample = (4, 6, 8, 10, 4, 2) +print(lasttupexample.count(4)) # prints 2 since there are two 4's +print(lasttupexample.index(4)) +# ^works just like list indexes; prints 0 which = the first occurence diff --git a/3_advanced/chapter17/practice/challenge (hard math + python)/disjoint_set_union.py b/3_advanced/chapter17/practice/challenge (hard math + python)/disjoint_set_union.py new file mode 100644 index 00000000..ede8aff9 --- /dev/null +++ b/3_advanced/chapter17/practice/challenge (hard math + python)/disjoint_set_union.py @@ -0,0 +1,22 @@ +# Given n number of cities (essentially a list of cities numbered +# from 0 to n-1), and a list of “bridges” with some arbitrary cost +# (how expensives that bridge is to build) which can connect two +# cities (you can move both directions along it), finda set of bridges +# such that when built you can reach any city from any starting city +# and that the combined cost of building the bridges is the cheapest +# possible. (this problem is called the minimum spanning tree) It +# should return the minimum total cost of building such a set of +# bridges (don’t return which those bridges are) + + +# numberOfCities: number of cities that needs to be connected +# possibleBridges: a vector containing a vectors each of size 3 +# which denotes [cityA, cityB, cost] + + +def findMinimumCost(numberOfCities, possibleBridges): + # put your code here; remove pass + pass + + +edges = [[0, 1, 1], [0, 2, 1], [1, 2, 2]] diff --git a/3_advanced/chapter17/practice/challenge (hard math + python)/linear_independence_checker.py b/3_advanced/chapter17/practice/challenge (hard math + python)/linear_independence_checker.py new file mode 100644 index 00000000..9ae4cbee --- /dev/null +++ b/3_advanced/chapter17/practice/challenge (hard math + python)/linear_independence_checker.py @@ -0,0 +1,31 @@ +# In linear algebra, a vector (list) of n vectors (lists) each +# containing n integers are considered linearly independent if we +# solve the following equation +# a * x + a * x + a * x + a * x = 0 +# 1 1 2 2 3 3 n n +# for where they can be any real constant, and we find that all of +# them equal to 0 being the only possible solution for this system +# of equations (this is called the trivial solution). Write a method +# which takes a vector of n vectors each of size n and determine if +# they are linearly independent. Return true if linearly independent, +# and false otherwise. +# (for this question, assume n is less than equal to 4 and greater than 1) + +# Note: Another way we can determine if n vectors is linearly independent is if +# you find that the matrix formed by concatenating the vectors has a nonzero +# determinant. This might be somewhat easier +# (search up calculating “determinant using cofactor expansion”). + + +def calculateDeterminant(matrix): + # put your code here; remove "pass" + pass + + +def testLinearIndependence(mat): + return calculateDeterminant(mat) != 0 + + +# mat is an example of an acceptable list of 3 (n) lists each containing +# 3 (n) integers; hint: if you use mat, it should give you True +mat = [[1, 1, 4], [0, 0, 5], [0, 7, 8]] diff --git a/3_advanced/chapter17/practice/challenge (hard math + python)/powerset_generator.py b/3_advanced/chapter17/practice/challenge (hard math + python)/powerset_generator.py new file mode 100644 index 00000000..503d9dba --- /dev/null +++ b/3_advanced/chapter17/practice/challenge (hard math + python)/powerset_generator.py @@ -0,0 +1,10 @@ +# Given a set of distinct integers (between 1 and 15 inclusive) +# (ex: {3,6,2,1}), return an array of all possible subsets that can be +# formed using the elements in the set. This also includes the empty +# set and the entire set itself. +# The set of all such subsets is referred to as the powerset. + + +def generatePowerset(elements): + # put your code here; remove "pass" + pass diff --git a/3_advanced/chapter17/practice/compute_similarity.py b/3_advanced/chapter17/practice/compute_similarity.py new file mode 100644 index 00000000..197eefa2 --- /dev/null +++ b/3_advanced/chapter17/practice/compute_similarity.py @@ -0,0 +1,11 @@ +# Given two sets of integers A and B (each element in these sets are +# between 1 and 1000 inclusive), find the similarity of the two sets +# (the sets are guaranteed to be nonempty). The similarity is a number +# which is computed by dividing the size of the intersection of the +# two sets by their union size. +# Note: the intersection is the # of elements that both sets have in common. + + +def compute_similarity(set1, set2): + # put your code here; remove "pass" + pass diff --git a/3_advanced/chapter17/practice/countable_set.py b/3_advanced/chapter17/practice/countable_set.py new file mode 100644 index 00000000..5bf37d82 --- /dev/null +++ b/3_advanced/chapter17/practice/countable_set.py @@ -0,0 +1,27 @@ +# Create a class called CountableSet which stores the number of times each +# element has been inserted into the CountableSet object. +# (Basically, store it like element: #of times inserted into Countable Set) +# Implement the following class: + + +class CountableSet: + def __init__( + self, objs + ): # objs is the initial list of objects to be inserted + pass + + # insert x into the set one time, increment the count by one + # returns True if map didn't already contain the key + # x is the integer to be inserted + def insert(self, x): + pass + + # decrement the count by one, returns True if map contains key + # x is integer to be deleted + def delete(self, x): + pass + + # should return the number of times x has been inserted into the set + # x is the integer being queried + def get(self, x): + pass diff --git a/3_advanced/chapter17/practice/duplicate_detector.py b/3_advanced/chapter17/practice/duplicate_detector.py new file mode 100644 index 00000000..fbd2f9f7 --- /dev/null +++ b/3_advanced/chapter17/practice/duplicate_detector.py @@ -0,0 +1,8 @@ +# Create a program that finds whether a list contains duplicates +# should return True or False +# use sets in your code + + +def dup_detector(item): + # put your code here and remove "pass" + pass diff --git a/3_advanced/chapter17/practice/ice_cream_shop.py b/3_advanced/chapter17/practice/ice_cream_shop.py new file mode 100644 index 00000000..cd813e68 --- /dev/null +++ b/3_advanced/chapter17/practice/ice_cream_shop.py @@ -0,0 +1,19 @@ +""" +An ice cream shop keeps all its available flavours +in a set. Every month, it gets a list of all the +flavours that are no longer available. Return +a new set containing the available flavours this +month after all the no-longer-available flavours +are removed. It is possible to solve this problem +using either discard or remove. +""" + + +def remove_flavours(avail_flavs, no_longer_flavs): + pass + # Remove pass and write your code in here + + +avail_flavs = {"Strawberry", "Blueberry", "Vanilla"} +remove_flavours(avail_flavs, ["Strawberry", "Vanilla"]) +print(avail_flavs) diff --git a/3_advanced/chapter17/practice/magic_tuple_number.py b/3_advanced/chapter17/practice/magic_tuple_number.py new file mode 100644 index 00000000..f4faa35e --- /dev/null +++ b/3_advanced/chapter17/practice/magic_tuple_number.py @@ -0,0 +1,17 @@ +""" +A magic tuple number for a given element is the +index of the given element’s first occurrence in +the tuple TIMES the number of occurrences of +the given element in the tuple. Given an element +and a tuple, return the magic tuple number. If +the element does not exist in the tuple, return -1. +""" + + +def magic_tuple_number(given_tup, given_elem): + pass + # Remove pass and write your code in here + + +print(magic_tuple_number((1, 3, "Two", 3), 3)) # prints 2 +print(magic_tuple_number((1, 3, "Bob"), "Cat")) # prints -1 diff --git a/3_advanced/chapter17/practice/min_superset.py b/3_advanced/chapter17/practice/min_superset.py new file mode 100644 index 00000000..1a7be908 --- /dev/null +++ b/3_advanced/chapter17/practice/min_superset.py @@ -0,0 +1,11 @@ +# Given 3 sets of distinct integers, return the size of the superset +# of minimum size which is the superset of all the given sets. +# Implement the following method: + + +def findMinSupersetLength(sets): + # code here; remove "pass" + pass + + +sets = [{1, 2, 3}, {2, 3, 5}, {1, 3, 6}] diff --git a/3_advanced/chapter17/practice/modify_tuple.py b/3_advanced/chapter17/practice/modify_tuple.py new file mode 100644 index 00000000..b758bb83 --- /dev/null +++ b/3_advanced/chapter17/practice/modify_tuple.py @@ -0,0 +1,14 @@ +# Given a tuple whose first two elements are +# strings and the third element is a dictionary. +# Add the given key and value to the dictionary +# in the tuple. + + +def modify_tuple(given_tuple, given_key, given_val): + pass + # Remove pass and write your code in here + + +given_tuple = ("Ken", "Kaneki", {1: "Apple"}) +modify_tuple(given_tuple, 2, "Orange") +print(given_tuple) # Dictionary should now be updated diff --git a/3_advanced/chapter17/practice/odd_set_day.py b/3_advanced/chapter17/practice/odd_set_day.py new file mode 100644 index 00000000..8a09dcda --- /dev/null +++ b/3_advanced/chapter17/practice/odd_set_day.py @@ -0,0 +1,18 @@ +""" +Given a set, remove all the even numbers from +it, and for each even number removed, add +"Removed [insert the even number you removed]". +Example: {1,54, 2, 5} becomes {"Removed 54", 1, +5, "Removed 2"}. It is possible to solve this +problem using either discard or remove. +""" + + +def odd_set_day(given_set): + pass + # Remove pass and write your code in here + + +given_set = {1, 2, 4, 5} +odd_set_day(given_set) +print(given_set) diff --git a/3_advanced/chapter17/practice/only_fav_movies.py b/3_advanced/chapter17/practice/only_fav_movies.py new file mode 100644 index 00000000..4c9215d9 --- /dev/null +++ b/3_advanced/chapter17/practice/only_fav_movies.py @@ -0,0 +1,23 @@ +""" +Charles is going to the movie today and wants +to figure out if all the movies played today +are his favorite movies. Given a set containing +the movies that are going to be played today +and a set containing all his favorite movies, +return True if all the movies played today are +his favorite. Return False otherwise. +""" + + +def only_fav_movies(movies_today, favorite_movies): + pass + # Remove pass and write your code in here + + +favorite_movies = {"Home Alone", "Star Wars", "Pokemon"} +print( + only_fav_movies({"Home Alone", "Star Wars"}, favorite_movies) +) # Prints True +print( + only_fav_movies({"Spider Man", "Home Alone"}, favorite_movies) +) # Prints False diff --git a/3_advanced/chapter17/practice/open_mind.py b/3_advanced/chapter17/practice/open_mind.py new file mode 100644 index 00000000..cc602224 --- /dev/null +++ b/3_advanced/chapter17/practice/open_mind.py @@ -0,0 +1,40 @@ +""" +Two brothers come together to watch TV everyday. +On weekdays(monday through thursday), they are +not open minded and only watch what they like to +watch themselves. Due to this, it is possible +for nothing to be watched. On weekends(friday +through sunday), they are open minded and would +watch what they themselves like to watch and what +the others like to watch even if they themselves +don’t like to watch that specific TV show. +Assume, all the TV shows the brothers like will +be played everyday. Given a day(1-4 represents +weekday and 5-7 represents weekend) and two +sets(what the brothers each like to watch), +return the set of possible TV shows the brothers +would both watch on that day. +""" + + +def open_mind(first_bro_set, second_bro_set, day): + pass + # Remove pass and write your code in here + + +first_bro_set = { + "pokemon", + "regular show", + "ben 10", + "adventure time", + "mega man", +} +second_bro_set = { + "ben 10", + "powerpuff girls", + "curious george", + "arthur", + "mega man", +} +print(open_mind(first_bro_set, second_bro_set, 3)) +print(open_mind(first_bro_set, second_bro_set, 7)) diff --git a/3_advanced/chapter17/practice/set_creator.py b/3_advanced/chapter17/practice/set_creator.py new file mode 100644 index 00000000..3a5e35dd --- /dev/null +++ b/3_advanced/chapter17/practice/set_creator.py @@ -0,0 +1,12 @@ +# Create an empty set and print the type of it. Create a +# set from a given dictionary(do set(given_dict)) and print it. +# Note: The set created from the given dictionary contains +# only the keys of the dictionary. + + +def set_creator(given_dict): + pass + # Remove pass and write your code in here + + +set_creator({1: "Wall Street", 2: "Main Street", "Tower": 3}) diff --git a/3_advanced/chapter17/practice/tuple_bears.py b/3_advanced/chapter17/practice/tuple_bears.py new file mode 100644 index 00000000..7c6d4a8b --- /dev/null +++ b/3_advanced/chapter17/practice/tuple_bears.py @@ -0,0 +1,16 @@ +# Fred had lost his teddy bear, so his parents are going to the store +# to buy a replacement for him. You are given a list of length 2 +# (2 elements) tuples, where each tuple represents a teddy bear. where +# the first element contains a number showing how similar that that bear is +# to Fred's original teddy bear(the smaller, the better), and the second +# element is a string of the teddy bear's name. +# Find the teddy bear closest to the one Fred lost, and print its name +# (don’t worry about tuples w/ same #) + + +def tuple_bears(item): + # put your code here and remove pass + pass + + +teddy_bears = [(5, "Freddy"), (3, "Runaway"), (7, "Killer"), (2, "Luscious")] diff --git a/3_advanced/chapter17/practice/tuple_creator.py b/3_advanced/chapter17/practice/tuple_creator.py new file mode 100644 index 00000000..05792021 --- /dev/null +++ b/3_advanced/chapter17/practice/tuple_creator.py @@ -0,0 +1,13 @@ +# Create an empty tuple and print the type of it. +# Create a tuple from any one element and print the type of it. +# Create a tuple from a given dictionary and print it. +# Note: The tuple created from a dictionary will only contain +# the keys of the dictionary + + +def tuple_creator(given_dict): + pass + # Remove pass and write your code in here + + +tuple_creator({1: "Wall Street", 2: "Main Street", "Tower": 3}) diff --git a/3_advanced/chapter17/solutions/challenge (hard math + python)/disjoint_set_union b/3_advanced/chapter17/solutions/challenge (hard math + python)/disjoint_set_union new file mode 100644 index 00000000..1ae9a1c8 --- /dev/null +++ b/3_advanced/chapter17/solutions/challenge (hard math + python)/disjoint_set_union @@ -0,0 +1,67 @@ +# Given n number of cities (essentially a list of cities numbered +# from 0 to n-1), and a list of “bridges” with some arbitrary cost +# (how expensives that bridge is to build) which can connect two +# cities (you can move both directions along it), finda set of bridges +# such that when built you can reach any city from any starting city +# and that the combined cost of building the bridges is the cheapest +# possible. (this problem is called the minimum spanning tree) It +# should return the minimum total cost of building such a set of +# bridges (don’t return which those bridges are) + + +# numberOfCities: number of cities that needs to be connected +# possibleBridges: a vector containing a vectors each of size 3 +# which denotes [cityA, cityB, cost] + +class DSU: + def __init__(self, size): + self.parents = [i for i in range(size)] + + def parent(self, n): + if (not(self.parents[n] == n)): + self.parents[n] = self.parent(self.parents[n]) + return self.parents[n] + + def isMerged(self, n1, n2): + return self.parent(n1) == self.parent(n2) + + def merge(self, n1, n2): + self.parents[self.parent(n1)] = self.parent(n2) + +# numberOfCities: number of cities that needs to be connected +# possibleBridges: a vector containing a vectors each of size 3 which denotes [cityA, cityB, cost] +def findMinimumCost(numberOfCities, possibleBridges): + size = numberOfCities + edges = possibleBridges + table = {} + weights = [] + dsu = DSU(size) + for edge in edges: + if edge[2] in table: + table[edge[2]].append([edge[0], edge[1]]) + else: + table[edge[2]] = [[edge[0], edge[1]]] + weights.append(edge[2]) + weights.sort() + total = 0 + merged = 0 + for weight in weights: + for edge in table[weight]: + n1 = edge[0] + n2 = edge[1] + if dsu.isMerged(n1, n2): + continue + dsu.merge(n1, n2) + total += weight + merged += 1 + if merged == size - 1: + return total + return total + +edges = [ + [0, 1, 1], + [0, 2, 1], + [1, 2, 2] +] + +print(findMinimumCost(3, edges)) diff --git a/3_advanced/chapter17/solutions/challenge (hard math + python)/linear_independence_checker.py b/3_advanced/chapter17/solutions/challenge (hard math + python)/linear_independence_checker.py new file mode 100644 index 00000000..485ae7b1 --- /dev/null +++ b/3_advanced/chapter17/solutions/challenge (hard math + python)/linear_independence_checker.py @@ -0,0 +1,50 @@ +# In linear algebra, a vector (list) of n vectors (lists) each +# containing n integers are considered linearly independent if we +# solve the following equation +# a * x + a * x + a * x + a * x = 0 +# 1 1 2 2 3 3 n n +# for where they can be any real constant, and we find that all of +# them equal to 0 being the only possible solution for this system +# of equations (this is called the trivial solution). Write a method +# which takes a vector of n vectors each of size n and determine if +# they are linearly independent. Return true if linearly independent, +# and false otherwise. +# (for this question, assume n is less than equal to 4 and greater than 1) + +# Note: Another way we can determine if n vectors is linearly independent is if +# you find that the matrix formed by concatenating the vectors has a nonzero +# determinant. This might be somewhat easier +# (search up calculating “determinant using cofactor expansion”). + + +def calculateDeterminant(matrix): + length = len(matrix) + if length == 2: + return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1] + cofactorLength = length - 1 + total = 0 + negativeFactor = 1 + for i in range(length): + matrixMinor = [ + [0 for k in range(cofactorLength)] for j in range(cofactorLength) + ] + for j in range(cofactorLength): + for k in range(cofactorLength): + if k >= i: + matrixMinor[j][k] = matrix[j + 1][k + 1] + else: + matrixMinor[j][k] = matrix[j + 1][k] + total = total + negativeFactor * matrix[0][i] * calculateDeterminant( + matrixMinor + ) + negativeFactor *= -1 + return total + + +def testLinearIndependence(mat): + return calculateDeterminant(mat) != 0 + + +mat = [[1, 1, 4], [0, 0, 5], [0, 7, 8]] + +print(testLinearIndependence(mat)) # prints True (determinant is equal to -35) diff --git a/3_advanced/chapter17/solutions/challenge (hard math + python)/powerset_generator b/3_advanced/chapter17/solutions/challenge (hard math + python)/powerset_generator new file mode 100644 index 00000000..f3ddf09c --- /dev/null +++ b/3_advanced/chapter17/solutions/challenge (hard math + python)/powerset_generator @@ -0,0 +1,21 @@ +# Given a set of distinct integers (between 1 and 15 inclusive) +# (ex: {3,6,2,1}), return an array of all possible subsets that can be +# formed using the elements in the set. This also includes the empty +# set and the entire set itself. +# The set of all such subsets is referred to as the powerset. + + +def generatePowerset(elements): + setSize = len(elements) + vec = list(elements) + limit = 1 << setSize # << is same as 1 * 2**setSize + result = [None for i in range(limit)] + for i in range(limit): + currentSet = set() + for j in range(setSize): + if ((1 << j) & i) > 0: # bitwise operations + currentSet.add(vec[j]) + result[i] = currentSet + return result + +print(generatePowerset({1, 2, 3})) diff --git a/3_advanced/chapter17/solutions/compute_similarity.py b/3_advanced/chapter17/solutions/compute_similarity.py new file mode 100644 index 00000000..4a1e662a --- /dev/null +++ b/3_advanced/chapter17/solutions/compute_similarity.py @@ -0,0 +1,18 @@ +# Given two sets of integers A and B (each element in these sets are +# between 1 and 1000 inclusive), find the similarity of the two sets +# (the sets are guaranteed to be nonempty). The similarity is a number +# which is computed by dividing the size of the intersection of the +# two sets by their union size. +# Note: the intersection is the # of elements that both sets have in common. + + +def computeSimilarity(set1, set2): + intersectionSize = 0 + for elem in set1: + if elem in set2: + intersectionSize += 1 + unionSize = len(set1) + len(set2) - intersectionSize + return intersectionSize / float(unionSize) + + +print(computeSimilarity({1, 2}, {1, 3})) diff --git a/3_advanced/chapter17/solutions/countable_set.py b/3_advanced/chapter17/solutions/countable_set.py new file mode 100644 index 00000000..c6944ae2 --- /dev/null +++ b/3_advanced/chapter17/solutions/countable_set.py @@ -0,0 +1,52 @@ +# Create a class called CountableSet which stores the number of times each +# element has been inserted into the CountableSet object. +# (Basically, store it like element: #of times inserted into Countable Set) +# Implement the following class: + + +class CountableSet: + def __init__( + self, objs + ): # objs is the initial list of objects to be inserted + self.elems = {} + for obj in objs: + self.insert(obj) + + # insert x into the set one time, increment the count by one + # returns True if map didn't already contain the key + # x is the integer to be inserted + def insert(self, x): + if x in self.elems.keys(): + self.elems[x] += 1 + return False + else: + self.elems[x] = 1 + return True + + # decrement the count by one, returns True if map contains key + # x is integer to be deleted + def delete(self, x): + if x in self.elems.keys(): + self.elems[x] -= 1 + if self.elems[x] == 0: + self.elems.pop(x) + return True + return False + + # returns the number of times x has been inserted into the set + # x is the integer being queried + def get(self, x): + if x in self.elems.keys(): + return self.elems[x] + return 0 + + +x = CountableSet([1, 2, 3, 1]) +x.insert(3) +print(x.elems) +x.insert(2) +print(x.elems) +x.delete(1) +print(x.elems) +x.delete(1) +print(x.elems) diff --git a/3_advanced/chapter17/solutions/duplicate_detector.py b/3_advanced/chapter17/solutions/duplicate_detector.py new file mode 100644 index 00000000..adf9a8a5 --- /dev/null +++ b/3_advanced/chapter17/solutions/duplicate_detector.py @@ -0,0 +1,14 @@ +# Create a program that finds whether a list contains duplicates +# should return True or False +# use sets in your code + + +def dup_detector(item): + theset = set(item) + if len(theset) < len(item): + return True + else: + return False + + +print(dup_detector([5, 4, 3, 2, 2])) # should print True diff --git a/3_advanced/chapter17/solutions/ice_cream_shop.py b/3_advanced/chapter17/solutions/ice_cream_shop.py new file mode 100644 index 00000000..36255fb4 --- /dev/null +++ b/3_advanced/chapter17/solutions/ice_cream_shop.py @@ -0,0 +1,19 @@ +""" +An ice cream shop keeps all its available flavours +in a set. Every month, it gets a list of all the +flavours that are no longer available. Return +a new set containing the available flavours this +month after all the no-longer-available flavours +are removed. It is possible to solve this problem +using either discard or remove. +""" + + +def remove_flavours(avail_flavs, no_longer_flavs): + for flav in no_longer_flavs: + avail_flavs.remove(flav) + + +avail_flavs = {"Strawberry", "Blueberry", "Vanilla"} +remove_flavours(avail_flavs, ["Strawberry", "Vanilla"]) +print(avail_flavs) diff --git a/3_advanced/chapter17/solutions/magic_tuple_number.py b/3_advanced/chapter17/solutions/magic_tuple_number.py new file mode 100644 index 00000000..048028b2 --- /dev/null +++ b/3_advanced/chapter17/solutions/magic_tuple_number.py @@ -0,0 +1,19 @@ +""" +A magic tuple number for a given element is the +index of the given element’s first occurrence in +the tuple TIMES the number of occurrences of +the given element in the tuple. Given an element +and a tuple, return the magic tuple number. If +the element does not exist in the tuple, return -1. +""" + + +def magic_tuple_number(given_tup, given_elem): + elem_count = given_tup.count(given_elem) + if elem_count != 0: + return given_tup.index(given_elem) * elem_count + return -1 + + +print(magic_tuple_number((1, 3, "Two", 3), 3)) # prints 2 +print(magic_tuple_number((1, 3, "Bob"), "Cat")) # prints -1 diff --git a/3_advanced/chapter17/solutions/min_superset.py b/3_advanced/chapter17/solutions/min_superset.py new file mode 100644 index 00000000..e7b55ff7 --- /dev/null +++ b/3_advanced/chapter17/solutions/min_superset.py @@ -0,0 +1,31 @@ +# Given 3 sets of distinct integers, return the size of the superset +# of minimum size which is the superset of all the given sets. +# Implement the following method: + + +# superset calcuated using Principle of Inclusion and Exclusion +# sets: a vector containing 3 sets +def findMinSupersetLength(sets): + total = 0 + for i in range(3): + total += len(sets[i]) + for i in range(3): + prevIndex = ((i - 1) + 3) % 3 + nextIndex = (i + 1) % 3 + total -= len(sets[prevIndex].intersection(sets[nextIndex])) + total += len(sets[0].intersection(sets[1]).intersection(sets[2])) + return total + + +sets = [{1, 2, 3}, {2, 3, 5}, {1, 3, 6}] + +print(findMinSupersetLength(sets)) + + +""" +Alternate, more understandable solution: +def findMinSupersetLength(sets): + a = sets[0] + a = a.union(sets[1]).union(set[2]) + return len(a) +""" diff --git a/3_advanced/chapter17/solutions/modify_tuple.py b/3_advanced/chapter17/solutions/modify_tuple.py new file mode 100644 index 00000000..46027594 --- /dev/null +++ b/3_advanced/chapter17/solutions/modify_tuple.py @@ -0,0 +1,13 @@ +# Given a tuple whose first two elements are +# strings and the third element is a dictionary. +# Add the given key and value to the dictionary +# in the tuple. + + +def modify_tuple(given_tuple, given_key, given_val): + given_tuple[2][given_key] = given_val + + +given_tuple = ("Ken", "Kaneki", {1: "Apple"}) +modify_tuple(given_tuple, 2, "Orange") +print(given_tuple) # Dictionary should now be updated diff --git a/3_advanced/chapter17/solutions/odd_set_day.py b/3_advanced/chapter17/solutions/odd_set_day.py new file mode 100644 index 00000000..431dd929 --- /dev/null +++ b/3_advanced/chapter17/solutions/odd_set_day.py @@ -0,0 +1,23 @@ +""" +Given a set, remove all the even numbers from +it, and for each even number removed, add +"Removed [insert the even number you removed]". +Example: {1,54, 2, 5} becomes {"Removed 54", 1, +5, "Removed 2"}. It is possible to solve this +problem using either discard or remove. +""" + + +def odd_set_day(given_set): + add_remove = [] + for elem in given_set: + if elem % 2 == 0: + add_remove.append(elem) + for remove in add_remove: + given_set.remove(remove) + given_set.add("Removed " + str(remove)) + + +given_set = {1, 2, 4, 5} +odd_set_day(given_set) +print(given_set) diff --git a/3_advanced/chapter17/solutions/only_fav_movies.py b/3_advanced/chapter17/solutions/only_fav_movies.py new file mode 100644 index 00000000..be33cc6e --- /dev/null +++ b/3_advanced/chapter17/solutions/only_fav_movies.py @@ -0,0 +1,29 @@ +""" +Charles is going to the movie today and wants +to figure out if all the movies played today +are his favorite movies. Given a set containing +the movies that are going to be played today +and a set containing all his favorite movies, +return True if all the movies played today are +his favorite. Return False otherwise. +""" + + +def only_fav_movies(movies_today, favorite_movies): + return movies_today.issubset(favorite_movies) + + +favorite_movies = {"Home Alone", "Star Wars", "Pokemon"} +print( + only_fav_movies({"Home Alone", "Star Wars"}, favorite_movies) +) # Prints True +print( + only_fav_movies({"Spider Man", "Home Alone"}, favorite_movies) +) # Prints False + + +# An Alternative Solution that is equally efficient is to +# check favorite_movies.issuperset(movies_today) + +# Another Alternative Solution that is less efficient is to +# check if every element of movies_today is in favorite_movies. diff --git a/3_advanced/chapter17/solutions/open_mind.py b/3_advanced/chapter17/solutions/open_mind.py new file mode 100644 index 00000000..cccdfd6e --- /dev/null +++ b/3_advanced/chapter17/solutions/open_mind.py @@ -0,0 +1,42 @@ +""" +Two brothers come together to watch TV everyday. +On weekdays(monday through thursday), they are +not open minded and only watch what they like to +watch themselves. Due to this, it is possible +for nothing to be watched. On weekends(friday +through sunday), they are open minded and would +watch what they themselves like to watch and what +the others like to watch even if they themselves +don’t like to watch that specific TV show. +Assume, all the TV shows the brothers like will +be played everyday. Given a day(1-4 represents +weekday and 5-7 represents weekend) and two +sets(what the brothers each like to watch), +return the set of possible TV shows the brothers +would both watch on that day. +""" + + +def open_mind(first_bro_set, second_bro_set, day): + if day <= 4: + return first_bro_set.intersection(second_bro_set) + else: + return first_bro_set.union(second_bro_set) + + +first_bro_set = { + "pokemon", + "regular show", + "ben 10", + "adventure time", + "mega man", +} +second_bro_set = { + "ben 10", + "powerpuff girls", + "curious george", + "arthur", + "mega man", +} +print(open_mind(first_bro_set, second_bro_set, 3)) +print(open_mind(first_bro_set, second_bro_set, 7)) diff --git a/3_advanced/chapter17/solutions/set_creator.py b/3_advanced/chapter17/solutions/set_creator.py new file mode 100644 index 00000000..9d2493d3 --- /dev/null +++ b/3_advanced/chapter17/solutions/set_creator.py @@ -0,0 +1,14 @@ +# Create an empty set and print the type of it. Create a +# set from a given dictionary(do set(given_dict)) and print it. +# Note: The set created from the given dictionary contains +# only the keys of the dictionary. + + +def set_creator(given_dict): + empty_set = set() + print(type(empty_set)) + dict_set = set(given_dict) + print(dict_set) + + +set_creator({1: "Wall Street", 2: "Main Street", "Tower": 3}) diff --git a/3_advanced/chapter17/solutions/tuple_bears.py b/3_advanced/chapter17/solutions/tuple_bears.py new file mode 100644 index 00000000..9154cad0 --- /dev/null +++ b/3_advanced/chapter17/solutions/tuple_bears.py @@ -0,0 +1,23 @@ +# Fred had lost his teddy bear, so his parents are going to the store +# to buy a replacement for him. You are given a list of length 2 +# (2 elements) tuples, where each tuple represents a teddy bear. where +# the first element contains a number showing how similar that that bear is +# to Fred's original teddy bear(the smaller, the better), and the second +# element is a string of the teddy bear's name. +# Find the teddy bear closest to the one Fred lost, and print its name +# (don’t worry about tuples w/ same #) + + +def tuple_bears(item): + ourmin = [item[0][0], item[0][1]] + for i in range(len(item)): + if ourmin[0] > item[i][0]: + ourmin[0] = item[i][0] + ourmin[1] = item[i][1] + i = 0 + return ourmin[1] + + +tuplelist = [(5, "Freddy"), (3, "Runaway"), (7, "Killer"), (2, "Luscious")] + +print(tuple_bears(tuplelist)) diff --git a/3_advanced/chapter17/solutions/tuple_creator.py b/3_advanced/chapter17/solutions/tuple_creator.py new file mode 100644 index 00000000..b702ef21 --- /dev/null +++ b/3_advanced/chapter17/solutions/tuple_creator.py @@ -0,0 +1,17 @@ +# Create an empty tuple and print the type of it. +# Create a tuple from any one element and print the type of it. +# Create a tuple from a given dictionary and print it. +# Note: The tuple created from a dictionary will only contain +# the keys of the dictionary + + +def tuple_creator(given_dict): + empty_tuple = () + print(type(empty_tuple)) + one_element_tuple = ("Blueberry",) + print(type(one_element_tuple)) + dict_tuple = tuple(given_dict) + print(dict_tuple) + + +tuple_creator({1: "Wall Street", 2: "Main Street", "Tower": 3}) diff --git a/3_advanced/chapter18/examples/Number Of a Factor.py b/3_advanced/chapter18/examples/Number Of a Factor.py new file mode 100644 index 00000000..65182bbe --- /dev/null +++ b/3_advanced/chapter18/examples/Number Of a Factor.py @@ -0,0 +1,23 @@ +# Code to figure out how many of a factor a number has + + +def number_factor(number, factor, factor_counter=0): + """ + Parameters: + 1)number is the number in which we are finding the number of + factors of. EX: 24 + 2)factor is the factor in which we are finding the number of + in the parameter number. EX: 2 + + Output: The number of times the parameter number can be divisible + by the parameter factor. This number is also the parameter + factor_counter right before it is returned. EX: 3 + """ + + if number % factor != 0: # Base Case + return factor_counter + else: # Recursive Case + return number_factor(number / factor, factor, factor_counter + 1) + + +print(number_factor(24, 2)) diff --git a/3_advanced/chapter18/examples/binary_search.py b/3_advanced/chapter18/examples/binary_search.py new file mode 100644 index 00000000..c14336b5 --- /dev/null +++ b/3_advanced/chapter18/examples/binary_search.py @@ -0,0 +1,31 @@ +# Code for binary search + + +def binary_search(arr, low, high, key): + """ + Parameters: + 1) arr is the sorted array in which we will be finding the element + 2) low is the lower bound of the interval in which we will + be finding the element index + 3) high is the upper bound of the interval in which we will + be finding the element index + 4) key is the element we are trying to find the index of + + Output: the index of the element key in the array arr. + If the element x does not exist in array arr, -1 will + be returned. + """ + + if high >= low: + mid = (high + low) // 2 + if arr[mid] == key: # Base Case 1 + return mid + elif arr[mid] < key: # Recursive Case 1 + return binary_search(arr, mid + 1, high, key) + else: # Recursive Case 2 (arr[mid] > x) + return binary_search(arr, low, mid - 1, key) + else: # Base Case 2: element not found + return -1 + + +print(binary_search([1, 24, 28, 30, 40, 52], 0, 5, 28)) diff --git a/3_advanced/chapter18/examples/fibonacci.py b/3_advanced/chapter18/examples/fibonacci.py new file mode 100644 index 00000000..d881582b --- /dev/null +++ b/3_advanced/chapter18/examples/fibonacci.py @@ -0,0 +1,79 @@ +# Fibonacci +# The Fibonacci sequence starts with 0 and 1. +# The next number in the sequence is the sum of the previous 2 numbers. +# Thus, the first 5 Fibonacci numbers are: 0, 1, 1, 2, 3. + + +def recursive_fib(n): + """ + Returns the nth number in the Fibonacci sequence recursively + + Args: + n (int): the position of the number in the Fibonacci sequence you want + + Returns: + int: the nth number in the Fibonacci sequence + For example, recursive_fib(5) will return 3 + """ + if n <= 0: # Base Case 1: out of bounds + return None + elif n == 1: # Base Case 2 + return 0 + elif n == 2: # Base Case 3 + return 1 + else: # Recursive Case + return recursive_fib(n - 1) + recursive_fib(n - 2) + + +def iterative_fib(n): + """ + Returns the nth number in the Fibonacci sequence iteratively + + Args: + n (int): the position of the number in the Fibonacci sequence you want + + Returns: + int: the nth number in the Fibonacci sequence + For example, iterative_fib(5) will return 3 + """ + if n <= 0: + return None # base case; out of bounds + + current = 0 + next_term = 1 + + for i in range(n - 1): # this is equivalent to for i in range(1, n) + current, next_term = next_term, current + next_term + # this is just a slightly rewritten fib sequence; + # instead of looking at the past 2 cases, it looks at the + # current and next terms to determine the next next term + + return current # will be 0 if n is 1, 1 if n is 2, etc... + + +def fib_sequence(n): + """ + Returns the fibonacci sequence as a list up to the nth fibonacci number + + Args: + n (int): the position of the number in the Fibonacci + sequence you want to go up to + + Returns: + list: the nth number in the Fibonacci sequence + For example, fib_sequence(5) will return [0, 1, 1, 2, 3] + + Adapted from: + https://medium.com/@danfcorreia/fibonacci-iterative-28b042a3eec + """ + sequence = [0, 1] + + for i in range(2, n): + sequence.append(sequence[i - 2] + sequence[i - 1]) + + return sequence + + +print("Recursive fib:", recursive_fib(5)) +print("Iterative fib:", iterative_fib(5)) +print("Fib sequence:", fib_sequence(5)) diff --git a/3_advanced/chapter18/examples/infinite_recursion.py b/3_advanced/chapter18/examples/infinite_recursion.py new file mode 100644 index 00000000..067371ba --- /dev/null +++ b/3_advanced/chapter18/examples/infinite_recursion.py @@ -0,0 +1,24 @@ +# notice how there is no base +# case, meaning no way out + + +def recurse(i): + i = i + 1 + print(i) + recurse(i) + + +recurse(0) # this will result in the following message: +# RecursionError: maximum recursion depth exceeded while +# calling a Python object + +# RecursionError happens when you exceed your maximum +# recursion limit. By default, it is set to 1000 +# you can check the maximum recursion depth by doing +# import sys +# sys.getrecursionlimit() +# you can change the maximum recursion depth by doing +# import sys +# sys.setrecursionlimit() +# However, this can be dangerous, so only do it if you +# know what you're doing. diff --git a/3_advanced/chapter18/practice/factorial.py b/3_advanced/chapter18/practice/factorial.py new file mode 100644 index 00000000..5248b0bb --- /dev/null +++ b/3_advanced/chapter18/practice/factorial.py @@ -0,0 +1,11 @@ +# Create a recursive method that mirrors how a +# factorial would work in math. + + +def factorial(n): + if n == 0: + # add here and remove "pass" + pass + else: + # add here and remove "pass" + pass diff --git a/3_advanced/chapter18/practice/koch_curve.py b/3_advanced/chapter18/practice/koch_curve.py new file mode 100644 index 00000000..499449ae --- /dev/null +++ b/3_advanced/chapter18/practice/koch_curve.py @@ -0,0 +1,42 @@ +# This is a fun problem that uses the turtle module. +# If you’ve never used the turtle module, the first two +# lines below are how to set it up and lines after are basic instructions: + +# import turtle +# bob = turtle.Turtle() #doesn’t have to be bob +# bob.left(angle) #turns bob left to an angle like 90 +# bob.right(angle) #turns bob right to an angle like 90 +# bob.fd(distance) #moves bob forward “distance” amount +# Depending on what IDE you are using, you may have to use +# bob.mainloop() if a window with an arrow doesn’t pop up. + +# The goal of this problem is to create a koch curve. +# [search up what koch curve looks like] + +# A koch curve works as follows: +# -Draw a Koch curve with length x/3. +# -Turn left 60 degrees. +# -Draw a Koch curve with length x/3. +# -Turn right 120 degrees. +# -Draw a Koch curve with length x/3. +# -Turn left 60 degrees. +# -Draw a Koch curve with length x/3. +# However, if x<3, you will just move bob(the turtle) forward +# by length x + +# Credits to: +# http://greenteapress.com/thinkpython2/html/thinkpython2006.html + + +import turtle + +bob = turtle.Turtle() + + +def kochcurve(x): + if x < 3: + # add here and remove "pass" + pass + else: + # add here and remove "pass" + pass diff --git a/3_advanced/chapter18/practice/list_sum.py b/3_advanced/chapter18/practice/list_sum.py new file mode 100644 index 00000000..fb253aa8 --- /dev/null +++ b/3_advanced/chapter18/practice/list_sum.py @@ -0,0 +1,16 @@ +# Create a recursive sequence that finds the sum of +# a list that may contain another list within it. + + +def listsum(arr): + total = 0 + + for i in arr: + if isinstance(i, list): + # add here and remove "pass" + pass + else: + # add here and remove "pass" + pass + + return total diff --git a/3_advanced/chapter18/practice/logarithm.py b/3_advanced/chapter18/practice/logarithm.py new file mode 100644 index 00000000..22927fe9 --- /dev/null +++ b/3_advanced/chapter18/practice/logarithm.py @@ -0,0 +1,16 @@ +""" +Create a recursive method that mirrors how a logarithm works in math. +You can have the base by default by ten. You do not have to deal +with decimals, just worry about returning integers. + +Note: Logarithms return the power that you raise a base number to +in order to get a number. + +Ex: logarithm of 9 to base 3 = 2; In this example, since 3 to the +2nd power gives you 9, the logarithm of 9 to base 3 is equal to 2. +""" + + +def logarithm(): # add parameters + # add here and remove "pass" + pass diff --git a/3_advanced/chapter18/solutions/factorial.py b/3_advanced/chapter18/solutions/factorial.py new file mode 100644 index 00000000..f1447a09 --- /dev/null +++ b/3_advanced/chapter18/solutions/factorial.py @@ -0,0 +1,9 @@ +# Create a recursive method that mirrors how a +# factorial would work in math. + + +def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n - 1) diff --git a/3_advanced/chapter18/solutions/koch_curve.py b/3_advanced/chapter18/solutions/koch_curve.py new file mode 100644 index 00000000..e3d0802b --- /dev/null +++ b/3_advanced/chapter18/solutions/koch_curve.py @@ -0,0 +1,48 @@ +# This is a fun problem that uses the turtle module. +# If you’ve never used the turtle module, the first two +# lines below are how to set it up and lines after are basic instructions: + +# import turtle +# bob = turtle.Turtle() #doesn’t have to be bob +# bob.left(angle) #turns bob left to an angle like 90 +# bob.right(angle) #turns bob right to an angle like 90 +# bob.fd(distance) #moves bob forward “distance” amount +# Depending on what IDE you are using, you may have to use bob.mainloop() +# if a window with an arrow doesn’t pop up. + +# The goal of this problem is to create a koch curve. +# [search up what koch curve looks like] + +# A koch curve works as follows: +# -Draw a Koch curve with length x/3. +# -Turn left 60 degrees. +# -Draw a Koch curve with length x/3. +# -Turn right 120 degrees. +# -Draw a Koch curve with length x/3. +# -Turn left 60 degrees. +# -Draw a Koch curve with length x/3. +# However, if x<3, you will just move bob(the turtle) forward by length x + +# Credits to: +# http://greenteapress.com/thinkpython2/html/thinkpython2006.html + + +import turtle + +bob = turtle.Turtle() + + +def kochcurve(x): + if x < 3: + bob.fd(x) + else: + kochcurve(x / 3) + bob.left(60) + kochcurve(x / 3) + bob.right(120) + kochcurve(x / 3) + bob.left(60) + kochcurve(x / 3) + + +kochcurve(90) # doesn't to be 90, could be any number diff --git a/3_advanced/chapter18/solutions/list_sum.py b/3_advanced/chapter18/solutions/list_sum.py new file mode 100644 index 00000000..73e9c467 --- /dev/null +++ b/3_advanced/chapter18/solutions/list_sum.py @@ -0,0 +1,17 @@ +# Create a recursive sequence that finds the sum of +# a list that may contain another list within it. +# +# Solution Visualizer URL: https://www.w3resource.com/python-exercises/ +# data-structures-and-algorithms/python-recursion-exercise-3.php + + +def listsum(arr): + total = 0 + + for i in arr: + if isinstance(i, list): + total = total + listsum(i) + else: + total = total + i + + return total diff --git a/3_advanced/chapter18/solutions/logarithm.py b/3_advanced/chapter18/solutions/logarithm.py new file mode 100644 index 00000000..a625c78f --- /dev/null +++ b/3_advanced/chapter18/solutions/logarithm.py @@ -0,0 +1,24 @@ +""" +Create a recursive method that mirrors how a logarithm works in math. +You can have the base by default by ten. You do not have to deal +with decimals, just worry about returning integers. + +Note: Logarithms return the power that you raise a base number to +in order to get a number. + +Ex: logarithm of 9 to base 3 = 2; In this example, since 3 to the +2nd power gives you 9, the logarithm of 9 to base 3 is equal to 2. +""" + + +def logarithm(number, base=10, at=1, times=0): + if number < 1 or base == 1: + return None + if number == 1: + return 0 + if at > number: + return times - 1 + if at == number: + return times + newcurrent = at * base + return logarithm(number, base, newcurrent, times + 1) diff --git a/3_advanced/chapter19/examples/error_handle.py b/3_advanced/chapter19/examples/error_handle.py new file mode 100644 index 00000000..a7e070d0 --- /dev/null +++ b/3_advanced/chapter19/examples/error_handle.py @@ -0,0 +1,25 @@ +# Error handling with try clauses or the assert keyword +# can help coders debug programs. They are also useful +# if you want to ignore a certain error. + + +""" try clause """ +try: # this will try the following code + x = 1 + y = "hi" + x + y +except TypeError: # this will only run if there's a TypeError + print("incorrect types, try again") +except NameError: # this will only run if there's a NameError + print("maybe you forgot to create that") +else: # this will run if no error occurs + print("everything good here!") +finally: + # will run no matter what + print("x is", x, "\ny is", y) + + +""" assert keyword """ +string = "goodbye" +assert string == "hello", "string is not hello" +print(string) # this will not be run because assert raises an exception diff --git a/3_advanced/chapter19/practice/finally_use.py b/3_advanced/chapter19/practice/finally_use.py new file mode 100644 index 00000000..82ab209a --- /dev/null +++ b/3_advanced/chapter19/practice/finally_use.py @@ -0,0 +1,15 @@ +# Write a function that takes two parameters and tries to divide +# parameter 1 by parameter 2 to get a result and print that result. +# However, if something goes wrong, have an except print a message +# saying "something went wrong" (optional: have specific messages +# for different errors). Finally, it should, no matter what, print +# "Goodbye World" when it is done. + + +def finally_use(num1, num2): + pass # change this + + +finally_use(4, 0) +finally_use(5, "hi") +finally_use(8, 4) diff --git a/3_advanced/chapter19/practice/int_checker.py b/3_advanced/chapter19/practice/int_checker.py new file mode 100644 index 00000000..d794f1e0 --- /dev/null +++ b/3_advanced/chapter19/practice/int_checker.py @@ -0,0 +1,10 @@ +# Create a program that asks the user to input an integer. Try to +# convert it from a string to an integer. If it fails, send the +# user a message telling them to input a real integer next time. + + +def int_checker(): + pass # change this out for the real code + + +int_checker() diff --git a/3_advanced/chapter19/practice/list_practice.py b/3_advanced/chapter19/practice/list_practice.py new file mode 100644 index 00000000..df751a2a --- /dev/null +++ b/3_advanced/chapter19/practice/list_practice.py @@ -0,0 +1,19 @@ +# Write a function that accesses a global list. It should try to +# take the user’s input for how many times to repeat its process. +# Its process should be: 1. ask the user for a value (any type) +# 2. Append that value to the list. Once that is done, ask the user +# to press q to quit or to input a number to access that index of the +# list. There should be a different error message depending on the type +# of error raised. Whether or not there are errors, when the user is done +# (or there is an error), it should print the list and ask the user +# whether they would like to continue. If this input is 'y', call the +# function again. + +globlist = [] + + +def list_practice(): + pass # change this when you write your code + + +list_practice() diff --git a/3_advanced/chapter19/practice/type_checker.py b/3_advanced/chapter19/practice/type_checker.py new file mode 100644 index 00000000..da688d35 --- /dev/null +++ b/3_advanced/chapter19/practice/type_checker.py @@ -0,0 +1,15 @@ +# Domestic bees make their honeycombs in rings where the total cells is +# (n + 1) * (3n) + 1 where n is the number of rows in the honeycomb +# Create a function that takes one argument and prints how many total +# cells there are in the honeycomb. +# If the argument is not the correct type, print a message saying so. +# It should be able to run through the list provided. + + +def type_checker(x): + pass # remove this + + +arg_list = [4, "hi", "obviously NAN", 5.6, None, {3: 4}, [3, 3]] +for i in arg_list: + type_checker(i) diff --git a/3_advanced/chapter19/solutions/finally_use.py b/3_advanced/chapter19/solutions/finally_use.py new file mode 100644 index 00000000..63d0c88f --- /dev/null +++ b/3_advanced/chapter19/solutions/finally_use.py @@ -0,0 +1,23 @@ +# Write a function that takes two parameters and tries to divide +# parameter 1 by parameter 2 to get a result and print that result. +# However, if something goes wrong, have an except print a message +# saying "something went wrong" (optional: have specific messages +# for different errors). Finally, it should, no matter what, print +# "Goodbye World" when it is done. + + +def finally_use(num1, num2): + try: + result = num1 / num2 + print(result) + except ZeroDivisionError: + print("Cannot divide by Zero") + except TypeError: + print("Invalid type for division") + finally: + print("Goodbye World") + + +finally_use(4, 0) +finally_use(5, "hi") +finally_use(8, 4) diff --git a/3_advanced/chapter19/solutions/int_checker.py b/3_advanced/chapter19/solutions/int_checker.py new file mode 100644 index 00000000..f47f4858 --- /dev/null +++ b/3_advanced/chapter19/solutions/int_checker.py @@ -0,0 +1,14 @@ +# Create a program that asks the user to input an integer. Try to +# convert it from a string to an integer. If it fails, send the +# user a message telling them to input a real integer next time. + + +def int_checker(): + number = input("Please input an integer") + try: + number = int(number) + except ValueError: # You don't need to specify + print("Sorry, that wasn't a valid integer") + + +int_checker() diff --git a/3_advanced/chapter19/solutions/list_practice.py b/3_advanced/chapter19/solutions/list_practice.py new file mode 100644 index 00000000..a86e9dd6 --- /dev/null +++ b/3_advanced/chapter19/solutions/list_practice.py @@ -0,0 +1,41 @@ +# Write a function that accesses a global list. It should try to +# take the user’s input for how many times to repeat its process. +# Its process should be: 1. ask the user for a value (any type) +# 2. Append that value to the list. Once that is done, ask the user +# to press q to quit or to input a number to access that index of the +# list. There should be a different error message depending on the type +# of error raised. Whether or not there are errors, when the user is done +# (or there is an error), it should print the list and ask the user +# whether they would like to continue. If this input is 'y', call the +# function again. + +globlist = [] + + +def list_practice(): + global globlist + try: + times = int(input("How many times would you like to do this? ")) + for i in range(times): + globlist.append(input("What to append? ")) + myinput = input( + "press q to quit; input a number to access that value in the list" + ) + while myinput != "q": + print(globlist[int(myinput)]) + myinput = input( + "press q to quit, input a number to access that value of" + + " the list" + ) + except ValueError: + print("That's not a number") + except IndexError: + print("That's out of range") + finally: + print("This is the list you ended up with: ", globlist) + cont = input("try again? y/n ") + if cont == "y": + list_practice() + + +list_practice() diff --git a/3_advanced/chapter19/solutions/type_checker.py b/3_advanced/chapter19/solutions/type_checker.py new file mode 100644 index 00000000..a5456e81 --- /dev/null +++ b/3_advanced/chapter19/solutions/type_checker.py @@ -0,0 +1,21 @@ +# Domestic bees make their honeycombs in rings where the total cells is +# (n + 1) * (3n) + 1 where n is the number of rows in the honeycomb +# Create a function that takes one argument and prints how many total +# cells there are in the honeycomb. +# If the argument is not the correct type, print a message saying so. +# It should be able to run through the list provided. + + +def type_checker(x): + try: + print((x + 1) * (3 * x) + 1) + # note to students: print(x * any number) would not result in + # an error if x is a string; it would just print x that many + # times + except TypeError: + print("That's not a valid number") + + +arg_list = [4, "hi", "obviously NAN", 5.6, None, {3: 4}, [3, 3]] +for i in arg_list: + type_checker(i) diff --git a/3_advanced/chapter20/examples/json.py b/3_advanced/chapter20/examples/json.py new file mode 100644 index 00000000..098dc9f9 --- /dev/null +++ b/3_advanced/chapter20/examples/json.py @@ -0,0 +1,52 @@ +import json + + +""" Writing """ +x = open("filename.json", "w") # opens JSON file with write mode +topdict = {} + +chinese = {"hello": "ni hao", "bye": "zai jian", "how are you": "ni hao ma"} +frenchlist = [34, 1, 2, 6] + +topdict["chinese"] = chinese +topdict["frenchlist"] = frenchlist + +json.dump(topdict, x, indent=4) # writes value of topdict into JSON file +x.close() # closes the JSON file and saves the changes + + +""" Reading """ +x = open("./testit.json", "r") # opens JSON file with write read +y = json.load(x) # "grabs" JSON data from testit.json + +for key in y: + print(key, ", ", y[key]) # prints the top values of the JSON file + +x.close() + + +""" Editing a pre-existing JSON file """ +x = open("filename.json", "r") +y = json.load(x) # y becomes the equivalent of a Python dictionary +x.close() + +# the value can be all the normal types that dictionaries can hold +y["some_key"] = "some value" +x = open("filename.json", "w") +json.dump(y, x, indent=4) +x.close() + + +""" json.dumps() method """ +oldDict = {"fname": "john", "lname": "doe", "age": 20} +print("oldDict:", type(oldDict)) # prints data type of oldDict +newStr = json.dumps(oldDict) # converts oldDict to string format +print("newStr:", type(newStr)) # prints data type of newStr + + +""" json.loads() method """ + +oldStr = '{"fname": "john", "lname": "doe", "age": 20}' +print("oldStr:", type(oldStr)) # prints data type of oldStr +newDict = json.loads(oldStr) # converts oldStr to string format +print("newDict:", type(newDict)) # prints data type of newDict diff --git a/3_advanced/chapter20/examples/shelve.py b/3_advanced/chapter20/examples/shelve.py new file mode 100644 index 00000000..01c75a50 --- /dev/null +++ b/3_advanced/chapter20/examples/shelve.py @@ -0,0 +1,17 @@ +# shelve is a Python module that aids with storing data. +# It functions similar to a dictionary, although it +# only allows keys to be strings. + + +import shelve + +# this will open or create a database +myshelf = shelve.open("mydatabase") + +# remember, while the key must be a string, the value can be any type +myshelf["key1"] = 4 + +print(myshelf["key1"]) # prints 4 + +myshelf.close() +# always remember to close the shelve after writing to save the data diff --git a/3_advanced/chapter20/examples/text_files.py b/3_advanced/chapter20/examples/text_files.py new file mode 100644 index 00000000..4f57ea51 --- /dev/null +++ b/3_advanced/chapter20/examples/text_files.py @@ -0,0 +1,71 @@ +# The functions below are the basics of +# creating, editting, and reading text files. + + +# "a" stands for "append" +myfile = open("mytext.txt", "a") + + +# "w" stands for "write" +myfile = open("mytext.txt", "w") + + +# writes into a mytext.txt on different lines +# "hello world\nhi again\nhelloooo" +# You need to use the "\n" character if you want to write to a new line; if you +# don't use it, the next .write() will write to the same line as the previous .write() +myfile.write("hello world\n") # writes on line 1 +myfile.write("hi again\n") # writes on line 2 +myfile.write("helloooo") # writes on line 3 + + +# saves file +myfile.close() + + +# "r" stands for "read" +myfile = open("mytext.txt", "r") + + +# takes data from mytext.txt and prints it +mydata = myfile.read() +print(mydata) + + +# determines if myfile is readable +print(myfile.readable()) + + +print(myfile.readline()) # prints the first line +print(myfile.readline()) # prints the second line +print(myfile.readline()) # prints the third line + + +# determines if you can set your position in myfile +print(myfile.seekable()) + + +# sets your position to the 0th index +myfile.seek(0) + + +# prints a list of all the lines in the file +print(myfile.readlines()) + + +# prints your position in a file +print(myfile.tell()) + + +# determines if you can write into myfile +print(myfile.writable()) + + +myfile = open("mytext.txt", "w") + + +# writes lines from provided list into myfile +myfile.writelines(["line one\n", "line 2"]) + + +myfile.close() diff --git a/3_advanced/chapter20/practice/favorite_foods.json b/3_advanced/chapter20/practice/favorite_foods.json new file mode 100644 index 00000000..ba2df668 --- /dev/null +++ b/3_advanced/chapter20/practice/favorite_foods.json @@ -0,0 +1,8 @@ +{ + "favorite foods": { + "Jerry": "ice cream", + "Ben": "ice cream", + "Steven": "eggroll", + "Spongebob": "Krabby Patty" + } +} \ No newline at end of file diff --git a/3_advanced/chapter20/practice/hidden_message.py b/3_advanced/chapter20/practice/hidden_message.py new file mode 100644 index 00000000..e878863d --- /dev/null +++ b/3_advanced/chapter20/practice/hidden_message.py @@ -0,0 +1,5 @@ +# Create a program that reads textfile.txt and writes (appends) 2 +# newlines and then every 7th word followed by a space + +# ex: given “hi”, “ho”, “ha”, “hy”, “he”, “hu”, “we”, “everyone” +# it would print 2 newlines and then ‘hi everyone’ diff --git a/3_advanced/chapter20/practice/json_practice_1.py b/3_advanced/chapter20/practice/json_practice_1.py new file mode 100644 index 00000000..4961d68f --- /dev/null +++ b/3_advanced/chapter20/practice/json_practice_1.py @@ -0,0 +1,6 @@ +# use the "favorite_foods.json" +# in that json file, there will be a dictionary called "favorite_foods" +# print all the unique favorite foods, which will be the values. +# Save all the names into a list. Add that list to the dictionary +# ('names' should be the key and the names list should be the value) +# and write the dictionary into the json file diff --git a/3_advanced/chapter20/practice/json_practice_2.py b/3_advanced/chapter20/practice/json_practice_2.py new file mode 100644 index 00000000..8b6426dd --- /dev/null +++ b/3_advanced/chapter20/practice/json_practice_2.py @@ -0,0 +1,4 @@ +# use the file "wildlife.json" +# load the data in the JSON file +# add at least one habitat and corresponding animal(s) to the dictionary +# finally, write the updated dictionary to the json file. diff --git a/3_advanced/chapter20/practice/modify_random_text.py b/3_advanced/chapter20/practice/modify_random_text.py new file mode 100644 index 00000000..7e459c31 --- /dev/null +++ b/3_advanced/chapter20/practice/modify_random_text.py @@ -0,0 +1,5 @@ +# Create a program that creates a blank text file and writes a +# random number (in the form of a string) between 1 and 1000 on it. +# Next, close the file. Next, open the file again (this time read it) +# and read the text. Assign a variable to that data. +# print (not write) the variable, then print the int(variable) * 4. diff --git a/3_advanced/chapter20/practice/mydatabase.db b/3_advanced/chapter20/practice/mydatabase.db new file mode 100644 index 00000000..9c84d85b Binary files /dev/null and b/3_advanced/chapter20/practice/mydatabase.db differ diff --git a/3_advanced/chapter20/practice/mydb.db b/3_advanced/chapter20/practice/mydb.db new file mode 100644 index 00000000..56a11caf Binary files /dev/null and b/3_advanced/chapter20/practice/mydb.db differ diff --git a/3_advanced/chapter20/practice/shelve_practice_1.py b/3_advanced/chapter20/practice/shelve_practice_1.py new file mode 100644 index 00000000..ac470e74 --- /dev/null +++ b/3_advanced/chapter20/practice/shelve_practice_1.py @@ -0,0 +1,13 @@ +# Use mydatabase.db; Using it, first get all the keys and put them into a list. +# For help on this, see the hint below. Next, sort the list. Finally, print the +# corresponding values. +# To do that, do print((shelfname)[key]) where (shelfname) is the name of your +# shelf and key is the key. + +# Hint: to get a dictionary or shelf’s keys, all you have to do is this: +""" +for key in myshelf.keys(): + keylist.append(key) +""" +# Keep in mind that the “myshelf” is just a name for a dictionary or shelf and +# that the “keylist” is just a list holding the keys. diff --git a/3_advanced/chapter20/practice/shelve_practice_2.py b/3_advanced/chapter20/practice/shelve_practice_2.py new file mode 100644 index 00000000..89ea7dca --- /dev/null +++ b/3_advanced/chapter20/practice/shelve_practice_2.py @@ -0,0 +1,4 @@ +# Use mydb.db . Using it, first create a total variable. Then, add +# all of the shelve’s values to the total. Remember to check if +# the value is an integer before adding it to the total. +# After all, shelves can store all types. diff --git a/3_advanced/chapter20/practice/shelve_practice_3.py b/3_advanced/chapter20/practice/shelve_practice_3.py new file mode 100644 index 00000000..a87e6986 --- /dev/null +++ b/3_advanced/chapter20/practice/shelve_practice_3.py @@ -0,0 +1,12 @@ +# Create a database to store orders. Next, ask the customer for their +# name and store that as a variable. Next, ask the customer whether +# they want to view their previous order or make a new order. + +# If they want to make a new order, use the shelf to store the order +# as the value and the customer’s name as the key. + +# If they want to view a previous order, check if their name is in +# the shelf’s keys. If it is, print their previous order. +# If not, tell them that they haven’t ordered. +# Remember to close the shelf. +# Hint: to store their order, you can do: shelf[name] = order diff --git a/3_advanced/chapter20/practice/textfile.txt b/3_advanced/chapter20/practice/textfile.txt new file mode 100644 index 00000000..6056bb2a --- /dev/null +++ b/3_advanced/chapter20/practice/textfile.txt @@ -0,0 +1,6 @@ +hi ho he hu hy ha we everyone. wow pow kow some tome Biome How +are bar tsar czar ceasar tar do moo cow baa sheep pig big you too +blue eggs and ham spam do? sew. machine grow large. barge in hopefully +successfully totally completely absolutely did it! you bought that +old fish ten days, did it taste good? huh? what? ok. it is never +close till it is right! diff --git a/3_advanced/chapter20/practice/txt_write_practice.py b/3_advanced/chapter20/practice/txt_write_practice.py new file mode 100644 index 00000000..0d26d17c --- /dev/null +++ b/3_advanced/chapter20/practice/txt_write_practice.py @@ -0,0 +1,136 @@ +import requests +import shelve + + +class game: + def __init__(self, pageinfo, bsl: int, gns, gds, gps, gops, end): + """ + Arguments: + bsl is the beginning search location. It should be an integer + pageinfo is the html of a website converted to a string + gns is the 'game's name start'; it is what to look for directly + before a game's name + gds is the 'game's discount start'; it is what to look for directly + before a game's discount + gps is the 'game's price start'; it is what to look for directly + before a game's discounted price + gops is the 'game original price start'; it is what to look for + directly before a game's original price + + """ + self.string = pageinfo + self.isvalid = True + self.begin = bsl + self.endloc = 0 + + self.discount = self.find(self.string, gds, end, cb=True) + self.price = self.find(self.string, gps, end) + self.ogprice = self.find(self.string, gops, end) + self.name = self.find(self.string, gns, end, cwe=True) + + def find(self, string, start: str, end: str, cb=False, cwe=False): + """ + Arguments + string is the string where the substring you are looking for + is located + start is the substring directly before the substring you are + looking for + end is the substring directly after the substring you are + looking for + cb is whether or not to change the beginning point for the + searches to the endloc + cwe is whether to compare the endloc with self.begin and + check whether the difference is withing the acceptable range + """ + try: + startloc = string.index(start, self.begin) + endloc = string.index(end, startloc) + except Exception: + self.endloc = self.begin + 1 + self.isvalid = False + return + + if cb: + self.begin = endloc + if cwe: + # check if the end location is too far away from the + # beginning to be a valid name + if endloc - self.begin > 300: + self.isvalid = False + self.endloc = endloc + + return string[startloc:endloc].lstrip(start).rstrip(end) + + +class scansteampage: + def __init__(self, database="gameshelf"): + """ + See game's explanation for the abbreviations + """ + link = "https://store.steampowered.com/" + gns = '