From d7895a868da6aa3fc02d6f53eb4a3d806be8b2ea Mon Sep 17 00:00:00 2001 From: mciorast Date: Wed, 19 Nov 2025 11:36:44 +0200 Subject: [PATCH] done with end of chapter4 and entire chapter5 --- chapter4-exercices/chapter4_10_ex.py | 47 +++++++++ chapter4-exercices/chapter4_12_ex.py | 11 +++ chapter4-exercices/chapter4_13_ex.py | 22 +++++ chapter4-exercices/chapter4_14_ex.py | 142 +++++++++++++++++++++++++++ chapter4-exercices/chapter4_15_ex.py | 6 ++ chapter4-exercices/chapter4_18_ex.py | 9 ++ chapter4-exercices/chapter4_19_ex.py | 16 +++ chapter4-exercices/chapter4_9_ex.py | 20 ++++ chapter5-exercices/chapter5_01_ex.py | 14 +++ chapter5-exercices/chapter5_02_ex.py | 16 +++ chapter5-exercices/chapter5_03_ex.py | 4 + chapter5-exercices/chapter5_04_ex.py | 11 +++ chapter5-exercices/chapter5_05_ex.py | 7 ++ chapter5-exercices/chapter5_06_ex.py | 23 +++++ chapter5-exercices/chapter5_07_ex.py | 15 +++ chapter5-exercices/chapter5_08_ex.py | 12 +++ chapter5-exercices/chapter5_09_ex.py | 12 +++ chapter5-exercices/chapter5_10_ex.py | 23 +++++ chapter5-exercices/chapter5_11_ex.py | 5 + chapter5-exercices/chapter5_12_ex.py | 18 ++++ chapter5-exercices/chapter5_13_ex.py | 31 ++++++ chapter5-exercices/chapter5_14_ex.py | 52 ++++++++++ chapter5-exercices/chapter5_15_ex.py | 24 +++++ chapter5-exercices/chapter5_16_ex.py | 53 ++++++++++ chapter5-exercices/chapter5_17_ex.py | 9 ++ chapter5-exercices/chapter5_18_ex.py | 19 ++++ chapter5-exercices/chapter5_19_ex.py | 31 ++++++ chapter5-exercices/chapter5_1_ex.py | 16 +++ chapter5-exercices/chapter5_20_ex.py | 9 ++ chapter5-exercices/chapter5_21_ex.py | 25 +++++ chapter5-exercices/chapter5_22_ex.py | 18 ++++ chapter5-exercices/chapter5_23_ex.py | 45 +++++++++ chapter5-exercices/chapter5_24_ex.py | 117 ++++++++++++++++++++++ chapter5-exercices/chapter5_25_ex.py | 9 ++ chapter5-exercices/chapter5_26_ex.py | 40 ++++++++ chapter5-exercices/chapter5_27_ex.py | 31 ++++++ chapter5-exercices/chapter5_2_ex.py | 36 +++++++ chapter5-exercices/chapter5_3_ex.py | 32 ++++++ chapter5-exercices/chapter5_4_ex.py | 33 +++++++ chapter5-exercices/chapter5_5_ex.py | 18 ++++ chapter5-exercices/chapter5_6_ex.py | 57 +++++++++++ chapter5-exercices/chapter5_7_ex.py | 32 ++++++ chapter5-exercices/chapter5_8_ex.py | 14 +++ chapter5-exercices/chapter5_9_ex.py | 18 ++++ 44 files changed, 1202 insertions(+) create mode 100755 chapter4-exercices/chapter4_10_ex.py create mode 100644 chapter4-exercices/chapter4_12_ex.py create mode 100755 chapter4-exercices/chapter4_13_ex.py create mode 100755 chapter4-exercices/chapter4_14_ex.py create mode 100644 chapter4-exercices/chapter4_15_ex.py create mode 100644 chapter4-exercices/chapter4_18_ex.py create mode 100644 chapter4-exercices/chapter4_19_ex.py create mode 100755 chapter4-exercices/chapter4_9_ex.py create mode 100755 chapter5-exercices/chapter5_01_ex.py create mode 100755 chapter5-exercices/chapter5_02_ex.py create mode 100755 chapter5-exercices/chapter5_03_ex.py create mode 100755 chapter5-exercices/chapter5_04_ex.py create mode 100755 chapter5-exercices/chapter5_05_ex.py create mode 100755 chapter5-exercices/chapter5_06_ex.py create mode 100755 chapter5-exercices/chapter5_07_ex.py create mode 100755 chapter5-exercices/chapter5_08_ex.py create mode 100755 chapter5-exercices/chapter5_09_ex.py create mode 100755 chapter5-exercices/chapter5_10_ex.py create mode 100644 chapter5-exercices/chapter5_11_ex.py create mode 100755 chapter5-exercices/chapter5_12_ex.py create mode 100755 chapter5-exercices/chapter5_13_ex.py create mode 100755 chapter5-exercices/chapter5_14_ex.py create mode 100755 chapter5-exercices/chapter5_15_ex.py create mode 100755 chapter5-exercices/chapter5_16_ex.py create mode 100755 chapter5-exercices/chapter5_17_ex.py create mode 100755 chapter5-exercices/chapter5_18_ex.py create mode 100755 chapter5-exercices/chapter5_19_ex.py create mode 100755 chapter5-exercices/chapter5_1_ex.py create mode 100644 chapter5-exercices/chapter5_20_ex.py create mode 100755 chapter5-exercices/chapter5_21_ex.py create mode 100644 chapter5-exercices/chapter5_22_ex.py create mode 100755 chapter5-exercices/chapter5_23_ex.py create mode 100755 chapter5-exercices/chapter5_24_ex.py create mode 100755 chapter5-exercices/chapter5_25_ex.py create mode 100755 chapter5-exercices/chapter5_26_ex.py create mode 100755 chapter5-exercices/chapter5_27_ex.py create mode 100755 chapter5-exercices/chapter5_2_ex.py create mode 100755 chapter5-exercices/chapter5_3_ex.py create mode 100755 chapter5-exercices/chapter5_4_ex.py create mode 100755 chapter5-exercices/chapter5_5_ex.py create mode 100755 chapter5-exercices/chapter5_6_ex.py create mode 100755 chapter5-exercices/chapter5_7_ex.py create mode 100755 chapter5-exercices/chapter5_8_ex.py create mode 100755 chapter5-exercices/chapter5_9_ex.py diff --git a/chapter4-exercices/chapter4_10_ex.py b/chapter4-exercices/chapter4_10_ex.py new file mode 100755 index 0000000..7d58661 --- /dev/null +++ b/chapter4-exercices/chapter4_10_ex.py @@ -0,0 +1,47 @@ +""" (Guess the Number) + Write a script that plays “guess the number.” Choose the number to be guessed by selecting a random integer in the range 1 to 1000. + Do not reveal this number to the user. + Display the prompt "Guess my number between 1 and 1000 with the fewest guesses:". + The player inputs a first guess. If the guess is incorrect, display "Too high. Try again." or "Too low. Try again." + as appropriate to help the player “zero in” on the correct answer, then prompt the user for the next guess. + When the user enters the correct answer, display "Congratulations. + You guessed the number!", and allow the user to choose whether to play again. """ + +import random as rnd + +def random_number(): + """ method to generate a random number between 1 and 1000 """ + return rnd.randrange(1, 1000) + +number = (random_number()) + +def guess_gen_number(): + """ method to ask the user to guess the randomly generated number between 1 and 1000 """ + guess_number = float(input("Guess my number between 1 and 1000: ")) + while guess_number > 0: + tries_left = 0 + tries_right = 0 + left_end = 1 + right_end = 1000 + if guess_number > number: + print(f"Too high. Please try again. Be aware that the interval changed between {left_end} and {right_end}.") + tries_right += 1 + right_end = guess_number + guess_number = float(input(f"Guess my number between {left_end} and {right_end}: ")) + elif guess_number < number: + print(f"Too low. Please try again. Be aware that the interval changed between {left_end} and {right_end}.") + tries_left += 1 + left_end = guess_number + guess_number = float(input(f"Guess my number between {left_end} and {right_end}: ")) + elif guess_number == number: + tries = 1 + tries_right + tries_left + print(f"Congratulations!! You guessed the number in about {tries} tries.") + break + return tries + +tries_number = guess_number = guess_gen_number() + +if tries_number < 10: + print("Either you know the secret or you got lucky!") +else: + print("You should be able to do better!") diff --git a/chapter4-exercices/chapter4_12_ex.py b/chapter4-exercices/chapter4_12_ex.py new file mode 100644 index 0000000..6c7002c --- /dev/null +++ b/chapter4-exercices/chapter4_12_ex.py @@ -0,0 +1,11 @@ +""" Simulation: The Tortoise and the Hare) In this problem, you’ll re-create the classic race of the tortoise and the hare. + You’ll use random-number generation to develop a simulation of this memorable event. + + Our contenders begin the race at square 1 of 70 squares. Each square represents a position along the race course. + The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. + The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground. + + A clock ticks once per second. With each tick of the clock, your application should adjust the position of the animals according to the rules in the table below. + Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70). + Start each animal at position 1 (the “starting gate”). If an animal slips left before square 1, move it back to square 1. """ + diff --git a/chapter4-exercices/chapter4_13_ex.py b/chapter4-exercices/chapter4_13_ex.py new file mode 100755 index 0000000..370730c --- /dev/null +++ b/chapter4-exercices/chapter4_13_ex.py @@ -0,0 +1,22 @@ +""" (Arbitrary Argument List) + Calculate the product of a series of integers that are passed to the function product, which receives an arbitrary argument list. + Test your function with several calls, each with a different number of arguments. """ +import random + +len_numbers = len(range(random.randrange(1,101))) + + + +a = [] + +for x in range(len_numbers): + a.append(random.randrange(random.randrange(1,101))) + +def product_of_numbers(*args): + product = 1 + for i in args: + product *= i + return print(f'List of numbers = {args}\nThe product of these numbers is {product}') + +product_of_numbers(*a) + diff --git a/chapter4-exercices/chapter4_14_ex.py b/chapter4-exercices/chapter4_14_ex.py new file mode 100755 index 0000000..8ff74c8 --- /dev/null +++ b/chapter4-exercices/chapter4_14_ex.py @@ -0,0 +1,142 @@ +""" (Computer-Assisted Instruction) + Computer-assisted instruction (CAI) refers to the use of computers in education. + Write a script to help an elementary school student learn multiplication. + Create a function that randomly generates and returns a tuple of two positive one-digit integers. + Use that function’s result in your script to prompt the user with a question, such as + + How much is 6 times 7? + + For a correct answer, display the message "Very good!" and ask another multiplication question. + For an incorrect answer, display the message "No. + Please try again." and let the student try the same question repeatedly until the student finally gets it right. """ + +import random as rnd + +variables = (rnd.randrange(10), rnd.randrange(10)) +choice = int(input('Which type of calculations do you need/want to perform with a single digit?\nFor addition press 1\nFor subtraction press 2\nFor multiplication press 3\nFor division press 4\n')) + +#initialization phase for multiplication +def elementary_multiplication(args): + var1, var2 = args + print(var1, var2) + product = var1 * var2 + result = float(input(f'How much is {var1} times {var2}?')) + + if result == product: + print('Verry good!') + else: + print('No. Please try again.') + + while result != product: + result = float(input(f'How much is {var1} times {var2}?')) + if result == product: + print('Verry good!') + break + want_continuation = str(input('Would you like to continue with more examples (yes/no)?')) + choice = int(input('Which type of calculations do you need/want to perform with a single digit?\nFor addition press 1\nFor subtraction press 2\nFor multiplication press 3\nFor division press 4\n')) + + return choice, want_continuation + +#initialization phase for addition +def elementary_addition(args): + var1, var2 = args + print(var1, var2) + addition = var1 + var2 + result = float(input(f'How much is {var1} added with {var2}?')) + + if result == addition: + print('Verry good!') + else: + print('No. Please try again.') + + while result != addition: + result = float(input(f'How much is {var1} added with {var2}?')) + if result == addition: + print('Verry good!') + break + want_continuation = str(input('Would you like to continue with more examples (yes/no)?')) + choice = int(input('Which type of calculations do you need/want to perform with a single digit?\nFor addition press 1\nFor subtraction press 2\nFor multiplication press 3\nFor division press 4\n')) + return choice, want_continuation + +#initialization phase for subtraction +def elementary_subtraction(args): + var1, var2 = args + print(var1, var2) + if var1 > var2: + subtraction = var1 - var2 + result = float(input(f'How much is {var1} minus {var2}?')) + else: + subtraction = var2 - var1 + result = float(input(f'How much is {var2} minus {var1}?')) + + + if result == subtraction: + print('Verry good!') + else: + print('No. Please try again.') + + while result != subtraction: + if var1 > var2: + subtraction = var1 - var2 + result = float(input(f'How much is {var1} minus {var2}?')) + else: + subtraction = var2 - var1 + result = float(input(f'How much is {var2} minus {var1}?')) + + if result == subtraction: + print('Verry good!') + break + want_continuation = str(input('Would you like to continue with more examples (yes/no)?')) + choice = int(input('Which type of calculations do you need/want to perform with a single digit?\nFor addition press 1\nFor subtraction press 2\nFor multiplication press 3\nFor division press 4\n')) + return choice, want_continuation + +#initialization phase for division +def elementary_division(args): + var1, var2 = args + print(var1, var2) + if var1 > var2: + division = var1 / var2 + result = float(input(f'How much is {var1} divided by {var2}?')) + else: + division = var2 / var1 + result = float(input(f'How much is {var2} divided by {var1}?')) + + if result == division: + print('Verry good!') + else: + print('No. Please try again.') + + while result != division: + if var1 > var2: + division = var1 / var2 + result = float(input(f'How much is {var1} divided by {var2}?')) + else: + division = var2 / var1 + result = float(input(f'How much is {var2} divided by {var1}?')) + + if result == division: + print('Verry good!') + break + want_continuation = str(input('Would you like to continue with more examples (yes/no)?')) + choice = int(input('Which type of calculations do you need/want to perform with a single digit?\nFor addition press 1\nFor subtraction press 2\nFor multiplication press 3\nFor division press 4\n')) + return choice, want_continuation + + +while choice in range(1,5): + if choice == 1: + choice_1 = elementary_addition(variables) + variables = (rnd.randrange(10), rnd.randrange(10)) + if choice == 2: + choice_2 = elementary_subtraction(variables) + variables = (rnd.randrange(10), rnd.randrange(10)) + if choice == 3: + choice_3 = elementary_multiplication(variables) + variables = (rnd.randrange(10), rnd.randrange(10)) + if choice == 4: + choice_4 = elementary_division(variables) + variables = (rnd.randrange(10), rnd.randrange(10)) + if choice == 0: + break + else: + print('Not a valid input. Please try again..\nBe aware that for ending type "0".') + diff --git a/chapter4-exercices/chapter4_15_ex.py b/chapter4-exercices/chapter4_15_ex.py new file mode 100644 index 0000000..7080f1d --- /dev/null +++ b/chapter4-exercices/chapter4_15_ex.py @@ -0,0 +1,6 @@ +""" (Computer-Assisted Instruction: Reducing Student Fatigue) + Varying the computer’s responses can help hold the student’s attention. + Modify the previous exercise so that various comments are displayed for each answer. + Possible responses to a correct answer should include 'Very good!', 'Nice work!' and 'Keep up the good work!' + Possible responses to an incorrect answer should include 'No. Please try again.', 'Wrong. Try once more.' and 'No. Keep trying.' + Choose a number from 1 to 3, then use that value to select one of the three appropriate responses to each correct or incorrect answer. """ \ No newline at end of file diff --git a/chapter4-exercices/chapter4_18_ex.py b/chapter4-exercices/chapter4_18_ex.py new file mode 100644 index 0000000..a47762f --- /dev/null +++ b/chapter4-exercices/chapter4_18_ex.py @@ -0,0 +1,9 @@ +""" (Functional-Style Programming: Internal vs. External Iteration) Why is internal iteration preferable to external iteration in functional-style programming? + + Answer: + External iteration means you (the programmer) control the iteration explicitly — e.g., + using a for or while loop. You tell the program when to move to the next element, when to stop, etc. This is imperative style. + + Internal iteration means you hand over the control of iteration to the library/framework — e.g., + calling .forEach(), .map(), .filter(), or a stream operation. You only provide the behavior (the function to apply), + and the library decides how to loop internally. This is functional style. """ \ No newline at end of file diff --git a/chapter4-exercices/chapter4_19_ex.py b/chapter4-exercices/chapter4_19_ex.py new file mode 100644 index 0000000..a374e9d --- /dev/null +++ b/chapter4-exercices/chapter4_19_ex.py @@ -0,0 +1,16 @@ +""" (Functional-Style Programming: What vs. How) + Why is programming that emphasizes “what” preferable to programming that emphasizes “how”? + What is it that makes “what” programming feasible? + + Answer: The how is likely reinventing the wheel.. which is not that feasible. + + 1. Why “what” (declarative) is preferable to “how” (imperative): + Clarity & readability: You describe what you want (the goal), not the low-level steps to get there. + Less error-prone: No need to manually manage indexes, states, or loop control. + Easier optimization & parallelization: Since the system controls how execution happens, it can automatically choose efficient strategies (e.g., parallel streams, SQL query optimizers). + Maintainability: Code is shorter, easier to change, and closer to natural problem descriptions. + + 2. What makes “what” programming feasible: + Higher-level abstractions like functions (map, filter, reduce), streams, and query languages hide the low-level iteration. + Powerful libraries/runtimes implement the “how” efficiently (so you don’t have to). + Immutability and pure functions allow these operations to be safely optimized and parallelized. """ \ No newline at end of file diff --git a/chapter4-exercices/chapter4_9_ex.py b/chapter4-exercices/chapter4_9_ex.py new file mode 100755 index 0000000..acf0b39 --- /dev/null +++ b/chapter4-exercices/chapter4_9_ex.py @@ -0,0 +1,20 @@ +""" (Temperature Conversion) Implement a Fahrenheit function that returns the Fahrenheit equivalent of a Celsius temperature. + Use the following formula: + + F = (9 / 5) * C + 32 + + Use this function to print a chart showing the Fahrenheit equivalents of all Celsius temperatures in the range 0–100 degrees. + Use one digit of precision for the results. Print the outputs in a neat tabular format. """ + +celsius_list = list(range(0, 101)) +Fahrenheit_list = [] + +def fahrenheit(*args): + for value in args: + F = (9 / 5) * value + 32 + cel_to_fa = round(F, 1) + Fahrenheit_list.append(cel_to_fa) + return print(f'Fahrenheit list of all the first 100 degrees is {Fahrenheit_list}') + +fahrenheit(*celsius_list) + diff --git a/chapter5-exercices/chapter5_01_ex.py b/chapter5-exercices/chapter5_01_ex.py new file mode 100755 index 0000000..b74e7ec --- /dev/null +++ b/chapter5-exercices/chapter5_01_ex.py @@ -0,0 +1,14 @@ +""" Create a function cube_list that cubes each element of a list. + Call the function with the list numbers containing 1 through 10. + Show numbers after the call. """ + + +def cube_list(args): + a = [] + for num in range(len(args)): + a.append(args[num] ** 3) + return print(a) + +numbers = [x for x in range(1, 11)] + +cube_list(numbers) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_02_ex.py b/chapter5-exercices/chapter5_02_ex.py new file mode 100755 index 0000000..67a222b --- /dev/null +++ b/chapter5-exercices/chapter5_02_ex.py @@ -0,0 +1,16 @@ +""" Use an empty list named characters and a += augmented assignment statement to convert the string 'Birthday' into a list of its characters. """ + + + + + +def convert_string_in_list(*args): + """ converting a string into a list of its characters. """ + characters = [] + for character in range(len(args)): + characters.append(args[character].lower()) + return characters + +strings = 'Birthday' + +print(convert_string_in_list(*strings)) diff --git a/chapter5-exercices/chapter5_03_ex.py b/chapter5-exercices/chapter5_03_ex.py new file mode 100755 index 0000000..1a90582 --- /dev/null +++ b/chapter5-exercices/chapter5_03_ex.py @@ -0,0 +1,4 @@ +""" Create a single-element tuple containing 123.45, then display it. """ + +single_tuple_element = (123.45, ) +print(single_tuple_element) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_04_ex.py b/chapter5-exercices/chapter5_04_ex.py new file mode 100755 index 0000000..fef8644 --- /dev/null +++ b/chapter5-exercices/chapter5_04_ex.py @@ -0,0 +1,11 @@ +""" Create a tuple high_low representing a day of the week (a string) and its high and low temperatures (integers), + display its string representation, then perform the following tasks in an interactive IPython session: + + Use the [] operator to access and display the high_low tuple’s elements. + + Unpack the high_low tuple into the variables day and high. + What happens and why? """ + +high_low = ('Monday', (21, 30)) +day, high = high_low +print(f"It's {day} and the temperatures are between the followings: High: {high[0]} - Low: {high[1]}") diff --git a/chapter5-exercices/chapter5_05_ex.py b/chapter5-exercices/chapter5_05_ex.py new file mode 100755 index 0000000..286b433 --- /dev/null +++ b/chapter5-exercices/chapter5_05_ex.py @@ -0,0 +1,7 @@ +""" Create the list names containing three name strings. + Use a for loop and the enumerate function to iterate through the elements and display each element’s index and value. """ + +names = ('Marian', 'John', 'Vladimir', 'Emilian') + +for index, name in enumerate(names): + print(f'{index:>2} {name}') \ No newline at end of file diff --git a/chapter5-exercices/chapter5_06_ex.py b/chapter5-exercices/chapter5_06_ex.py new file mode 100755 index 0000000..40208ed --- /dev/null +++ b/chapter5-exercices/chapter5_06_ex.py @@ -0,0 +1,23 @@ +""" Create a list called numbers containing the values from 1 through 15, then use slices to perform the following operations consecutively: + Select number’s even integers. + Replace the elements at indices 5 through 9 with 0s, then show the resulting list. + Keep only the first five elements, then show the resulting list. + Delete all the remaining elements by assigning to a slice. Show the resulting list. """ + +#Create a list called numbers containing the values from 1 through 15 +numbers = list(range(1,16)) +print(f'Create a list called numbers containing the values from 1 through 15: {numbers}') + +#Select number’s even integers. +print(f'Select number’s even integers. {numbers[1:len(numbers):2]}') + +#Replace the elements at indices 5 through 9 with 0s, then show the resulting list. +numbers[5:10] = [0] * len(numbers[5:10]) +print(f'Replace the elements at indices 5 through 9 with 0s, then show the resulting list. {numbers[5:10]}') + +#Keep only the first five elements, then show the resulting list. +numbers[5:] = [] +print(f'Keep only the first five elements, then show the resulting list. {numbers}') + +numbers[:] = [] +print(f'Delete all the remaining elements by assigning to a slice. Show the resulting list. {numbers}') diff --git a/chapter5-exercices/chapter5_07_ex.py b/chapter5-exercices/chapter5_07_ex.py new file mode 100755 index 0000000..5857f67 --- /dev/null +++ b/chapter5-exercices/chapter5_07_ex.py @@ -0,0 +1,15 @@ +""" Create a list called numbers containing the values from 1 through 15, then use the del statement to perform the following operations consecutively: + Delete a slice containing the first four elements, then show the resulting list. + Starting with the first element, use a slice to delete every other element of the list, then show the resulting list. """ + +numbers = list(range(1, 16)) + +del numbers[:4] +print(numbers) + + +del numbers[::2] +print(numbers) + + + diff --git a/chapter5-exercices/chapter5_08_ex.py b/chapter5-exercices/chapter5_08_ex.py new file mode 100755 index 0000000..4c8c862 --- /dev/null +++ b/chapter5-exercices/chapter5_08_ex.py @@ -0,0 +1,12 @@ +""" sorting a list """ + +import random as rnd + + +def sort_list_a(args): + args.sort(reverse=True) + return args + +numbers = [rnd.randrange(100) for x in range(10)] +print(sort_list_a(numbers)) + diff --git a/chapter5-exercices/chapter5_09_ex.py b/chapter5-exercices/chapter5_09_ex.py new file mode 100755 index 0000000..8c621ba --- /dev/null +++ b/chapter5-exercices/chapter5_09_ex.py @@ -0,0 +1,12 @@ +""" Create a five-element list containing 67, 12, 46, 43 and 13, then use list method index to search for a 43 and 44. + Ensure that no ValueError occurs when searching for 44. """ + +five_element = [67, 12, 46, 43] + +key = float(input('Please enter a number to search for:')) + +if key in five_element: + print(f'Found {key} at index {five_element.index(key)}') +else: + print(f'Number {key} not found') + diff --git a/chapter5-exercices/chapter5_10_ex.py b/chapter5-exercices/chapter5_10_ex.py new file mode 100755 index 0000000..09b7f67 --- /dev/null +++ b/chapter5-exercices/chapter5_10_ex.py @@ -0,0 +1,23 @@ +""" (Telephone-Number Word Generator) You should find this exercise to be entertaining. + Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them, as shown in the following table: + A table shows telephone numbers 2 through 9 with corresponding three letters associated with each number. 2, A B C. 3 D E F. 4 G H I. 5 J K L. 6 M N O. 7 P R S. 8 T U V. 9 W X Y. + + Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words (or phrases) that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in the preceding table to develop the seven-letter word “NUMBERS.” Every seven-letter word or phrase corresponds to exactly one seven-digit telephone number. A budding data science entrepreneur might like to reserve the phone number 244-3282 (“BIGDATA”). + Every seven-digit phone number without 0s or 1s corresponds to many different seven-letter words, but most of these words represent unrecognizable gibberish. A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters “PETCARE.” + + Write a script that, given a seven-digit number, generates every possible seven-letter word combination corresponding to that number. + There are 2,187 (37) such combinations. Avoid phone numbers with the digits 0 and 1 (to which no letters correspond). + See if your phone number corresponds to meaningful words. """ + +import itertools + + +string_init = list(str(input("Enter a seven-digit number: "))) + + + +def anagrams(arg): + + return + +print(string_init) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_11_ex.py b/chapter5-exercices/chapter5_11_ex.py new file mode 100644 index 0000000..87db10a --- /dev/null +++ b/chapter5-exercices/chapter5_11_ex.py @@ -0,0 +1,5 @@ +""" (Word or Phrase to Phone-Number Generator) + Just as people would enjoy knowing what word or phrase their phone number corresponds to, + they might choose a word or phrase appropriate for their business and determine what phone numbers correspond to it. + These are sometimes called vanity phone numbers, and various websites sell such phone numbers. + Write a script similar to the one in the previous exercise that produces the possible phone number for the given seven-letter string. """ \ No newline at end of file diff --git a/chapter5-exercices/chapter5_12_ex.py b/chapter5-exercices/chapter5_12_ex.py new file mode 100755 index 0000000..731d5f4 --- /dev/null +++ b/chapter5-exercices/chapter5_12_ex.py @@ -0,0 +1,18 @@ +""" (Is a Sequence Sorted?) Create a function is_ordered that receives a sequence and returns True if the elements are in sorted order. + Test your function with sorted and unsorted lists, tuples and strings. """ + +def is_ordered(sequence): + """Return True if the elements of the sequence are sorted in ascending order.""" + seq_list = list(sequence) + return seq_list == sorted(seq_list) + + +# --- Testing with lists, tuples, and strings --- +print(is_ordered([1, 2, 3, 4])) # True +print(is_ordered([3, 2, 1])) # False + +print(is_ordered((1, 2, 3))) # True +print(is_ordered((3, 1, 2))) # False + +print(is_ordered("abc")) # True +print(is_ordered("cba")) # False diff --git a/chapter5-exercices/chapter5_13_ex.py b/chapter5-exercices/chapter5_13_ex.py new file mode 100755 index 0000000..744d1a3 --- /dev/null +++ b/chapter5-exercices/chapter5_13_ex.py @@ -0,0 +1,31 @@ +""" (Tuples Representing Invoices) When you purchase products or services from a company, + you typically receive an invoice listing what you purchased and the total amount of money due. + Use tuples to represent hardware store invoices that consist of four pieces of data—a part ID string, + a part description string, an integer quantity of the item being purchased and, for simplicity, a float item price (in general, Decimal should be used for monetary amounts). + Use the sample hardware data shown in the following table.""" + +how_many_items = int(input("How many items would you like to purchase? ")) + +def item_description(arg): + items = [] + for item in range(1, arg + 1): + part_number = int(input(f"Part number for the item number {item} is: ")) + part_description = str(input(f"Part description for the item number {item} is: ")) + quantity = int(input(f"Quantity for the item number {item} is: ")) + price = float(input(f"Price for the item number {item} is: ")) + items.append((part_number, part_description, quantity, price)) + items = tuple(items) + return items + +a = item_description(how_many_items) + +print(f"Part number Part description Quantity Price") +for item in a: + part_number, part_description, quantity, price = item + print(f"{part_number:<13}{part_description:<18}{quantity:<10}{price:<5.2f}") + + + + + + diff --git a/chapter5-exercices/chapter5_14_ex.py b/chapter5-exercices/chapter5_14_ex.py new file mode 100755 index 0000000..5956307 --- /dev/null +++ b/chapter5-exercices/chapter5_14_ex.py @@ -0,0 +1,52 @@ +""" Perform the following tasks on a list of invoice tuples: + Use function sorted with a key argument to sort the tuples by part description, then display the results. + To specify the element of the tuple that should be used for sorting, first import the itemgetter function from the operator module as in + + from operator import itemgetter + + Then, for sorted’s key argument specify itemgetter( index ) where index specifies which element of the tuple should be used for sorting purposes. + Use the sorted function with a key argument to sort the tuples by price, then display the results. + Map each invoice tuple to a tuple containing the part description and quantity, sort the results by quantity, then display the results. + Map each invoice tuple to a tuple containing the part description and the value of the invoice (the product of the quantity and the item price), sort the results by the invoice value, then display the results. + Modify Part (d) to filter the results to invoice values in the range $200 to $500. + Calculate the total of all the invoices. """ + +from operator import itemgetter + + +def sorted_key(arg): + items = [] + for item in range(1, arg + 1): + (part_number, part_description, quantity, price) = (int(input(f"Part number for the item number {item} is: ")), + str(input(f"Part description for the item {item} is ")), + int(input(f"Quantity for the item number {item} is: ")), + float(input(f"Price for the item number {item} is: "))) + items.append((part_number, part_description, quantity, price)) + return items + +def choice_key(): + key_choice = str(input("Which item would you like to sort by?")).lower() + if key_choice == 'part number': + b = sorted(sorted_key(how_many_items), key=itemgetter(0)) + elif key_choice == 'part description': + b = sorted(sorted_key(how_many_items), key=itemgetter(1)) + elif key_choice == 'quantity': + b = sorted(sorted_key(how_many_items), key=itemgetter(2)) + elif key_choice == 'price': + b = sorted(sorted_key(how_many_items), key=itemgetter(3)) + return b + +def printing_result(): + a = sorted_key(how_many_items) + print(f"Part number Part description Quantity Price") + for item in a: + part_number, part_description, quantity, price = item + print(f"{part_number:<13}{part_description:<18}{quantity:<10}{price:<5.2f}") + return + +how_many_items = int(input("How many items would you like to purchase? ")) + + + +printing_result() + diff --git a/chapter5-exercices/chapter5_15_ex.py b/chapter5-exercices/chapter5_15_ex.py new file mode 100755 index 0000000..730f44f --- /dev/null +++ b/chapter5-exercices/chapter5_15_ex.py @@ -0,0 +1,24 @@ +""" (Sorting Letters and Removing Duplicates) letter. Perform the following tasks and display your results: + + 1.Sort the list in ascending order. + 2.Sort the list in descending order. + 3.Get the unique values sort them in ascending order. """ + +import random + +def sort_letters_ascending(arg): + return sorted(arg) + +def sort_letters_descending(arg): + return sorted(arg, reverse=True) + +def sort_letters_set(arg): + return sorted(set(arg)) + +letters = [chr(random.randrange(ord('a'), ord('f') +1)) for _ in range(20)] + +print(sort_letters_ascending(letters)) +print(sort_letters_descending(letters)) +print(sort_letters_set(letters)) + + diff --git a/chapter5-exercices/chapter5_16_ex.py b/chapter5-exercices/chapter5_16_ex.py new file mode 100755 index 0000000..50edd5b --- /dev/null +++ b/chapter5-exercices/chapter5_16_ex.py @@ -0,0 +1,53 @@ +""" (Filter/Map Performance) With regard to the following code: + numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] + list(map(lambda x: x ** 2, + filter(lambda x: x % 2 != 0, numbers))) + + 1. How many times does the filter operation call its lambda argument? + 2. How many times does the map operation call its lambda argument? + 3. If you reverse the filter and map operations, how many times does the map operation call its lambda argument? + + To help you answer the preceding questions, define functions that perform the same tasks as the lambdas. + In each function, include a print statement so you can see each time the function is called. + Finally, replace the lambdas in the preceding code with the names of your functions. """ + +numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] + +def filter_function(arg): + numbers_filtered = [] + for number in arg: + if number % 2 != 0: + numbers_filtered.append(number) + + return numbers_filtered + +def map_function(arg): + numbers_mapped = [] + for number in arg: + numbers_mapped.append(number ** 2) + return numbers_mapped + +def filter_map(arg): + numbers_mapped = [] + numbers_filtered = [] + for number in arg: + numbers_mapped.append(number ** 2) + print(number ** 2, end =' ') + print() + + for number in numbers_mapped: + if number % 2 != 0: + numbers_filtered.append(number) + print(number, end=' ') + print() + return numbers_filtered + +print(filter_function(numbers)) +print(map_function(filter_function(numbers))) +print(filter_map(numbers)) + + + + + + diff --git a/chapter5-exercices/chapter5_17_ex.py b/chapter5-exercices/chapter5_17_ex.py new file mode 100755 index 0000000..0e7dcd5 --- /dev/null +++ b/chapter5-exercices/chapter5_17_ex.py @@ -0,0 +1,9 @@ +""" (Summing the Triples of the Even Integers from 2 through 10) + Starting with a list containing 1 through 10, use filter, map and sum to calculate the total of the triples of + the even integers from 2 through 10. Reimplement your code with list comprehensions rather than filter and map. """ + +a = sum(list(map(lambda x: x * 3,list(filter(lambda x: x % 2 == 0, range(1, 10)))))) +print(a) + +b = sum(x * 3 for x in range(1, 10) if x % 2 == 0) +print(b) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_18_ex.py b/chapter5-exercices/chapter5_18_ex.py new file mode 100755 index 0000000..796037f --- /dev/null +++ b/chapter5-exercices/chapter5_18_ex.py @@ -0,0 +1,19 @@ +""" (Finding the People with a Specified Last Name) + Create a list of tuples containing first and last names. Use filter to locate the tuples containing the last name Jones. + Ensure that several tuples in your list have that last name. """ + +#initialization phase.. + +how_many_pople = int(input("How many people to find? ")) + +def create_list_of_tuple(arg): + items = [] + for item in range(1, arg + 1): + (first_name, last_name) = (str(input(f"Please enter first name for person number {item} ")).lower(), + str(input(f"Please enter last name for person number {item} ")).lower()) + items.append((first_name, last_name)) + return items + +filter_key = str(input("Please enter last name for person number to filter: ")).lower() +a = list(filter(lambda y: y[1] == filter_key, create_list_of_tuple(how_many_pople))) +print(a) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_19_ex.py b/chapter5-exercices/chapter5_19_ex.py new file mode 100755 index 0000000..d41c876 --- /dev/null +++ b/chapter5-exercices/chapter5_19_ex.py @@ -0,0 +1,31 @@ +""" (Display a Two-Dimensional List in Tabular Format) + Define a function named display_table that receives a two-dimensional list and displays its contents in tabular format. + List the column indices as headings across the top, and list the row indices at the left of each row. """ + +how_many_rows = int(input("How many rows would you like to display? ")) +how_many_columns = int(input("How many columns would you like? ")) + + + +def generate_rows(): + two_dim_list = [] + for row in range(how_many_rows): + a = [] + for column in range(how_many_columns): + a.append(int(input(f'Please enter value: '))) + two_dim_list.append(a) + return two_dim_list + +def display_table(arg): + print("The contents of the table: ") + for item in range(how_many_columns): + print(f" {item:^1}", end=' ') + print() + for i, item in enumerate(arg): + print(f'{i}', end= ' ') + for value in item: + print(f"{value:^2}", end=' ') + print() + return print(f'\n') + +display_table(generate_rows()) diff --git a/chapter5-exercices/chapter5_1_ex.py b/chapter5-exercices/chapter5_1_ex.py new file mode 100755 index 0000000..add46ad --- /dev/null +++ b/chapter5-exercices/chapter5_1_ex.py @@ -0,0 +1,16 @@ +""" Replace the ***s in the following list comprehension and map function call, such that given a list of heights in inches, + the code maps the list to a list of tuples containing the original height values and their corresponding values in meters. + For example, if one element in the original list contains the height 69 inches, the corresponding element + in the new list will contain the tuple (69, 1.7526), representing both the height in inches and the height in meters. + There are 0.0254 meters per inch. + + [*** for x in [69, 77, 54]] + list(map(lambda ***, [69, 77, 54])) """ + + + +a = [x for x in [69, 77, 54]] +print(a) +b = list(map(lambda x: (x, x ** 0.0254), [69, 77, 54])) +print(b) + diff --git a/chapter5-exercices/chapter5_20_ex.py b/chapter5-exercices/chapter5_20_ex.py new file mode 100644 index 0000000..425b6c2 --- /dev/null +++ b/chapter5-exercices/chapter5_20_ex.py @@ -0,0 +1,9 @@ +""" 5.21 (Computer-Assisted Instruction: Reducing Student Fatigue) + Re-implement Exercise 4.15 to store the computer’s responses in lists. + Use random-number generation to select responses using random list indices. + 4.15 (Computer-Assisted Instruction: Reducing Student Fatigue) Varying the computer’s responses can help hold the student’s attention. + Modify the previous exercise so that various comments are displayed for each answer. + Possible responses to a correct answer should include 'Very good!', 'Nice work!' and 'Keep up the good work!' + Possible responses to an incorrect answer should include 'No. Please try again.', 'Wrong. + Try once more.' and 'No. Keep trying.' Choose a number from 1 to 3, then use that value to select one of the three appropriate responses to each correct or incorrect answer. """ + diff --git a/chapter5-exercices/chapter5_21_ex.py b/chapter5-exercices/chapter5_21_ex.py new file mode 100755 index 0000000..bc81558 --- /dev/null +++ b/chapter5-exercices/chapter5_21_ex.py @@ -0,0 +1,25 @@ +""" 5.22 (Simulating a Queue with a List) + In this chapter, you simulated a stack using a list. You also can simulate a queue collection with a list. + Queues represent waiting lines similar to a checkout line in a supermarket. + The cashier services the person at the front of the line first. Other customers enter the line only at the end and wait for service. + + In a queue, you insert items at the back (known as the tail) and delete items from the front (known as the head). + For this reason, queues are first-in, first-out (FIFO) collections. The insert and remove operations are commonly known as enqueue and dequeue. + + Queues have many uses in computer systems, such as sharing CPUs among a potentially large number of competing applications and the operating system itself. + Applications not currently being serviced sit in a queue until a CPU becomes available. The application at the front of the queue is the next to receive service. + Each application gradually advances to the front as the applications before it receive service. + + Simulate a queue of integers using list methods append (to simulate enqueue) and pop with the argument 0 (to simulate dequeue). + Enqueue the values 3, 2 and 1, then dequeue them to show that they’re removed in FIFO order. """ + +a = [] +for i in range(3, 0, -1): + a.append(i) + + +for i in range(len(a)): + print(a.pop(0), end=" ") +print() + + diff --git a/chapter5-exercices/chapter5_22_ex.py b/chapter5-exercices/chapter5_22_ex.py new file mode 100644 index 0000000..b8a7fc9 --- /dev/null +++ b/chapter5-exercices/chapter5_22_ex.py @@ -0,0 +1,18 @@ +""" 5.23 (Functional-Style Programming: Order of filter and map Calls) + When combining filter and map operations, the order in which they’re performed matters. + Consider a list numbers containing 10, 3, 7, 1, 9, 4, 2, 8, 5, 6 and the following code: + + + In [1]: numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] + + + In [2]: list(map(lambda x: x * 2, + + ...: filter(lambda x: x % 2 == 0, numbers))) + + ...: + + Out[3]: [20, 8, 4, 16, 12] + + Reorder this code to call map first and filter second. What happens and why? """ + diff --git a/chapter5-exercices/chapter5_23_ex.py b/chapter5-exercices/chapter5_23_ex.py new file mode 100755 index 0000000..1125728 --- /dev/null +++ b/chapter5-exercices/chapter5_23_ex.py @@ -0,0 +1,45 @@ +""" 5.24 (Card Shuffling and Dealing) + In Exercises 5.24 through 5.26, you’ll use lists of tuples in scripts that simulate card shuffling and dealing. + Each tuple represents one card in the deck and contains a face + (e.g., 'Ace', 'Deuce', 'Three', …, 'Jack', 'Queen', 'King') and a suit (e.g., 'Hearts', 'Diamonds', 'Clubs', 'Spades'). + Create an initialize_deck function to initialize the deck of card tuples with 'Ace' through 'King' of each suit, as in + + + + deck = [('Ace', 'Hearts'), …, ('King', 'Hearts'), + + ('Ace', 'Diamonds'), …, ('King', 'Diamonds'), + + ('Ace', 'Clubs'), …, ('King', 'Clubs'), + + ('Ace', 'Spades'), …, ('King', 'Spades')] + + Before returning the list, use the random module’s shuffle function to randomly order the list elements. Output the shuffled cards in the following four-column format: + A screen shot of an image that shows the use of a random module’s shuffle function and the output of the shuffled cards in a 4 column format. """ + +import random + +def create_deck(): + faces = ['ace', 'deuce', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king'] + suits = ['hearts', 'diamonds', 'clubs', 'spades'] + + deck = [(x, y) for x in suits for y in faces] + + random.shuffle(deck) + return deck + +def displying_deck(arg): + for i, item in enumerate(arg, start=1): + print(f"{item[0]} of {item[1]:<9}", end="\t") + if i % 5 == 0: + print() + return print() + + +if __name__ == '__main__': + deck = create_deck() + print("shuffled cards:") + displying_deck(deck) + + + diff --git a/chapter5-exercices/chapter5_24_ex.py b/chapter5-exercices/chapter5_24_ex.py new file mode 100755 index 0000000..2da7d19 --- /dev/null +++ b/chapter5-exercices/chapter5_24_ex.py @@ -0,0 +1,117 @@ +""" 5.25 (Card Playing: Evaluating Poker Hands) + Modify Exercise 5.24 to deal a five-card poker hand as a list of five card tuples. + Then create functions (i.e., is_pair, is_two_pair, is_three_of_a_kind, …) that determine whether the hand they receive as an argument contains groups of cards, such as: + + one pair + two pairs + three of a kind (e.g., three jacks) + a straight (i.e., five cards of consecutive face values) + a flush (i.e., all five cards of the same suit) + a full house (i.e., two cards of one face value and three cards of another) + four of a kind (e.g., four aces) + straight flush (i.e., a straight with all five cards of the same suit) + … and others. + + See https://en.wikipedia.org/wiki/List_of_poker_hands for poker-hand types and how they rank with respect to one another. For example, three of a kind beats two pairs. """ + +import random + +ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14) + +def deck_initialization(): + faces = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king'] + suits = ['hearts', 'diamonds', 'clubs', 'spades'] + + deck = [(x, y) for x in faces for y in suits] + random.shuffle(deck) + return deck + +def display_five_cards(arg): + cards = [] + + for i in range(5): + cards.append(arg[i]) + for i, card in enumerate(cards): + if i + 1 == 1: + print(f"{i + 1}st card is {card[0]} of {card[1]}") + elif i + 1 == 2: + print(f"{i + 1}nd card is {card[0]} of {card[1]}") + elif i + 1 == 3: + print(f"{i + 1}rd card is {card[0]} of {card[1]}") + elif i + 1 == 4: + print(f"{i + 1}th card is {card[0]} of {card[1]}") + elif i + 1 == 5: + print(f"{i + 1}th card is {card[0]} of {card[1]}") + return cards + + +def is_pair(arg): + face = [] + for faces, suit in arg: + face.append(faces) + cards = list(set(i for i in face if face.count(i) == 2)) + print(cards) + if len(cards) > 0: + printing = [x for x in arg if x[0] == cards[0]] + print(f"We've got a pair of the following cards: {printing}") + else: + return print(f"Could not find a pair in {arg}.") + + +def two_pairs(arg): + faces = [] + for face, suit in arg: + faces.append(face) + cards = list(set(i for i in faces if faces.count(i) == 2)) + print(cards if len(cards) > 1 else f"Could not find a pair in {arg}.") + if len(cards) > 1: + printing_two_pairs = [] + for item in cards: + for face, suit in enumerate(arg): + if item in suit: + printing_two_pairs.append(suit) + print(f"Found the following pairs: {printing_two_pairs}.") + return + + +def three_of_a_kind(arg): + faces = [] + for face, suit in arg: + faces.append(face) + cards = list(set(x for x in faces if faces.count(x) == 3)) + print(cards if len(cards) > 0 else f"Could not find a three of a kind pair in {arg}.") + if len(cards) > 0: + printing_three_of_a_kind = [] + for item in cards: + for face, suit in enumerate(arg): + if item in suit: + printing_three_of_a_kind.append(suit) + print(f"Found the following three of a kind: {printing_three_of_a_kind}") + return + +def four_of_a_kind(arg): + faces = [] + for face, suit in arg: + faces.append(face) + cards = list(set(i for i in faces if faces.count(i) == 4)) + print(cards if len(cards) > 0 else f"Could not find a four of a kind pair in {arg}.") + if len(cards) > 0: + printing_four_of_a_kind = [] + for item in cards: + for face, suit in enumerate(arg): + if item in suit: + printing_four_of_a_kind.append(suit) + print(f"Found the following four of a kind: {printing_four_of_a_kind}") + return + + + +if __name__ == '__main__': + desk = deck_initialization() + print("displayed 5 shuffled cards: ") +# print(display_five_cards(deck_initialization())) +# print(is_pair(display_five_cards(deck_initialization()))) +# print(two_pairs(display_five_cards(deck_initialization()))) +# print(three_of_a_kind(display_five_cards(deck_initialization()))) + print(four_of_a_kind(display_five_cards(deck_initialization()))) + diff --git a/chapter5-exercices/chapter5_25_ex.py b/chapter5-exercices/chapter5_25_ex.py new file mode 100755 index 0000000..bbd6329 --- /dev/null +++ b/chapter5-exercices/chapter5_25_ex.py @@ -0,0 +1,9 @@ +""" Intro to Data Science: Duplicate Elimination and Counting Frequencies) + Use a list comprehension to create a list of 50 random values in the range 1 through 10. + Use NumPy’s unique function to obtain the unique values and their frequencies. Display the results. """ + +import random +import numpy + +list_compre = [random.randint(1, 10) for _ in range(50)] +print(numpy.unique_counts(list_compre)) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_26_ex.py b/chapter5-exercices/chapter5_26_ex.py new file mode 100755 index 0000000..3bc7bb2 --- /dev/null +++ b/chapter5-exercices/chapter5_26_ex.py @@ -0,0 +1,40 @@ +""" Intro to Data Science: Survey Response Statistics) + Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” + Place the 20 responses in a list + + 1, 2, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 5 + + Determine and display the frequency of each rating. + Use the built-in functions, statistics module functions and NumPy functions demonstrated in Section 5.17.2 + to display the following response statistics: minimum, maximum, range, mean, median, mode, variance and standard deviation. """ + + +import random +import statistics +import numpy + + + +lst = [random.randint(1, 5) for i in range(20)] + +printing = [] + +for item in lst: + items = (item, lst.count(item)) + printing.append(items) +print(lst) +printing = list(set(printing)) +print("min = ", min(lst)) +print("max = ", max(lst)) +print("range = ", min(lst), '-', max(lst)) +print("mean = ", statistics.mean(lst)) +print("median = ", statistics.median(lst)) +print("mode = ", statistics.mode(lst)) +print("variance = ", numpy.var(lst)) +print("standard_deviation = ", numpy.std(lst)) + + +print(list(set(printing))) + +for item, occurrences in printing: + print(f"We found the item {item} with {occurrences} occurrences.") diff --git a/chapter5-exercices/chapter5_27_ex.py b/chapter5-exercices/chapter5_27_ex.py new file mode 100755 index 0000000..9e5797e --- /dev/null +++ b/chapter5-exercices/chapter5_27_ex.py @@ -0,0 +1,31 @@ +""" (Intro to Data Science: Visualizing Survey Response Statistics) + Using the list in Exercise 5.28 and the techniques you learned in Section 5.17.2, + display a bar chart showing the response frequencies and their percentages of the total responses. """ + +import matplotlib.pyplot as plt +import numpy as np +import random as rd +import seaborn as sns + + +lst = [rd.randint(1, 5) for i in range(20000)] + +val, freq = np.unique(lst, return_counts=True) + +title = f'Rolling a two-side die {len(lst):,} Times' +sns.set_style('whitegrid') + +axes = sns.barplot(x=val, y=freq, hue=val, palette="bright", legend=False, ) #pentru a seta graficul cu valorile obtinute +axes.set_title(title) #pentru a seta titlul +axes.set(xlabel="die value", ylabel="frequency") #pentru a seta descrierile pe fiecare axa.. X si Y +axes.set_ylim(top=max(freq) * 1.10) #pentru a seta inaltimea dorita pentru axa Y + #pentru a call-ui matplotlib si a face display-ul graficului + +for bar, frequency in zip(axes.patches, freq): + text_x = bar.get_x() + bar.get_width() / 2.0 + text_y = bar.get_height() + text = f'{frequency:,}\n{frequency / len(lst):.2%}' + axes.text(text_x, text_y, text, + fontsize=11, ha='center', va='bottom') + +plt.show() \ No newline at end of file diff --git a/chapter5-exercices/chapter5_2_ex.py b/chapter5-exercices/chapter5_2_ex.py new file mode 100755 index 0000000..1d37fc0 --- /dev/null +++ b/chapter5-exercices/chapter5_2_ex.py @@ -0,0 +1,36 @@ +""" (Iteration Order) Create a 2-by-3 list, then use a nested loop to: + Set each element’s value to an integer indicating the order in which it was processed by the nested loop. + Display the elements in tabular format. + Use the column indices as headings across the top, and the row indices to the left of each row. """ + +#initialization phase - defining the rows and columns. +(row, col) = (2, 3) + +#initialization phase - defining the table with zeroes. +table = [[0 for c in range(col)] for r in range(row)] + +#number1 - Set each element’s value to an integer indicating the order in which it was processed by the nested loop. +total = 1 +for r in range(row): + for c in range(col): + table[r][c] = total + total += 1 + +#number2 - Display the elements in tabular format - print column headings. +print(" ", end="") +for c in range(col): + print(f'{c:4}', end='') +print() + +#number2 - Display the elements in tabular format - print rows in the left. +for r in range(row): + print(f'{r:2} |', end='') + for c in range(col): + print(f'{table[r][c]:4}', end='') + print() + + + + + + diff --git a/chapter5-exercices/chapter5_3_ex.py b/chapter5-exercices/chapter5_3_ex.py new file mode 100755 index 0000000..45af324 --- /dev/null +++ b/chapter5-exercices/chapter5_3_ex.py @@ -0,0 +1,32 @@ +""" Create a string called alphabet containing 'abcdefghijklmnopqrstuvwxyz', then perform the following separate slice operations to obtain: + The first half of the string using starting and ending indices. + The first half of the string using only the ending index. + The second half of the string using starting and ending indices. + The second half of the string using only the starting index. + Every second letter in the string starting with 'a'. + The entire string in reverse. + Every third letter of the string in reverse starting with 'z'.""" + +#initial phase - Create a string called alphabet containing 'abcdefghijklmnopqrstuvwxyz', then perform the following separate slice operations to obtain +alphabet = ('abcdefghijklmnopqrstuvwxyz') + +#processing phase1 - obtain The first half of the string using starting and ending indices. +print(alphabet[0:len(alphabet)//2]) + +#processing phase2 - obtain The first half of the string using only the ending index. +print(alphabet[:len(alphabet)//2]) + +#processing phase3 - obtain The second half of the string using starting and ending indices. +print(alphabet[len(alphabet)//2:len(alphabet)]) + +#processing phase4 - obtain The second half of the string using only the starting index. +print(alphabet[len(alphabet)//2:]) + +#processing phase5 - obtain Every second letter in the string starting with 'a'. +print(alphabet[::2]) + +#processing phase6 - obtain The entire string in reverse. +print(alphabet[::-1]) + +#processing phase7 - obtain Every third letter of the string in reverse starting with 'z'. +print(alphabet[::-3]) \ No newline at end of file diff --git a/chapter5-exercices/chapter5_4_ex.py b/chapter5-exercices/chapter5_4_ex.py new file mode 100755 index 0000000..24698bc --- /dev/null +++ b/chapter5-exercices/chapter5_4_ex.py @@ -0,0 +1,33 @@ +""" (Functions Returning Tuples) + Define a function rotate that receives three arguments and returns a tuple in which the first argument is at index 1, + the second argument is at index 2 and the third argument is at index 0. + Define variables a, b and c containing 'Doug', 22 and 1984. + Then call the function three times. + For each call, unpack its result into a, b and c, then display their values. """ + +#processing phase: +def rotate(x, y, z): + return (z, x, y) + +#initialization phase: +a, b, c = ('Doug', 22, 1984) + +#first call: +a, b, c = rotate(a, b, c) +print(a, b, c) + +#second call: +a, b, c = rotate(a, b, c) +print(a, b, c) + +#third call: +a, b, c = rotate(a, b, c) +print(a, b, c) + + + + + + + + diff --git a/chapter5-exercices/chapter5_5_ex.py b/chapter5-exercices/chapter5_5_ex.py new file mode 100755 index 0000000..7237f45 --- /dev/null +++ b/chapter5-exercices/chapter5_5_ex.py @@ -0,0 +1,18 @@ +""" (Duplicate Elimination) + Create a function that receives a list and returns a (possibly shorter) list containing only the unique values in sorted order. + Test your function with a list of numbers and a list of strings. """ + +def unique_values(list1): + return sorted(set(list1)) + +a = int(input("Please enter the list size: ")) + +c = [] + +for i in range(a): + b = float(input("please enter a value to add to the list: ")) + c.append(b) + +print(unique_values(c)) + + diff --git a/chapter5-exercices/chapter5_6_ex.py b/chapter5-exercices/chapter5_6_ex.py new file mode 100755 index 0000000..e2916dd --- /dev/null +++ b/chapter5-exercices/chapter5_6_ex.py @@ -0,0 +1,57 @@ +""" (Sieve of Eratosthenes) A prime number is an integer greater than 1 that’s evenly divisible only by itself and 1. + The Sieve of Eratosthenes is an elegant, straightforward method of finding prime numbers. + The process for finding all primes less than 1000 is: + + 1.Create a 1000-element list primes with all elements initialized to True. + List elements with prime indices (like 2, 3, 5, 7, 11, …) will remain True. + All other list elements will eventually be set to False. + + 2.Starting with index 2, if a given element is True iterate through the rest of the list + and set to False every element in primes whose index is a multiple of the index for the element we’re currently processing. + For list index 2, all elements beyond element 2 in the list that have indices which are multiples of 2 (i.e., 4, 6, 8, 10, …, 998) will be set to False. + + 3.Repeat Step (b) for the next True element. + For list index 3 (which was initialized to True), all elements beyond element 3 in the list + that have indices which are multiples of 3 (i.e., 6, 9, 12, 15, …, 999) will be set to False; and so on. + A subtle observation (think about why this is true): The square root of 999 is 31.6, + you’ll need to test and set to False only all multiples of 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29 and 31. + This will significantly improve the performance of your algorithm, especially if you decide to look for large prime numbers. + + When this process completes, the list elements that are still True indicate that the index is a prime number. + These indices can be displayed. Use a list of 1000 elements to determine and display the prime numbers less than 1000. + Ignore list elements 0 and 1. [As you work through the book, you’ll discover other Python capabilities that will enable you to cleverly reimplement this exercise.] """ + +import math + +#initialization phase: Declaring the list of the first n numbers.. + +n_numbers = int(input("Please enter a number for guessing all the primes numbers: ")) +list_numbers = [x for x in range(n_numbers + 1)] + +#processing phase: +def list_d(arg): + c = [] + for index, value in enumerate(arg): + d = [x for x in range(2, int(math.sqrt(value)) + 1)] + if len(d) == 0: + response = 'true' + else: + response_d = [] + for item in d: + z = value % item + response_d.append(z) + if 0 in response_d: + response = 'false' + else: + response = 'true' + b = (index, response) + c.append(b) + return c + +print(list_d(list_numbers)) + + + + + + diff --git a/chapter5-exercices/chapter5_7_ex.py b/chapter5-exercices/chapter5_7_ex.py new file mode 100755 index 0000000..573ec92 --- /dev/null +++ b/chapter5-exercices/chapter5_7_ex.py @@ -0,0 +1,32 @@ +""" (Palindrome Tester) + A string that’s spelled identically backward and forward, like 'radar', is a palindrome. + Write a function is_palindrome that takes a string and returns True if it’s a palindrome and False otherwise. + Use a stack (simulated with a list as we did in Section 5.11) to help determine whether a string is a palindrome. + Your function should ignore case sensitivity (that is, 'a' and 'A' are the same), spaces and punctuation. """ + +stringup = str(input("Enter a string to verify if it'a palindrome or not:")) + +length_string = len(stringup) + +def is_palindrome(arg): + if length_string % 2 == 0: + length_string_mid = length_string // 2 + else: + length_string_mid = length_string // 2 + 1 + string_final = list(arg) + first_part_string = [] + second_part_string = [] + for x in range(length_string_mid): + first_part_string.append(stringup[x]) + second_part_string.append(string_final.pop()) + return first_part_string, second_part_string + +a, b = is_palindrome(stringup) +first_check = a +second_check = b + +if first_check == second_check: + print("Palindrome") +else: + print("Not Palindrome") + diff --git a/chapter5-exercices/chapter5_8_ex.py b/chapter5-exercices/chapter5_8_ex.py new file mode 100755 index 0000000..cfa2103 --- /dev/null +++ b/chapter5-exercices/chapter5_8_ex.py @@ -0,0 +1,14 @@ +""" (Anagrams) An anagram of a string is another string formed by rearranging the letters in the first. + Write a script that produces all possible anagrams of a given string using only techniques that you’ve seen to this point in the book. + [The itertools module provides many functions, including one that produces permutations.] """ + +import itertools + +string_ini = str(input("Enter a string: ")) + +def anagrams(arg): + anagrams = itertools.permutations(arg) + return list(anagrams) + +print(anagrams(string_ini)) + diff --git a/chapter5-exercices/chapter5_9_ex.py b/chapter5-exercices/chapter5_9_ex.py new file mode 100755 index 0000000..c06cb62 --- /dev/null +++ b/chapter5-exercices/chapter5_9_ex.py @@ -0,0 +1,18 @@ +""" (Summarizing Letters in a String) Write a function summarize_letters that receives a string and returns a list of tuples + containing the unique letters and their frequencies in the string. Test your function and display each letter with its frequency. + Your function should ignore case sensitivity (that is, 'a' and 'A' are the same) and ignore spaces and punctuation. + When done, write a statement that says whether the string has all the letters of the alphabet. """ + +string_ini = sorted(list(str(input("Enter a string: ")).lower().strip())) + +def summarize_letters(arg): + string_mid = [] + for letter in arg: + a = letter, arg.count(letter) + string_mid.append(a) + string_final = sorted(set(string_mid)) + return string_final + +print(summarize_letters(string_ini)) + +