diff --git a/.github/workflows/python-lint.yml b/.github/workflows/disabled/python-lint.yml similarity index 100% rename from .github/workflows/python-lint.yml rename to .github/workflows/disabled/python-lint.yml diff --git a/.github/workflows/python-format.yml b/.github/workflows/python-format.yml index 71331888..0eac2193 100644 --- a/.github/workflows/python-format.yml +++ b/.github/workflows/python-format.yml @@ -7,7 +7,7 @@ on: pull_request jobs: format-lint-python: - name: Format Python with black + name: Format Python with black and lint with flake8 runs-on: ubuntu-latest steps: @@ -20,12 +20,14 @@ jobs: python-version: '3.x' - name: Install Python dependencies - run: pip install black + run: pip install black flake8 - - name: Run black - uses: samuelmeuli/lint-action@v1 + - name: Run black and flake8 + uses: wearerequired/lint-action@v1 with: - github_token: ${{ secrets.GITHUB_TOKEN }} black: true - black_args: --line-length 79 # same max line length as flake8 - auto_fix: true # auto commit style fixes \ No newline at end of file + 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 d1e0b281..c233127c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .vscode/ *.xml *.iml +venv/ \ No newline at end of file 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 d726553a..40f4ab82 100644 --- a/1_beginner/chapter1/examples/printing.py +++ b/1_beginner/chapter1/examples/printing.py @@ -1,5 +1,10 @@ # 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") 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/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/solutions/change.py b/1_beginner/chapter3/solutions/change.py index bad5b99b..a8cd5ee9 100644 --- a/1_beginner/chapter3/solutions/change.py +++ b/1_beginner/chapter3/solutions/change.py @@ -30,19 +30,19 @@ # 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 94897dfd..07494915 100644 --- a/1_beginner/chapter3/solutions/cylinder_volume.py +++ b/1_beginner/chapter3/solutions/cylinder_volume.py @@ -6,5 +6,5 @@ PI = 3.14 height = float(input("Height of cylinder: ")) radius = float(input("Radius of cylinder: ")) -volume = PI * radius ** 2 * height +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/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/chapter5/practice/alternating.py b/1_beginner/chapter5/practice/alternating.py index a57c1dde..0fe44abc 100644 --- a/1_beginner/chapter5/practice/alternating.py +++ b/1_beginner/chapter5/practice/alternating.py @@ -1,17 +1,12 @@ """ Alternating - -Ask the user for an integer. The 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 +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. - -number = int(input("Enter Number Here: ")) - +# Write code here # Now try 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/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/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/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/2_intermediate/chapter10/practice/img_avg.py b/2_intermediate/chapter10/practice/img_avg.py index dc9de796..2b71c3b3 100644 --- a/2_intermediate/chapter10/practice/img_avg.py +++ b/2_intermediate/chapter10/practice/img_avg.py @@ -1,50 +1,83 @@ """ Image Average -Here is the challenge problem for 2D loops: -Images are often represented as 3D arrays, -where the rows and columns are the pixels in the image, -and each pixel has an RGB (red, green, blue) value -which determines the color of the pixel. +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 +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. -The neighbors of an image are all the pixels that surround it, -1 on each side, and 4 on the diagonals, for 8 in total. Each -pixel doesn't necessarily have 8 neighbors, though (think about why). - -The code to grab an image from the internet and make it -into an array is given to you. The code also displays the new image -you create in the end. - -NOTE: The image is 3 dimensional because each pixel has RGB values. To find the average value of all of a pixels neighbors, you must -change the average of the red value to the red value, blue to blue, etc. +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] +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 -url = "https://images.dog.ceo/breeds/waterdog-spanish/20180723_185544.jpg" -img = numpy.array(Image.open(requests.get(url, stream=True).raw)).tolist() -newimg = img -transpose = numpy.transpose(img) +# 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 +# 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() - -plt.imshow(transpose) -plt.show() diff --git a/2_intermediate/chapter10/solutions/img_avg.py b/2_intermediate/chapter10/solutions/img_avg.py index 815ab8ea..66077ed6 100644 --- a/2_intermediate/chapter10/solutions/img_avg.py +++ b/2_intermediate/chapter10/solutions/img_avg.py @@ -1,95 +1,162 @@ """ Image Average -Here is the challenge problem for 2D loops: -Images are often represented as 3D arrays, -where the rows and columns are the pixels in the image, -and each pixel has an RGB (red, green, blue) value -which determines the color of the pixel. +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 +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. -The neighbors of an image are all the pixels that surround it, -1 on each side, and 4 on the diagonals, for 8 in total. Each -pixel doesn't necessarily have 8 neighbors, though (think about why). - -The code to grab an image from the internet and make it -into an array is given to you. The code also displays the new image -you create in the end. - -NOTE: The image is 3 dimensional because each pixel has RGB values. To find the average value of all of a pixels neighbors, you must -change the average of the red value to the red value, blue to blue, etc. +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] +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 -url = "https://images.dog.ceo/breeds/waterdog-spanish/20180723_185544.jpg" -img = numpy.array(Image.open(requests.get(url, stream=True).raw)) -newimg = img -transpose = numpy.transpose(img) +# 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 -def solution1(): +def distort(original_image, new_image): """ - Iterating over the image here. i is a variable from - 0 to the width of the image. - j is a variable that ranges from 0 to the height of the image. - i is associated with values + 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. """ - for i in range(len(img)): - for j in range(len(img[0])): - x_n = [0] - y_n = [0] - - if i == 0: - x_n.append(1) - elif i == len(img) - 1: - x_n.append(-1) - else: - x_n.append(1) - x_n.append(-1) - - if j == 0: - y_n.append(1) - elif j == len(img[0]) - 1: - y_n.append(-1) - else: - y_n.append(1) - y_n.append(-1) - - r_avg = -1 * img[i][j][0] - g_avg = -1 * img[i][j][1] - b_avg = -1 * img[i][j][2] - c = -1 - - for x in x_n: - for y in y_n: - r_avg += img[i + x][j + y][0] - g_avg += img[i + x][j + y][1] - b_avg += img[i + x][j + y][2] - c += 1 - r_avg = r_avg / c - g_avg = g_avg / c - b_avg = b_avg / c - - newimg[i][j] = [r_avg, g_avg, b_avg] - - -solution1() - + 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() - -plt.imshow(transpose) -plt.show() 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/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/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/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/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/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/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/3_advanced/chapter13/examples/vector.py b/2_intermediate/chapter13/examples/vector.py similarity index 95% rename from 3_advanced/chapter13/examples/vector.py rename to 2_intermediate/chapter13/examples/vector.py index 3768a6ec..6038aad3 100644 --- a/3_advanced/chapter13/examples/vector.py +++ b/2_intermediate/chapter13/examples/vector.py @@ -1,26 +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] +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/3_advanced/chapter13/examples/vector2.py b/2_intermediate/chapter13/examples/vector2.py similarity index 90% rename from 3_advanced/chapter13/examples/vector2.py rename to 2_intermediate/chapter13/examples/vector2.py index 1c2236e3..224ccd01 100644 --- a/3_advanced/chapter13/examples/vector2.py +++ b/2_intermediate/chapter13/examples/vector2.py @@ -1,59 +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] +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/3_advanced/chapter13/examples/vector3.py b/2_intermediate/chapter13/examples/vector3.py similarity index 90% rename from 3_advanced/chapter13/examples/vector3.py rename to 2_intermediate/chapter13/examples/vector3.py index d23d6a35..25307216 100644 --- a/3_advanced/chapter13/examples/vector3.py +++ b/2_intermediate/chapter13/examples/vector3.py @@ -1,68 +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 +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/3_advanced/chapter13/practice/car.py b/2_intermediate/chapter13/practice/car.py similarity index 97% rename from 3_advanced/chapter13/practice/car.py rename to 2_intermediate/chapter13/practice/car.py index 742b40a9..dd972e70 100644 --- a/3_advanced/chapter13/practice/car.py +++ b/2_intermediate/chapter13/practice/car.py @@ -1,31 +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 +""" +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/3_advanced/chapter13/practice/filler b/2_intermediate/chapter13/practice/filler similarity index 100% rename from 3_advanced/chapter13/practice/filler rename to 2_intermediate/chapter13/practice/filler diff --git a/3_advanced/chapter13/practice/lexicographical_vector.py b/2_intermediate/chapter13/practice/lexicographical_vector.py similarity index 97% rename from 3_advanced/chapter13/practice/lexicographical_vector.py rename to 2_intermediate/chapter13/practice/lexicographical_vector.py index b828d345..43a8f202 100644 --- a/3_advanced/chapter13/practice/lexicographical_vector.py +++ b/2_intermediate/chapter13/practice/lexicographical_vector.py @@ -1,12 +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 +""" +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/3_advanced/chapter13/practice/line.py b/2_intermediate/chapter13/practice/line.py similarity index 97% rename from 3_advanced/chapter13/practice/line.py rename to 2_intermediate/chapter13/practice/line.py index bce1b743..6bfca643 100644 --- a/3_advanced/chapter13/practice/line.py +++ b/2_intermediate/chapter13/practice/line.py @@ -1,9 +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 +""" +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/3_advanced/chapter13/practice/matrix.py b/2_intermediate/chapter13/practice/matrix.py similarity index 97% rename from 3_advanced/chapter13/practice/matrix.py rename to 2_intermediate/chapter13/practice/matrix.py index e249ff53..91ba119a 100644 --- a/3_advanced/chapter13/practice/matrix.py +++ b/2_intermediate/chapter13/practice/matrix.py @@ -1,10 +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 +""" +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/3_advanced/chapter13/practice/matrix_add_subtract.py b/2_intermediate/chapter13/practice/matrix_add_subtract.py similarity index 96% rename from 3_advanced/chapter13/practice/matrix_add_subtract.py rename to 2_intermediate/chapter13/practice/matrix_add_subtract.py index 240d0e55..8aa83fe2 100644 --- a/3_advanced/chapter13/practice/matrix_add_subtract.py +++ b/2_intermediate/chapter13/practice/matrix_add_subtract.py @@ -1,25 +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 +""" +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/3_advanced/chapter13/practice/matrix_frobenius_norm.py b/2_intermediate/chapter13/practice/matrix_frobenius_norm.py similarity index 97% rename from 3_advanced/chapter13/practice/matrix_frobenius_norm.py rename to 2_intermediate/chapter13/practice/matrix_frobenius_norm.py index 434e7ef0..f7689fd1 100644 --- a/3_advanced/chapter13/practice/matrix_frobenius_norm.py +++ b/2_intermediate/chapter13/practice/matrix_frobenius_norm.py @@ -1,26 +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 +""" +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/3_advanced/chapter13/practice/matrix_less_greater.py b/2_intermediate/chapter13/practice/matrix_less_greater.py similarity index 96% rename from 3_advanced/chapter13/practice/matrix_less_greater.py rename to 2_intermediate/chapter13/practice/matrix_less_greater.py index e76f87f3..1d928dae 100644 --- a/3_advanced/chapter13/practice/matrix_less_greater.py +++ b/2_intermediate/chapter13/practice/matrix_less_greater.py @@ -1,25 +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 +""" +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/3_advanced/chapter13/practice/polar_coordinates.py b/2_intermediate/chapter13/practice/polar_coordinates.py similarity index 97% rename from 3_advanced/chapter13/practice/polar_coordinates.py rename to 2_intermediate/chapter13/practice/polar_coordinates.py index 2ad13c4a..98e23c30 100644 --- a/3_advanced/chapter13/practice/polar_coordinates.py +++ b/2_intermediate/chapter13/practice/polar_coordinates.py @@ -1,10 +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 +""" +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/3_advanced/chapter13/practice/triangle.py b/2_intermediate/chapter13/practice/triangle.py similarity index 97% rename from 3_advanced/chapter13/practice/triangle.py rename to 2_intermediate/chapter13/practice/triangle.py index 94e58bdf..61ec4f28 100644 --- a/3_advanced/chapter13/practice/triangle.py +++ b/2_intermediate/chapter13/practice/triangle.py @@ -1,15 +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 +""" +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/3_advanced/chapter13/practice/vector.py b/2_intermediate/chapter13/practice/vector.py similarity index 97% rename from 3_advanced/chapter13/practice/vector.py rename to 2_intermediate/chapter13/practice/vector.py index 9dfd66c5..c3107c1f 100644 --- a/3_advanced/chapter13/practice/vector.py +++ b/2_intermediate/chapter13/practice/vector.py @@ -1,10 +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 +""" +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/3_advanced/chapter13/solutions/car.py b/2_intermediate/chapter13/solutions/car.py similarity index 97% rename from 3_advanced/chapter13/solutions/car.py rename to 2_intermediate/chapter13/solutions/car.py index 976626b8..5f5c6717 100644 --- a/3_advanced/chapter13/solutions/car.py +++ b/2_intermediate/chapter13/solutions/car.py @@ -1,124 +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) +""" +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/3_advanced/chapter13/solutions/filler b/2_intermediate/chapter13/solutions/filler similarity index 100% rename from 3_advanced/chapter13/solutions/filler rename to 2_intermediate/chapter13/solutions/filler diff --git a/3_advanced/chapter13/solutions/lexicographical_vector.py b/2_intermediate/chapter13/solutions/lexicographical_vector.py similarity index 97% rename from 3_advanced/chapter13/solutions/lexicographical_vector.py rename to 2_intermediate/chapter13/solutions/lexicographical_vector.py index 6b7a05f4..de8faafd 100644 --- a/3_advanced/chapter13/solutions/lexicographical_vector.py +++ b/2_intermediate/chapter13/solutions/lexicographical_vector.py @@ -1,72 +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 +""" +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/3_advanced/chapter13/solutions/line.py b/2_intermediate/chapter13/solutions/line.py similarity index 96% rename from 3_advanced/chapter13/solutions/line.py rename to 2_intermediate/chapter13/solutions/line.py index 335aa00f..a524ff83 100644 --- a/3_advanced/chapter13/solutions/line.py +++ b/2_intermediate/chapter13/solutions/line.py @@ -1,23 +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)) +""" +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/3_advanced/chapter13/solutions/matrix.py b/2_intermediate/chapter13/solutions/matrix.py similarity index 97% rename from 3_advanced/chapter13/solutions/matrix.py rename to 2_intermediate/chapter13/solutions/matrix.py index 180755a5..fd1ba70f 100644 --- a/3_advanced/chapter13/solutions/matrix.py +++ b/2_intermediate/chapter13/solutions/matrix.py @@ -1,27 +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)) +""" +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/3_advanced/chapter13/solutions/matrix_add_subtract.py b/2_intermediate/chapter13/solutions/matrix_add_subtract.py similarity index 97% rename from 3_advanced/chapter13/solutions/matrix_add_subtract.py rename to 2_intermediate/chapter13/solutions/matrix_add_subtract.py index 769a5984..d2e24973 100644 --- a/3_advanced/chapter13/solutions/matrix_add_subtract.py +++ b/2_intermediate/chapter13/solutions/matrix_add_subtract.py @@ -1,57 +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) +""" +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/3_advanced/chapter13/solutions/matrix_frobenius_norm.py b/2_intermediate/chapter13/solutions/matrix_frobenius_norm.py similarity index 96% rename from 3_advanced/chapter13/solutions/matrix_frobenius_norm.py rename to 2_intermediate/chapter13/solutions/matrix_frobenius_norm.py index df99717b..09be9792 100644 --- a/3_advanced/chapter13/solutions/matrix_frobenius_norm.py +++ b/2_intermediate/chapter13/solutions/matrix_frobenius_norm.py @@ -1,53 +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)) +""" +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/3_advanced/chapter13/solutions/matrix_less_greater.py b/2_intermediate/chapter13/solutions/matrix_less_greater.py similarity index 96% rename from 3_advanced/chapter13/solutions/matrix_less_greater.py rename to 2_intermediate/chapter13/solutions/matrix_less_greater.py index bb798b76..5521a3c6 100644 --- a/3_advanced/chapter13/solutions/matrix_less_greater.py +++ b/2_intermediate/chapter13/solutions/matrix_less_greater.py @@ -1,74 +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) +""" +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/3_advanced/chapter13/solutions/polar_coordinates.py b/2_intermediate/chapter13/solutions/polar_coordinates.py similarity index 96% rename from 3_advanced/chapter13/solutions/polar_coordinates.py rename to 2_intermediate/chapter13/solutions/polar_coordinates.py index 9f038383..ff743831 100644 --- a/3_advanced/chapter13/solutions/polar_coordinates.py +++ b/2_intermediate/chapter13/solutions/polar_coordinates.py @@ -1,27 +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)) +""" +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/3_advanced/chapter13/solutions/triangle.py b/2_intermediate/chapter13/solutions/triangle.py similarity index 97% rename from 3_advanced/chapter13/solutions/triangle.py rename to 2_intermediate/chapter13/solutions/triangle.py index b9168a33..31043ab8 100644 --- a/3_advanced/chapter13/solutions/triangle.py +++ b/2_intermediate/chapter13/solutions/triangle.py @@ -1,45 +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)) +""" +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/3_advanced/chapter13/solutions/vector.py b/2_intermediate/chapter13/solutions/vector.py similarity index 96% rename from 3_advanced/chapter13/solutions/vector.py rename to 2_intermediate/chapter13/solutions/vector.py index 7bbfc15d..95c90664 100644 --- a/3_advanced/chapter13/solutions/vector.py +++ b/2_intermediate/chapter13/solutions/vector.py @@ -1,39 +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 +""" +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/intermediateproject/gui_memory_cards.py b/2_intermediate/intermediateproject/gui_memory_cards.py deleted file mode 100644 index c3124055..00000000 --- a/2_intermediate/intermediateproject/gui_memory_cards.py +++ /dev/null @@ -1,140 +0,0 @@ -import random -import tkinter as tk -from functools import partial -import time - - -class memcards(tk.Frame): - def __init__(self, parent, items): - super().__init__(parent) - self.parent = parent - self.grid() - - self.flipped = set() - self.current = [] - self.memorder = [None for i in range(len(items) * 2)] - self.dictionary = items - self.keys = list(items.keys()) - self.values = list(items.values()) - self.shuffle() - self.definemap() - self.createlabel() - - def createlabel(self): - self.label = tk.Label( - self, - text="The Rows and Columns start at 0, not 1; #" - + " means unflipped; _ means correct", - ) - self.label.grid( - row=len(self.memorder) // len(self.currmap[0]), - column=0, - rowspan=2, - columnspan=len(self.currmap[0]), - sticky=tk.W + tk.S, - ) - self.label.config(bg="purple") - - def definemap(self): - # figure out potential heights and widths - divisors = [] - for i in range(len(self.memorder)): - if (len(self.memorder)) % (i + 1) == 0: - divisors.append(i + 1) - # gets the real width and height of map - width = divisors[len(divisors) // 2] - height = divisors[(len(divisors) // 2) - 1] - themap = [[None for i in range(width)] for x in range(height)] - for x in range(height): - for i in range(width): - themap[x][i] = tk.Button( - self, text="#", command=partial(self.flip, x, i) - ) - themap[x][i].grid(row=x, column=i, ipadx=10, ipady=5) - themap[x][i].config(bg="light blue") - self.currmap = themap - - def shuffle(self): - doneitems = {} - while len(self.memorder) > len(doneitems): - itemloc = random.randint(0, len(self.keys) - 1) - b = random.randint(0, 1) - memorderloc = random.randint(0, len(self.keys * 2) - 1) - if memorderloc not in doneitems.values(): - if b == 0 and self.memorder[memorderloc] not in self.keys: - self.memorder[memorderloc] = self.keys[itemloc] - doneitems[self.memorder[memorderloc]] = memorderloc - if b == 1 and self.memorder[memorderloc] not in self.values: - self.memorder[memorderloc] = self.values[itemloc] - doneitems[self.memorder[memorderloc]] = memorderloc - - def flip(self, row, column): - self.currmap[row][column]["text"] = self.memorder[ - (row * len(self.currmap[0])) + column - ] - self.currmap[row][column].grid(row=row, column=column) - self.current.append( - [ - self.memorder[(row * len(self.currmap[0])) + column], - [row, column], - ] - ) - - def unflip(self, correct: bool): - if correct: - self.flipped.add(self.current[0][0]) - self.flipped.add(self.current[1][0]) - self.currmap[self.current[0][1][0]][self.current[0][1][1]][ - "text" - ] = "__" - self.currmap[self.current[1][1][0]][self.current[1][1][1]][ - "text" - ] = "__" - self.label["text"] = "Correct" - else: - self.currmap[self.current[0][1][0]][self.current[0][1][1]][ - "text" - ] = "#" - self.currmap[self.current[1][1][0]][self.current[1][1][1]][ - "text" - ] = "#" - self.label["text"] = "Incorrect" - self.current = [] - - def mainloop(self): - try: - while 1: - self.update_idletasks() - self.update() - if len(self.current) == 2: - if ( - self.current[0][0] in self.dictionary - and self.dictionary[self.current[0][0]] - == self.current[1][0] - ): - time.sleep(0.5) - self.unflip(True) - elif ( - self.current[1][0] in self.dictionary - and self.dictionary[self.current[1][0]] - == self.current[0][0] - ): - time.sleep(0.5) - self.unflip(True) - else: - time.sleep(0.5) - self.unflip(False) - if len(self.flipped) == len(self.memorder): - self.label["text"] = "Congratulations, you win!" - time.sleep(0.01) - except tk.TclError: - print("Exited successfully, Game Over") - - -items = {"a": 1, "b": 2, "c": 3, "d": 4} - - -root = tk.Tk() -root.minsize(150, 100) -app = memcards(root, items) -app.mainloop() diff --git a/2_intermediate/intermediateproject/memory_cards.py b/2_intermediate/intermediateproject/memory_cards.py deleted file mode 100644 index be1e21f1..00000000 --- a/2_intermediate/intermediateproject/memory_cards.py +++ /dev/null @@ -1,93 +0,0 @@ -import random - - -class memcards: - def __init__(self, items: dict): - self.memorder = [None for i in range(len(items) * 2)] - self.dict = items - self.keys = list(items.keys()) - self.values = list(items.values()) - self.shuffle() - self.currmap = self.definemap() - self.play() - - def play(self): - instructions = ( - "The Rows and Columns start at 0, not 1; # means " - + "unflipped; _ means correct" - ) - # I used a set, but you could also have used a list or - # a dictionary so long as you checked if elements were already - # in the list before adding them - flipped = set() - print(instructions) - while len(self.memorder) > len(flipped): - self.display() - row1 = int(input("Which row would you like to select? ")) - column1 = int(input("Which column would you like to select? ")) - item1 = self.flip(row1, column1, "reveal") - row2 = int(input("Which row would you like to select now? ")) - column2 = int(input("Which column would you like to select? ")) - item2 = self.flip(row2, column2, "reveal") - if item1 in self.dict and self.dict[item1] == item2: - print("Correct!") - flipped.add(self.flip(row1, column1, "correct")) - flipped.add(self.flip(row2, column2, "correct")) - elif item2 in self.dict and self.dict[item2] == item1: - print("Correct!") - flipped.add(self.flip(row1, column1, "correct")) - flipped.add(self.flip(row2, column2, "correct")) - else: - self.flip(row1, column1, "hide") - self.flip(row2, column2, "hide") - print("Try again, incorrect :(") - print("Congratulations, you win! You found all of the pairs!") - - def definemap(self): - # figure out potential heights and widths - divisors = [] - for i in range(len(self.memorder)): - if (len(self.memorder)) % (i + 1) == 0: - divisors.append(i + 1) - # gets the real width and height of map - width = divisors[len(divisors) // 2] - height = divisors[(len(divisors) // 2) - 1] - themap = [["# " for i in range(width)] for i in range(height)] - return themap - - def shuffle(self): - doneitems = {} - while len(self.memorder) > len(doneitems): - itemloc = random.randint(0, len(self.keys) - 1) - b = random.randint(0, 1) - memorderloc = random.randint(0, len(self.keys * 2) - 1) - if memorderloc not in doneitems.values(): - if b == 0 and self.memorder[memorderloc] not in self.keys: - self.memorder[memorderloc] = self.keys[itemloc] - doneitems[self.memorder[memorderloc]] = memorderloc - if b == 1 and self.memorder[memorderloc] not in self.values: - self.memorder[memorderloc] = self.values[itemloc] - doneitems[self.memorder[memorderloc]] = memorderloc - - def flip(self, row, column, operation): - if operation == "reveal": - self.currmap[row][column] = self.memorder[ - (row * len(self.currmap[0])) + column - ] - self.display() - return self.memorder[(row * len(self.currmap[0])) + column] - if operation == "hide": - self.currmap[row][column] = "# " - return None - if operation == "correct": - self.currmap[row][column] = "_ " - return self.memorder[(row * len(self.currmap[0])) + column] - - def display(self): - for i in range(len(self.currmap)): - print(self.currmap[i]) - - -mydiction = {"a": 1, "b": 2, "c": 3} - -letsplay = memcards(mydiction) diff --git a/2_intermediate/intermediateproject/memory_cards_prompt b/2_intermediate/intermediateproject/memory_cards_prompt deleted file mode 100644 index 6a9d7a5e..00000000 --- a/2_intermediate/intermediateproject/memory_cards_prompt +++ /dev/null @@ -1,13 +0,0 @@ -Follow these steps to create this algorithm. -1) Store words and definitions in a dictionary(or a list, if you want, depending on how you write the code). -2) Generate a grid(this should probably be in a 2D list) and fill it randomly with the words and definitions. -Display the grid and indicate that all cards are flipped down. -3) For every turn: -3a) Display the grid(showing which cards have been flipped up so far). -3ai) Define a function called display_grid() to do this. -3b) Ask the user to pick 2 locations(they should input the row and column of each position they choose). -If they pick a location with a card that’s already flipped up, ask them to pick again. -3c) Check whether the cards at the chosen locations are a matching word/definition pair. -Give the user a message telling them whether they chose correctly or not. -3d) Update the grid display, so that if the user guessed correctly, they’ll see empty spots on the grid display during the next turn. -4) Display a win message when the user has all the cards flipped up(when they’ve found all the word/definition pairs). diff --git a/2_intermediate/intermediateproject/vowel_exercise.py b/2_intermediate/intermediateproject/vowel_exercise.py deleted file mode 100644 index 2be16e72..00000000 --- a/2_intermediate/intermediateproject/vowel_exercise.py +++ /dev/null @@ -1,18 +0,0 @@ -words = ["Apple", "Orange", "Candles", "Kara", "orange"] - -output = [] -VOWEL_LIST = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"] -for elem in words: # Loops through every element in words - if len(elem) % 2 == 0 or elem[0] in VOWEL_LIST: - num_vowels = 0 - for char in elem: - if char in VOWEL_LIST: - num_vowels += 1 - output.append(num_vowels) - else: - num_consonants = 0 - for char in elem: - if char not in VOWEL_LIST: - num_consonants += 1 - output.append(num_consonants) -print(output) # Should print [2, 3, 5, 2, 3] in this case diff --git a/3_advanced/advancedproject/dice.py b/3_advanced/advancedproject/dice.py deleted file mode 100644 index 31da22a2..00000000 --- a/3_advanced/advancedproject/dice.py +++ /dev/null @@ -1,97 +0,0 @@ -# Daniel likes to get together with his friends every week on a -# random day to play dice. In his game of dice, the objective is -# to see who gets three of the same number first. - -# Algorithm Description: Use a class to represent a player. Create a -# turn log (using 2d list with each inner list containing the outcomes -# for all players representing a turn. Ex: [[1,2,4],[4,2,6]] ). -# Create a dictionary (that is an instance variable of the player -# class) to keep track of how many of each dice outcome each -# person playing the game got. For example, Daniel’s outcomes can -# look like {1:2, 2:3, 3:1, 4:0, 5:1, 6:2}. Once a person gets 3 -# of the same outcome, a unique statement will be created -# (the statement should be like "Player x won"). -# If multiple people won, it should be like "Player x, y won" - -# Follow these steps to create this algorithm. -# 1) Import the random module which we will be using later. - -# 2) Create a main class with -# --- instance variable in init: that asks the user for how many -# players and creates that many player classes -# --- instance variable in init: holding a list containing player -# (which is a class covered in the next section) instances based -# on how much the user inputted(so if user says 2 players playing, -# there should be 2 player instances in this list). -# --- instance variable in init: holding a turn log that should -# take each player's result each round (see in algorithm description) -# --- instance variable in init: holding the winners for this game -# --- instance variable in init: holding whether this game is over -# or not. -# --- a 'round' method that simulates one round of the game. so all -# the players should roll a random outcome(more in section 3). -# remember, every round, the turn log should be updated. -# also, check if the game has been won, and if it has, update the -# list containing the winners and the variable containing whether -# the game has been won. - -# 3) Create a player class with -# --- instance variable in init: holding the random dice outcome -# for the player for this round -# --- instance variable in init: holding a dictionary that -# stores how many times they got each outcome -# --- instance variable in init: that tracks whether the -# player has rolled 3 of the same thing(in other words won) or not. -# --- a 'roll' method that determines the random outcome for the player -# (dice: a random int between 0 and 6 inclusive) and also whether the -# player won this round or not. - -# At the end run the main class by doing main(). Running main() -# should print the turn log and print which player(s) won. - -import random - - -class main: - def __init__(self): - self.playercount = int(input("How many players are playing? ")) - self.turnlog = [] - self.players = [player() for i in range(self.playercount)] - self.winners = [] - self.over = False - - print( - "Note: player 0 is the first player, " - + "player 1 is the second player, etc" - ) - while not self.over: - self.round() - print("This is the record of the game") - print(self.turnlog) - print("Player(s)", str(self.winners).lstrip("[").rstrip("]"), "won") - - def round(self): - for i in range(self.playercount): - self.players[i].roll() - if self.players[i].win: - self.winners.append(i) - self.over = True - self.turnlog.append( - [self.players[x].thisround for x in range(self.playercount)] - ) - - -class player: - def __init__(self): - self.thisround = None - self.outcomes = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} - self.win = False - - def roll(self): - self.thisround = random.randint(1, 6) - self.outcomes[self.thisround] += 1 - if 3 in self.outcomes.values(): - self.win = True - - -letsplay = main() diff --git a/3_advanced/chapter13/examples/filler b/3_advanced/chapter13/examples/filler deleted file mode 100644 index a27d933f..00000000 --- a/3_advanced/chapter13/examples/filler +++ /dev/null @@ -1 +0,0 @@ -#This is filler. Remove later. 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/filler b/3_advanced/chapter14/examples/filler deleted file mode 100644 index 644012f7..00000000 --- a/3_advanced/chapter14/examples/filler +++ /dev/null @@ -1 +0,0 @@ -#This is filler content. You can only add 1 folder at a time? 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/filler b/3_advanced/chapter14/practice/filler deleted file mode 100644 index 8f31d373..00000000 --- a/3_advanced/chapter14/practice/filler +++ /dev/null @@ -1 +0,0 @@ -This is filler content. You can only add 1 folder at a time? diff --git a/3_advanced/chapter14/solutions/filler b/3_advanced/chapter14/solutions/filler deleted file mode 100644 index 8f31d373..00000000 --- a/3_advanced/chapter14/solutions/filler +++ /dev/null @@ -1 +0,0 @@ -This is filler content. You can only add 1 folder at a time? diff --git a/3_advanced/chapter14/solutions/odd_squares.py b/3_advanced/chapter14/solutions/odd_squares.py index 1e385094..4a4dfd74 100644 --- a/3_advanced/chapter14/solutions/odd_squares.py +++ b/3_advanced/chapter14/solutions/odd_squares.py @@ -10,4 +10,4 @@ ex_list[idx] = int(ex_list[idx]) # write your code below -odds_quares = [n ** 2 for n in list if n % 2 == 1] +odds_quares = [n**2 for n in list if n % 2 == 1] 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/filler b/3_advanced/chapter15/examples/filler deleted file mode 100644 index 644012f7..00000000 --- a/3_advanced/chapter15/examples/filler +++ /dev/null @@ -1 +0,0 @@ -#This is filler content. You can only add 1 folder at a time? 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/chapter16/practice/ch16_practice1.py b/3_advanced/chapter15/practice/ch15_practice1.py similarity index 100% rename from 3_advanced/chapter16/practice/ch16_practice1.py rename to 3_advanced/chapter15/practice/ch15_practice1.py diff --git a/3_advanced/chapter16/practice/ch16_practice2.py b/3_advanced/chapter15/practice/ch15_practice2.py similarity index 96% rename from 3_advanced/chapter16/practice/ch16_practice2.py rename to 3_advanced/chapter15/practice/ch15_practice2.py index 3bf1ccfe..9e886b2e 100644 --- a/3_advanced/chapter16/practice/ch16_practice2.py +++ b/3_advanced/chapter15/practice/ch15_practice2.py @@ -1,19 +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 -""" +""" +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/chapter16/practice/ch16_practice3.py b/3_advanced/chapter15/practice/ch15_practice3.py similarity index 96% rename from 3_advanced/chapter16/practice/ch16_practice3.py rename to 3_advanced/chapter15/practice/ch15_practice3.py index d8f26f99..582bf665 100644 --- a/3_advanced/chapter16/practice/ch16_practice3.py +++ b/3_advanced/chapter15/practice/ch15_practice3.py @@ -1,20 +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) -""" +""" +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/chapter16/practice/ch16_practice4.py b/3_advanced/chapter15/practice/ch15_practice4.py similarity index 53% rename from 3_advanced/chapter16/practice/ch16_practice4.py rename to 3_advanced/chapter15/practice/ch15_practice4.py index 7ecd7d08..ebf66abd 100644 --- a/3_advanced/chapter16/practice/ch16_practice4.py +++ b/3_advanced/chapter15/practice/ch15_practice4.py @@ -1,28 +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) -#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. -""" +""" +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/chapter16/practice/ch16_practice5.py b/3_advanced/chapter15/practice/ch15_practice5.py similarity index 96% rename from 3_advanced/chapter16/practice/ch16_practice5.py rename to 3_advanced/chapter15/practice/ch15_practice5.py index 961452a8..8e456b10 100644 --- a/3_advanced/chapter16/practice/ch16_practice5.py +++ b/3_advanced/chapter15/practice/ch15_practice5.py @@ -1,18 +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) -""" +""" +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/practice/filler b/3_advanced/chapter15/practice/filler deleted file mode 100644 index 644012f7..00000000 --- a/3_advanced/chapter15/practice/filler +++ /dev/null @@ -1 +0,0 @@ -#This is filler content. You can only add 1 folder at a time? diff --git a/3_advanced/chapter16/solutions/ch16_practice1.py b/3_advanced/chapter15/solutions/ch15_practice1.py similarity index 100% rename from 3_advanced/chapter16/solutions/ch16_practice1.py rename to 3_advanced/chapter15/solutions/ch15_practice1.py diff --git a/3_advanced/chapter16/solutions/ch16_practice2.py b/3_advanced/chapter15/solutions/ch15_practice2.py similarity index 100% rename from 3_advanced/chapter16/solutions/ch16_practice2.py rename to 3_advanced/chapter15/solutions/ch15_practice2.py diff --git a/3_advanced/chapter16/solutions/ch16_practice3.py b/3_advanced/chapter15/solutions/ch15_practice3.py similarity index 96% rename from 3_advanced/chapter16/solutions/ch16_practice3.py rename to 3_advanced/chapter15/solutions/ch15_practice3.py index 02164783..94f6739d 100644 --- a/3_advanced/chapter16/solutions/ch16_practice3.py +++ b/3_advanced/chapter15/solutions/ch15_practice3.py @@ -1,21 +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) -""" +""" +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/chapter16/solutions/ch16_practice4.py b/3_advanced/chapter15/solutions/ch15_practice4.py similarity index 97% rename from 3_advanced/chapter16/solutions/ch16_practice4.py rename to 3_advanced/chapter15/solutions/ch15_practice4.py index 93c726e5..29e88c25 100644 --- a/3_advanced/chapter16/solutions/ch16_practice4.py +++ b/3_advanced/chapter15/solutions/ch15_practice4.py @@ -1,28 +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. -""" +""" +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/chapter16/solutions/ch16_practice5.py b/3_advanced/chapter15/solutions/ch15_practice5.py similarity index 97% rename from 3_advanced/chapter16/solutions/ch16_practice5.py rename to 3_advanced/chapter15/solutions/ch15_practice5.py index d65635fc..a56efd4d 100644 --- a/3_advanced/chapter16/solutions/ch16_practice5.py +++ b/3_advanced/chapter15/solutions/ch15_practice5.py @@ -1,23 +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. -""" +""" +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/chapter15/solutions/filler b/3_advanced/chapter15/solutions/filler deleted file mode 100644 index 644012f7..00000000 --- a/3_advanced/chapter15/solutions/filler +++ /dev/null @@ -1 +0,0 @@ -#This is filler content. You can only add 1 folder at a time? diff --git a/3_advanced/chapter15/examples/Selection Sort Code.py b/3_advanced/chapter16/examples/Selection Sort Code.py similarity index 97% rename from 3_advanced/chapter15/examples/Selection Sort Code.py rename to 3_advanced/chapter16/examples/Selection Sort Code.py index 4a2411cc..dc919a08 100644 --- a/3_advanced/chapter15/examples/Selection Sort Code.py +++ b/3_advanced/chapter16/examples/Selection Sort Code.py @@ -1,9 +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) +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/examples/filler b/3_advanced/chapter16/examples/filler deleted file mode 100644 index 8c040cb1..00000000 --- a/3_advanced/chapter16/examples/filler +++ /dev/null @@ -1 +0,0 @@ -#Filler Content. Will Remove later diff --git a/3_advanced/chapter15/practice/selection_sort_even.py b/3_advanced/chapter16/practice/selection_sort_even.py similarity index 96% rename from 3_advanced/chapter15/practice/selection_sort_even.py rename to 3_advanced/chapter16/practice/selection_sort_even.py index 27cd2859..2be5473c 100644 --- a/3_advanced/chapter15/practice/selection_sort_even.py +++ b/3_advanced/chapter16/practice/selection_sort_even.py @@ -1,18 +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 +""" +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/chapter15/practice/selection_sort_f3.py b/3_advanced/chapter16/practice/selection_sort_f3.py similarity index 96% rename from 3_advanced/chapter15/practice/selection_sort_f3.py rename to 3_advanced/chapter16/practice/selection_sort_f3.py index 1c3a6ac4..3fb8c4d5 100644 --- a/3_advanced/chapter15/practice/selection_sort_f3.py +++ b/3_advanced/chapter16/practice/selection_sort_f3.py @@ -1,18 +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 +""" +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/chapter15/practice/selection_sort_gtl.py b/3_advanced/chapter16/practice/selection_sort_gtl.py similarity index 96% rename from 3_advanced/chapter15/practice/selection_sort_gtl.py rename to 3_advanced/chapter16/practice/selection_sort_gtl.py index 876507c6..52459438 100644 --- a/3_advanced/chapter15/practice/selection_sort_gtl.py +++ b/3_advanced/chapter16/practice/selection_sort_gtl.py @@ -1,17 +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 +""" +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/chapter15/solutions/selection_sort_even.py b/3_advanced/chapter16/solutions/selection_sort_even.py similarity index 96% rename from 3_advanced/chapter15/solutions/selection_sort_even.py rename to 3_advanced/chapter16/solutions/selection_sort_even.py index 06c96dbb..5e23944e 100644 --- a/3_advanced/chapter15/solutions/selection_sort_even.py +++ b/3_advanced/chapter16/solutions/selection_sort_even.py @@ -1,28 +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) +""" +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/chapter15/solutions/selection_sort_f3.py b/3_advanced/chapter16/solutions/selection_sort_f3.py similarity index 97% rename from 3_advanced/chapter15/solutions/selection_sort_f3.py rename to 3_advanced/chapter16/solutions/selection_sort_f3.py index ed3190c1..8fabd885 100644 --- a/3_advanced/chapter15/solutions/selection_sort_f3.py +++ b/3_advanced/chapter16/solutions/selection_sort_f3.py @@ -1,30 +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 +""" +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/chapter15/solutions/selection_sort_gtl.py b/3_advanced/chapter16/solutions/selection_sort_gtl.py similarity index 96% rename from 3_advanced/chapter15/solutions/selection_sort_gtl.py rename to 3_advanced/chapter16/solutions/selection_sort_gtl.py index 26ac4bcc..425e064b 100644 --- a/3_advanced/chapter15/solutions/selection_sort_gtl.py +++ b/3_advanced/chapter16/solutions/selection_sort_gtl.py @@ -1,26 +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) +""" +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/sets.py b/3_advanced/chapter17/examples/sets.py index 7f10ef71..7cb86a04 100644 --- a/3_advanced/chapter17/examples/sets.py +++ b/3_advanced/chapter17/examples/sets.py @@ -39,7 +39,7 @@ # 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.symettricdifference(set2)) +print(set1.symmetric_difference(set2)) # will print 1,2,3,4,5,6,7 since those are the unique items print(set1.union(set2)) diff --git a/3_advanced/chapter17/examples/tuples.py b/3_advanced/chapter17/examples/tuples.py index bfe29486..cc41a975 100644 --- a/3_advanced/chapter17/examples/tuples.py +++ b/3_advanced/chapter17/examples/tuples.py @@ -1,8 +1,20 @@ # 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]) @@ -12,6 +24,7 @@ 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) diff --git a/3_advanced/chapter17/solutions/min_superset.py b/3_advanced/chapter17/solutions/min_superset.py index cce07d80..e7b55ff7 100644 --- a/3_advanced/chapter17/solutions/min_superset.py +++ b/3_advanced/chapter17/solutions/min_superset.py @@ -2,6 +2,7 @@ # 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): diff --git a/3_advanced/chapter18/examples/binary_search.py b/3_advanced/chapter18/examples/binary_search.py index 2b98e198..c14336b5 100644 --- a/3_advanced/chapter18/examples/binary_search.py +++ b/3_advanced/chapter18/examples/binary_search.py @@ -1,29 +1,29 @@ # Code for binary search -def binary_search(arr, low, high, x): +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)x is the element we are trying to find the index of + 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 x in the array arr. + 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. """ - while high >= low: + if high >= low: mid = (high + low) // 2 - if arr[mid] == x: # Base Case 1 + if arr[mid] == key: # Base Case 1 return mid - elif arr[mid] < x: # Recursive Case 1 - return binary_search(arr, mid + 1, high, x) - else: # Recursive Case 2 - return binary_search(arr, low, mid - 1, x) + 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 diff --git a/3_advanced/chapter18/examples/fibonacci.py b/3_advanced/chapter18/examples/fibonacci.py index 0c0cadc4..d881582b 100644 --- a/3_advanced/chapter18/examples/fibonacci.py +++ b/3_advanced/chapter18/examples/fibonacci.py @@ -1,22 +1,79 @@ -# Code for finding the nth term in the Fibonacci sequence +# 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 fibonacci(n): +def recursive_fib(n): + """ + Returns the nth number in the Fibonacci sequence recursively - # Parameter: n is the position of the number in the Fibonacci sequence. - # Output: The nth number of the Fibonacci sequence will be outputted. + Args: + n (int): the position of the number in the Fibonacci sequence you want - # fibonacci(5) means we are finding the 5th fibonacci number - # in the fiboacci sequence going from the left - - if n < 0: # Base Case 1: out of bounds - return "Does not exist" - elif n == 1: # Base Case 2: first number is 0 + 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: second number is 1 + elif n == 2: # Base Case 3 return 1 - else: # Recursive Case: - return fibonacci(n - 1) + fibonacci(n - 2) + 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(fibonacci(5)) +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/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/type_checker.py b/3_advanced/chapter19/practice/type_checker.py index 68609a01..da688d35 100644 --- a/3_advanced/chapter19/practice/type_checker.py +++ b/3_advanced/chapter19/practice/type_checker.py @@ -1,4 +1,7 @@ -# Create a function that takes one argument and multiplies it by 4. +# 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. @@ -7,6 +10,6 @@ def type_checker(x): pass # remove this -arg_list = [4, "hi", "obviously NAN", 5.6] +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/list_practice.py b/3_advanced/chapter19/solutions/list_practice.py index d1ee1a46..a86e9dd6 100644 --- a/3_advanced/chapter19/solutions/list_practice.py +++ b/3_advanced/chapter19/solutions/list_practice.py @@ -19,14 +19,13 @@ def list_practice(): 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" + "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" + "press q to quit, input a number to access that value of" + + " the list" ) except ValueError: print("That's not a number") diff --git a/3_advanced/chapter19/solutions/type_checker.py b/3_advanced/chapter19/solutions/type_checker.py index 38e14e96..a5456e81 100644 --- a/3_advanced/chapter19/solutions/type_checker.py +++ b/3_advanced/chapter19/solutions/type_checker.py @@ -1,15 +1,21 @@ -# Create a function that takes one argument and prints arg * 4. +# 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 * 4) + 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] +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 = '