Skip to content

Instantly share code, notes, and snippets.

@xmha97
Last active January 2, 2026 15:17
Show Gist options
  • Select an option

  • Save xmha97/620816e942af87238a2f419716e7d276 to your computer and use it in GitHub Desktop.

Select an option

Save xmha97/620816e942af87238a2f419716e7d276 to your computer and use it in GitHub Desktop.
Homeworks

Homework 1-1

Take radius of a circle as user input and
i. Calculate the area of the circle and assign the value to a variable name of area_of_circle
ii. Calculate the circumference of the circle and assign the value to a variable name of circum_of_circle

Hint: Use pi number in math module.

import math

math.pi
#!/usr/bin/env python3
"""Homework 1-1"""
import math
print("It's homework 1-1\n")
# Get radius from the user and convert it to a float
radius = float(input("Please enter the radius: "))
# i. Calculate the area of the circle
# Formula: Area = pi * r^2
area_of_circle = math.pi * (radius ** 2)
# ii. Calculate the circumference of the circle
# Formula: Circumference = 2 * pi * r
circum_of_circle = 2 * math.pi * radius
# Printing the results
print("\nArea of the circle:", area_of_circle)
print("Circumference of the circle:", circum_of_circle)
input("\nPress Enter to exit...")

Homework 1-2

Take a number as seconds from user and convert it to hours, minutes and seconds.

Example 1:

Input:
92

Output:
hours: 0, minutes: 1, seconds: 32

Example 2:

Input:
5876

Output:
hours: 1, minutes: 37, seconds: 56

#!/usr/bin/env python3
"""Homework 1-2"""
print("It's homework 1-2\n")
# 1. Input - Get total seconds from user
total_seconds = int(input("Enter the number of seconds: "))
# 2. Processing - Time conversion
# Calculate hours: how many full 3600 seconds are in the input
hours = total_seconds // 3600
# Find remaining seconds after taking away the hours
remaining_after_hours = total_seconds % 3600
# Calculate minutes: how many full 60 seconds are in the remaining amount
minutes = remaining_after_hours // 60
# Calculate final seconds: what is left after taking away minutes
seconds = remaining_after_hours % 60
# 3. Output - Display the result in the requested format
print(f"\nhours: {hours}, minutes: {minutes}, seconds: {seconds}")
input("\nPress Enter to exit...")

Homework 1-3

Get the coordinates of two points as user input and calculate the Euclidean distance between them.

Example 1:

Input: x1 = 5, y1= 3 & x2 = 2, y2 = 4

Output: 3.16227766

#!/usr/bin/env python3
"""Homework 1-3"""
print("It's homework 1-3\n")
import math
# 1. Get coordinates of the first point
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
# 2. Get coordinates of the second point
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
# 3. Calculate the difference and power of 2
# (x2 - x1)^2 and (y2 - y1)^2
dx_squared = (x2 - x1) ** 2
dy_squared = (y2 - y1) ** 2
# 4. Sum them up and take the square root (Euclidean Distance)
distance = math.sqrt(dx_squared + dy_squared)
# 5. Output the result
print("\nThe Euclidean distance is:", distance)
input("\nPress Enter to exit...")

Homework 1-4

There is a toy factory that makes cars that require 4 wheels, 1 body and 2 dummies. By taking three numbers from the input respectively as the number of wheels, the number of bodies and the number of dummies, determine the maximum number of cars that can be made?

Example 1:

Input:
wheels: 423, bodies: 87, dummies: 190

Output:
87

Example 2:

Input:
wheels: 342, bodies: 102, dummies: 169

Output:
84

#!/usr/bin/env python3
"""Homework 1-4"""
print("It's homework 1-4\n")
# 1. Input - Get the number of parts from the user
wheels = int(input("Enter number of wheels: "))
bodies = int(input("Enter number of bodies: "))
dummies = int(input("Enter number of dummies: "))
# 2. Processing - Calculate how many cars each part can support
# How many cars can we make with the available wheels? (divide by 4)
cars_from_wheels = wheels // 4
# How many cars can we make with the available bodies? (divide by 1)
cars_from_bodies = bodies // 1
# How many cars can we make with the available dummies? (divide by 2)
cars_from_dummies = dummies // 2
# 3. Finding the limiting factor
# The maximum number of complete cars is the minimum of these three values
max_cars = min(cars_from_wheels, cars_from_bodies, cars_from_dummies)
# 4. Output - Display the result
print("\nMaximum number of cars that can be made:", max_cars)
input("\nPress Enter to exit...")

Homework 1-5

In the previous question, how many wheels, bodies and dummies are left?

