Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions chapter4-exercices/chapter4_10_ex.py
Original file line number Diff line number Diff line change
@@ -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!")
11 changes: 11 additions & 0 deletions chapter4-exercices/chapter4_12_ex.py
Original file line number Diff line number Diff line change
@@ -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. """

22 changes: 22 additions & 0 deletions chapter4-exercices/chapter4_13_ex.py
Original file line number Diff line number Diff line change
@@ -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)

142 changes: 142 additions & 0 deletions chapter4-exercices/chapter4_14_ex.py
Original file line number Diff line number Diff line change
@@ -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".')

6 changes: 6 additions & 0 deletions chapter4-exercices/chapter4_15_ex.py
Original file line number Diff line number Diff line change
@@ -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. """
9 changes: 9 additions & 0 deletions chapter4-exercices/chapter4_18_ex.py
Original file line number Diff line number Diff line change
@@ -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. """
16 changes: 16 additions & 0 deletions chapter4-exercices/chapter4_19_ex.py
Original file line number Diff line number Diff line change
@@ -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. """
20 changes: 20 additions & 0 deletions chapter4-exercices/chapter4_9_ex.py
Original file line number Diff line number Diff line change
@@ -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)

14 changes: 14 additions & 0 deletions chapter5-exercices/chapter5_01_ex.py
Original file line number Diff line number Diff line change
@@ -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)
16 changes: 16 additions & 0 deletions chapter5-exercices/chapter5_02_ex.py
Original file line number Diff line number Diff line change
@@ -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))
4 changes: 4 additions & 0 deletions chapter5-exercices/chapter5_03_ex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
""" Create a single-element tuple containing 123.45, then display it. """

single_tuple_element = (123.45, )
print(single_tuple_element)
11 changes: 11 additions & 0 deletions chapter5-exercices/chapter5_04_ex.py
Original file line number Diff line number Diff line change
@@ -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]}")
7 changes: 7 additions & 0 deletions chapter5-exercices/chapter5_05_ex.py
Original file line number Diff line number Diff line change
@@ -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}')
23 changes: 23 additions & 0 deletions chapter5-exercices/chapter5_06_ex.py
Original file line number Diff line number Diff line change
@@ -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}')
15 changes: 15 additions & 0 deletions chapter5-exercices/chapter5_07_ex.py
Original file line number Diff line number Diff line change
@@ -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)



12 changes: 12 additions & 0 deletions chapter5-exercices/chapter5_08_ex.py
Original file line number Diff line number Diff line change
@@ -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))

Loading