Example 1:

Input:
wheels: 423, bodies: 87, dummies: 190

Output:
wheels: 75, bodies: 0, dummies: 16

Example 2:

Input:
wheels: 342, bodies: 102, dummies: 169

Output:
wheels: 6, bodies: 18, dummies: 1

#!/usr/bin/env python3
"""Homework 1-5"""
print("It's homework 1-5\n")
# 1. Input - Get the number of parts
wheels = int(input("Enter number of wheels: "))
bodies = int(input("Enter number of bodies: "))
dummies = int(input("Enter number of dummies: "))
# 2. Re-calculate max cars (from previous homework)
cars_from_wheels = wheels // 4
cars_from_bodies = bodies // 1
cars_from_dummies = dummies // 2
max_cars = min(cars_from_wheels, cars_from_bodies, cars_from_dummies)
# 3. Calculate remaining parts
# Subtract the parts used for 'max_cars' from the total parts
wheels_left = wheels - (max_cars * 4)
bodies_left = bodies - (max_cars * 1)
dummies_left = dummies - (max_cars * 2)
# 4. Output - Display the leftovers
print(f"\nwheels: {wheels_left}, bodies: {bodies_left}, dummies: {dummies_left}")
input("\nPress Enter to exit...")

Homework 1-6

Take two variables from input and make the following using string formatting methods:

Example 1:

Input:
x = 6, y = 8

Output:

8 + 6 = 14
8 - 6 = 2
8 * 6 = 48
8 / 6 = 1.33
8 % 6 = 2
8 // 6 = 1
8 ** 6 = 262144

Example 2:

Input:
x = 7, y = 2

Output:

7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3.5
7 % 2 = 1
7 // 2 = 3
7 ** 2 = 49
#!/usr/bin/env python3
"""Homework 1-6"""
print("It's homework 1-6\n")
# 1. Get two numbers from the user
x = int(input("Enter x: "))
y = int(input("Enter y: "))
# Using f-strings to format the output exactly as requested
# Example: Using y and x as they appear in the first example output
print(f"\n{y} + {x} = {y + x}")
print(f"{y} - {x} = {y - x}")
print(f"{y} * {x} = {y * x}")
# For division, we round to 2 decimal places using :.2f
print(f"{y} / {x} = {y / x:.2f}")
print(f"{y} % {x} = {y % x}")
print(f"{y} // {x} = {y // x}")
print(f"{y} ** {x} = {y ** x}")
input("\nPress Enter to exit...")

Homework 2-1

Assign your first name and your last name to variables and:
a. Find common letters between your first name and last name.
b. Return all letters used in either your first name or last name.

Example 1:

Input:
Emad, Sudani

Output:
a. {'a', 'd'}
b. {'d', 'E', 'i', 'm', 'S', 'n', 'a', 'u'}

Hint: Use set and its methods.

#!/usr/bin/env python3
"""Homework 2-1"""
print("It's homework 2-1\n")
# 1. Get input from the user
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# 2. Convert inputs to sets
set_first = set(first_name)
set_last = set(last_name)
# a. Find common letters using intersection (&)
# This finds letters that exist in BOTH sets
common_letters = set_first.intersection(set_last)
# b. Find all letters using union (|)
# This combines both sets and removes duplicates
all_letters = set_first.union(set_last)
# 3. Output the results
print(f"\na. {common_letters}")
print(f"b. {all_letters}")
input("\nPress Enter to exit...")

Homework 2-2

Create a dictionary containing your first name, last name, age, city and graduation which is another dictionary containing university_name, field and is_graduated keys.

#!/usr/bin/env python3
"""Homework 2-2"""
print("It's homework 2-2\n")
# 1. Getting general information
f_name = input("Enter your first name: ")
l_name = input("Enter your last name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")
# 2. Getting graduation information (for the nested dictionary)
uni = input("Enter university name: ")
field = input("Enter your field of study: ")
# We check if the user typed 'yes' to set it as True
grad_status = input("Have you graduated? (yes/no): ").lower() == "yes"
# 3. Creating the nested dictionary
user_info = {
"first_name": f_name,
"last_name": l_name,
"age": age,
"city": city,
"graduation": {
"university_name": uni,
"field": field,
"is_graduated": grad_status
}
}
# 4. Printing the final dictionary to see the result
print("\nGenerated Dictionary:")
print(user_info)
input("\nPress Enter to exit...")

Homework 2-3

Given an integer n, return True if it is a power of two. Otherwise, return False. An integer n is a power of two, if there exists an integer x such that n == 2 ** x.

Hint:
The binary form of every 2 ** x likes 0b100...0
The binary form of every 2 ** x - 1 likes 0b11..1
Bitwise and between these two always lead to a certain answer

#!/usr/bin/env python3
"""Homework 2-3"""
print("It's homework 2-3\n")
# 1. Get the integer n from the user
n = int(input("Enter an integer: "))
# 2. Check the condition
# Condition 1: n must be greater than 0
# Condition 2: n AND (n-1) must be 0 (the bitwise trick)
is_power_of_two = (n > 0) and (n & (n - 1) == 0)
# 3. Output the result
print(f"\n{is_power_of_two}")
input("\nPress Enter to exit...")

Homework 2-4

Take file name as input and print its extension in output.

Example 1:

Input:
homework1.pdf

Output:
pdf

Example 2:

Input:
question7.py

Output:
py

Hint: Use split() method.

#!/usr/bin/env python3
"""Homework 2-4"""
print("It's homework 2-4\n")
# 1. Get the file name from the user
file_name = input("Enter the file name: ")
# 2. Split the string by the dot character
# This creates a list of parts
parts = file_name.split('.')
# 3. Get the last element of the list (which is the extension)
extension = parts[-1]
# 4. Output the result
print(f"\n{extension}")
input("\nPress Enter to exit...")

Homework 2-5

The following is a list of 10 students ages:

ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]

i. Find the range of the ages.
ii. Append following list to the ages:

[23, 18, 22, 24]

iii. How many unique ages are in the list?

#!/usr/bin/env python3
"""Homework 2-5"""
print("It's homework 2-5\n")
# 1. Get the first list of ages from the user
# User should enter numbers like: 19 22 19 24 20 25 26 24 25 24
input_ages = input("Enter the first list of ages (separated by space): ")
# Convert the string input into a list of integers
ages = [int(age) for age in input_ages.split()]
# i. Find the range of the ages
age_range = max(ages) - min(ages)
print(f"\ni. The range of ages is: {age_range}")
# 2. Get the second list to append
input_new = input("\nEnter the second list of ages to add (separated by space): ")
new_data = [int(age) for age in input_new.split()]
# ii. Extend the ages list
ages.extend(new_data)
print(f"\nii. Updated list: {ages}")
# iii. Count unique ages
unique_ages_count = len(set(ages))
print(f"\niii. Number of unique ages: {unique_ages_count}")
input("\nPress Enter to exit...")

Homework 2-6

Write a code which gives grade to students according to theirs scores:

80-100, A
70-89, B
60-69, C
50-59, D
0-49, F
#!/usr/bin/env python3
"""Homework 2-6"""
print("It's homework 2-6\n")
# 1. Get the student's score
score = float(input("Enter the student's score: "))
# 2. Determine the grade based on the score
if 80 <= score <= 100:
grade = "A"
elif 70 <= score < 80:
grade = "B"
elif 60 <= score < 70:
grade = "C"
elif 50 <= score < 60:
grade = "D"
elif 0 <= score < 50:
grade = "F"
else:
grade = "Invalid Score! (Please enter a number between 0 and 100)"
# 3. Output the result
print(f"\nThe grade is: {grade}")
input("\nPress Enter to exit...")

Homework 3-1

A number n is a Harshad (also called Niven) number if it is divisible by the sum of its digits. For example, 666 is divisible by 6 + 6 + 6, so it is a Harshad number.
Write a program to determine whether the given number is a Harshad number.

Example 1:

Input:
209

Output:
True

Example 2:

Input:
41

Output:
False

#!/usr/bin/env python3
"""Homework 3-1"""
print("It's homework 3-1\n")
# 1. Get the number from the user
number_str = input("Enter a number: ")
n = int(number_str)
# 2. Calculate the sum of its digits
# We iterate through each character in the string, convert it to int, and sum them
digit_sum = sum(int(digit) for digit in number_str)
# 3. Check divisibility
# A number is Harshad if n % digit_sum == 0
is_harshad = (n % digit_sum == 0)
# 4. Output the result
print(f"\n{is_harshad}")
input("\nPress Enter to exit...")

Homework 3-2

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.

Example 1:

Input:
[1,8,6,2,5,4,8,3,7]

Output:
49

Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Chart

#!/usr/bin/env python3
"""Homework 3-2"""
print("It's homework 3-2\n")
# 1. Get heights from the user
# User should enter numbers like: 1 8 6 2 5 4 8 3 7
user_input = input("Enter the heights separated by space: ")
# 2. Convert the string input into a list of integers
height = [int(h) for h in user_input.split()]
# 3. Two Pointers Logic
left = 0
right = len(height) - 1
max_water = 0
while left < right:
# Calculate current area
width = right - left
current_height = min(height[left], height[right])
current_area = width * current_height
# Update max_water if we found a larger container
max_water = max(max_water, current_area)
# Move the pointer of the shorter line to seek a taller one
if height[left] < height[right]:
left += 1
else:
right -= 1
# 4. Print the final result
print(f"\nThe maximum amount of water: {max_water}")
input("\nPress Enter to exit...")

Homework 3-3

Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and timeand-a-half for the hourly rate for all hours worked above 40 hours.

Example 1:

Input:
hours: 30
rate per hour: 100

Output: 3000

Example 2:

Input:
hours: 50
rate per hour: 100

Output:
5500

#!/usr/bin/env python3
"""Homework 3-3"""
print("It's homework 3-3\n")
# 1. Get hours and rate from the user
try:
hours = float(input("Enter hours: "))
rate = float(input("Enter rate per hour: "))
# 2. Check for overtime
if hours <= 40:
# Standard pay calculation
pay = hours * rate
else:
# Pay for first 40 hours
regular_pay = 40 * rate
# Pay for extra hours at 1.5x rate
overtime_hours = hours - 40
overtime_pay = overtime_hours * (rate * 1.5)
pay = regular_pay + overtime_pay
# 3. Output the result
print(f"\n{pay}")
except ValueError:
print("\nError, please enter numeric input")
input("\nPress Enter to exit...")

Homework 3-4

Take the discount code from the input and if it is valid, deduct 40% up to 10 dollars from the bill and print the price with and without discount in the output.
Discount code is “python2022”

Example 1:

Input:
discount code: pyton200
total price: 20

Output:
price without discount: 20
price with discount: 20

Example 2:

Input:
discount code: python2022
total price: 20

Output:
price without discount: 20
price with discount: 12

Example 3:

Input:
discount code: python2022
total price: 40

Output:
price without discount: 40
price with discount: 30

#!/usr/bin/env python3
"""Homework 3-4"""
print("It's homework 3-4\n")
# 1. Get inputs from user
user_code = input("discount code: ")
total_price = float(input("total price: "))
# 2. Set the valid discount code and rules
valid_code = "python2022"
discount_rate = 0.40
max_discount_amount = 10
# 3. Logic to calculate discount
final_price = total_price # Default if code is invalid
if user_code == valid_code:
# Calculate 40% of the price
calculated_discount = total_price * discount_rate
# Apply the cap (limit to 10 dollars)
actual_discount = min(calculated_discount, max_discount_amount)
# Calculate the price with discount
final_price = total_price - actual_discount
# 4. Output the results
print(f"\nprice without discount: {total_price}")
print(f"price with discount: {final_price}")
input("\nPress Enter to exit...")

Homework 3-5

Given a pH value, return whether that value is "alkaline" (greater than 7), "acidic" (less than 7), or "neutral" (7). Return "invalid" if the value given is less than 0 or greater than 14.

#!/usr/bin/env python3
"""Homework 3-5"""
print("It's homework 3-5\n")
# 1. Get the pH value from the user
try:
ph_value = float(input("Enter the pH value: "))
# 2. Check the conditions
if ph_value < 0 or ph_value > 14:
result = "invalid"
elif ph_value == 7:
result = "neutral"
elif ph_value < 7:
result = "acidic"
else:
result = "alkaline"
# 3. Output the result
print(f"\n{result}")
except ValueError:
print("\nPlease enter a valid number.")
input("\nPress Enter to exit...")

Homework 3-6

Given a word, create a dictionary that stores the indexes of each letter in a list.
Make sure the letters are the keys.
Make sure the letters are symbols.
Make sure the indexes are stored in a list and those lists are values.

Example 1:

Input:
python

Output:
{'p': [0], 'y': [1], 't': [2], 'h': [3], 'o': [4], 'n': [5]}

Example 2:

Input:
street

Output:
{'s': [0], 't': [1, 5], 'r': [2], 'e': [3, 4]}

#!/usr/bin/env python3
"""Homework 3-6"""
print("It's homework 3-6\n")
# 1. Get the word from the user
word = input("Enter a word: ")
# 2. Create an empty dictionary to store results
letter_map = {}
# 3. Iterate through the word using enumerate to get index and letter
for index, letter in enumerate(word):
# If the letter is already a key, append the new index to its list
if letter in letter_map:
letter_map[letter].append(index)
# If it's the first time we see this letter, create a new list with the index
else:
letter_map[letter] = [index]
# 4. Output the resulting dictionary
print(f"\n{letter_map}")
input("\nPress Enter to exit...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment