Created
February 10, 2025 03:29
-
-
Save iojini/cceff36d13cc01e00d52bab3dc70dff1 to your computer and use it in GitHub Desktop.
Lesson 10 Assignment (also includes assignments for Lessons 11, 12, and 13)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Homework Lesson 10 - Workshop - Homework | |
# READ CAREFULLY THE EXERCISE DESCRIPTION AND SOLVE IT RIGHT AFTER IT | |
################################################################################ | |
### When solving coding challenges, think about the time complexity (Big O). ### | |
################################################################################ | |
# Challenge 1 | |
# Multiplication of a three-digit number | |
# | |
# A program gets a three-digit number and has to multiply all its digits. | |
# For example, if a number is 349, the code has to print the number 108, because 3*4*9 = 108. | |
# | |
# Hints: | |
# Use the modulus operator % to get the last digit. | |
# Use floor division to remove the last digit | |
def multiplication_of_three(number): | |
last_digit = number % 10 | |
number = number // 10 | |
middle_digit = number % 10 | |
first_digit = number // 10 | |
return first_digit*middle_digit*last_digit | |
print(multiplication_of_three(349)) | |
# --------------------------------------------------------------------- | |
# Challenge 2 | |
# Sum and multiplication of even and odd numbers. | |
# | |
# You are given an array of integers. Your task is to calculate two values: the sum of | |
# all even numbers and the product of all odd numbers in the array. Please return these | |
# two values as a list [sum_even, multiplication_odd]. | |
# | |
# Example | |
# For the array [1, 2, 3, 4]: | |
# | |
# The sum of all even numbers is 2 + 4 = 6. | |
# The product of all odd numbers is 1 * 3 = 3. | |
# The function should return the list [6, 3]. | |
def sum_even_and_product_odd(arr): | |
# Initialize variables for the sum of even numbers and the product of odd numbers | |
sum_even = 0 | |
product_odd = 1 | |
# Your code here | |
for i in arr: | |
if i % 2 == 0: | |
sum_even += i | |
else: | |
product_odd *= i | |
return [sum_even, product_odd] | |
print(sum_even_and_product_odd([1, 2, 3, 4])) | |
# --------------------------------------------------------------------- | |
# Challenge 3 | |
# Invert a list of numbers | |
# | |
# Given a list of numbers, return the inverse of each. Each positive becomes a negative, | |
# and the negatives become positives. | |
# | |
# Example: | |
# Input: [1, 5, -2, 4] | |
# Output: [-1, -5, 2, -4] | |
def invert_list(arr): | |
new_list = [] | |
for i in arr: | |
new_list.append(-1 * i) | |
return new_list | |
print(invert_list([1, 5, -2, 4])) | |
# --------------------------------------------------------------------- | |
# Challenge 4 | |
# Difference between | |
# | |
# Implement a function that returns the difference between the largest and the | |
# smallest value in a given list. | |
# The list contains positive and negative numbers. All elements are unique. | |
# | |
# Example: | |
# Input: [3, 5, 7, 2] | |
# Output: 7 - 2 = 5 | |
def max_diff(arr): | |
# Check if the list is empty | |
# If it is, return 0 as there's no difference to be calculated | |
if len(arr) == 0: | |
return 0 | |
# If the list is not empty, | |
# proceed with the rest of the code. | |
# Your code here | |
return max(arr) - min(arr) | |
print(max_diff([3, 5, 7, 2])) | |
# --------------------------------------------------------------------- | |
# Challenge 5 | |
# Sum between range values | |
# You are given an array of integers and two integer values, min and max. | |
# Your task is to write a function that finds the sum of all elements in the | |
# array that fall within the range [min, max], inclusive. | |
# | |
# Example: | |
# arr = [3, 2, 1, 4, 10, 8, 7, 6, 9, 5] | |
# min_val = 3 | |
# max_val = 7 | |
# | |
# Output: 25 (3 + 4 + 5 + 6 + 7) | |
# | |
# Hint: Iterate through each number (num) in the array (arr) and check if the current number falls within the range [min_val, max_val]. | |
def sum_between_range(arr, min_val, max_val): | |
sum_range = 0 | |
for i in arr: | |
if i >= min_val and i <= max_val: | |
sum_range += i | |
return sum_range | |
print(sum_between_range([3, 2, 1, 4, 10, 8, 7, 6, 9, 5], 3, 7)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# HOMEWORK Lesson 11: Dictionaries | |
# Read carefully until the end before you start solving the exercises. | |
from lesson_6.practice_005_aggregators_helpers import employees | |
# Basic Dictionary | |
# Create an empty dictionary and then add a few of your friends. Make the key their email (can be fake) | |
# and the value their name. When you're done, create the same dictionary as a pre-populated dictionary. | |
#First Dictionary | |
friends = {} | |
friends["rachel.green@gmail.com"] = "Rachel Green" | |
friends["monica.gellar@gmail.com"] = "Monica Geller" | |
friends["phoebe.buffay@gmail.com"] = "Phoebe Buffay" | |
#Second Dictionary | |
friends1 = { | |
"rachel.green@gmail.com": "Rachel Green", | |
"monica.gellar@gmail.com": "Monica Geller", | |
"phoebe.buffay@gmail.com": "Phoebe Buffay" | |
} | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Nested Dictionary | |
# Create a nested dictionary for a list of 5 company employees. | |
# The key should be their employee id (an integer from 1-5 will do) and the value should be a dictionary with | |
# the name, department and salary of the employee. | |
employees = { | |
1: {"name": "Monica Geller", "department": "Culinary", "salary": 80000}, | |
2: {"name": "Rachel Green", "department": "Fashion", "salary": 60000}, | |
3: {"name": "Phoebe Buffay", "department": "Physical Therapy", "salary": 90000}, | |
4: {"name": "Ross Geller", "department": "Paleontology", "salary": 100000}, | |
5: {"name": "Joseph Tribbiani", "department": "Theater", "salary": 300000}, | |
} | |
print(employees) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Accessing Values | |
# Use the previous nested dictionary and write some print statements that will answer the following: | |
# - Print a list of the employee IDs | |
print(employees.keys()) | |
# - Print the employee data for employee with the ID 3. | |
print(employees[3]) | |
# - Loop over the employees and print all their names and salaries. | |
for employee_id, employee_info in employees.items(): | |
print(f"{employee_info['name']}, {employee_info['salary']}") | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Updating Values | |
# We have the following dictionary with employee salaries. | |
salaries = { | |
'james' : 10000, | |
'tom' : 15000, | |
'ryan' : 16000, | |
'julia' : 17000 | |
} | |
# We need to increase everyone's salary by 1,000 and also add a new employee joseph with a salary of 18,000. | |
# Please come up with a way to do this using update() | |
salaries.update({employee: salary + 1000 for employee, salary in salaries.items()}) | |
salaries.update({'joseph': 18000}) | |
print(salaries) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Deleting Values | |
# You remember those employees from Updating Values section? Well, Julia got fired, so we need to remove her | |
# name from the salaries dictionary. How would you do that? | |
del salaries["julia"] | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Iterating over Dictionaries | |
# Given the list of movies below, please use view objects (keys(), values(), items() - where necessary) to answer | |
# the questions: | |
films = { | |
2016: "Star Wars: Episode VII - The Force Awakens", | |
2017: "Star Wars: Episode VIII - The Last Jedi", | |
2018: "Black Panther", | |
2019: "Avengers: Endgame", | |
2020: "Bad Boys for Life" | |
} | |
# - Is Black Panther in the list of movies? | |
if "Black Panther" in films.values(): | |
print("Yes") | |
else: | |
print("No") | |
# - Is there any movie for the year 2021? | |
if 2021 in films.keys(): | |
print("Yes") | |
else: | |
print("No") | |
# - Print a message for each element that shows the year, the title and the position in the dictionary (1-5). | |
# Hint: use a counter. | |
counter = 1 | |
for year, title in films.items(): | |
print(f"{counter}: {year}: {title}") | |
counter += 1 | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 1. Animal Shelter Volunteer | |
# You volunteer in a local animal shelter and you've stored information | |
# about different pets in a Python dictionary. | |
# Your task is to create a Python program that helps you: | |
# - Access the age of specific pets by their names. | |
# - Find out which pets are not yet adopted. | |
# - Identify the most common animal type in the shelter (e.g., dog, cat). | |
# Pre-code | |
# Initialize the shelter_pets dictionary | |
shelter_pets = { | |
'Whiskers': {'Age': 2, 'Type': 'Cat', 'Adopted': False}, | |
'Fido': {'Age': 4, 'Type': 'Dog', 'Adopted': True}, | |
'Patch': {'Age': 1, 'Type': 'Dog', 'Adopted': False}, | |
'Snowball': {'Age': 3, 'Type': 'Rabbit', 'Adopted': True} | |
} | |
# Access and print the age of Whiskers | |
print(shelter_pets['Whiskers']['Age']) # Should output 2 | |
# Access and print if Patch is a dog or cat | |
print(shelter_pets['Patch']['Type']) | |
# Access and print if Snowball is adopted or not | |
print(shelter_pets['Snowball']['Adopted']) | |
# Find out which pets are not yet adopted and print their names | |
for pet, info in shelter_pets.items(): | |
if not info['Adopted']: | |
print(pet) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 2. Best - selling books | |
# Create a Python program to manage a collection of best-selling books | |
# and their publication years. Your initial list of best-selling books may have inaccuracies | |
# or could be outdated. Therefore, you'll also practice updating single and multiple entries | |
# in your dictionary. Specifically, you will: | |
# - Update the title of a book for a specific year due to a naming convention change. | |
# - Update the titles for multiple books at once based on new sales data. | |
# - Delete a book and its year from the collection as it's no longer considered a best-seller. | |
# - Print the title of the book published in a specific year. | |
# Pre-code: | |
# Initialize a dictionary called best_selling_books to store your collection. | |
best_selling_books = { | |
1997: "Harry Potter and the Philosopher's Stone", | |
1984: "Neuromancer", | |
2003: "The Kite Runner", | |
2015: "Go Set a Watchman" | |
} | |
# The U.S. title for the Harry Potter book published in 1997 is "Harry Potter and the Sorcerer's Stone". | |
# Update the title to its U.S. version. | |
best_selling_books[1997] = "Harry Potter and the Sorcerer's Stone" | |
# New sales data reveals that "The Hunt for Red October" was the actual best-seller for 1984 | |
# and "The Da Vinci Code" for 2003. | |
# Update these in a single operation. | |
best_selling_books.update({ | |
1984: "The Hunt for Red October", | |
2003: "The Da Vinci Code" | |
}) | |
# The book published in 2015, "Go Set a Watchman," is no longer considered a best-seller. | |
# Use the del keyword to remove this entry from the dictionary. | |
del best_selling_books[2015] | |
# Print the updated dictionary of best selling books. | |
print(best_selling_books) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 3. Manage Music Collection | |
# Create a Python program that manages a collection of music albums and their release years. | |
# You will use a dictionary where the keys are the release years and the values are the names of albums. | |
# The program should allow you to: | |
# - Print all the release years (keys) from the dictionary. | |
# - Print all the album names (values) from the dictionary. | |
# - Print both the release years and album names together. | |
# - Check if a particular year or album exists in the collection. | |
# Steps and pre-code | |
#Initialize a dictionary to store Bob Dylan's albums | |
dylan_albums = { | |
1962: "Bob Dylan", | |
1963: "The Freewheelin' Bob Dylan", | |
1975: "Blood on the Tracks", | |
1997: "Time Out of Mind" | |
} | |
# Use .keys() to loop through and print out all the release years | |
for year in dylan_albums.keys(): | |
print(year) | |
# Use .values() to loop through and print out all the album names | |
for album in dylan_albums.values(): | |
print(album) | |
# Use .items() to loop through and print out both the release year and album name | |
for year, album in dylan_albums.items(): | |
print(f"{year}: {album}") | |
# Use the 'in' keyword to check if a particular year or album is in the dictionary (pick any year and any album) | |
# Remember the keyword by default checks only the keys, not the values. | |
# If you want to check if a particular value (in this case, an album name), | |
# you need to specify that you're searching within the dictionary's values. | |
specific_year = 1997 | |
specific_album = "Time Out of Mind" | |
if specific_year in dylan_albums: | |
print("Yes") | |
else: | |
print("No") | |
if specific_album in dylan_albums.values(): | |
print("Yes") | |
else: | |
print("No") | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 4. Remove duplicates | |
# Remove duplicates from the following dictionary: | |
person = { | |
'first': 'Jeff', | |
'name': 'Jeff', | |
'last': 'Smith', | |
'last_name': 'Smith', | |
'state': 'CA', | |
'age': 55 | |
} | |
# Steps: | |
# - Create a dict person | |
# - Create an empty dictionary result = {} | |
# - Make a for loop to iterate over person dictionary | |
# - If item’s value not in result dict, add key value part into result. | |
person = { | |
'first': 'Jeff', | |
'name': 'Jeff', | |
'last': 'Smith', | |
'last_name': 'Smith', | |
'state': 'CA', | |
'age': 55 | |
} | |
result = {} | |
for key, value in person.items(): | |
if value not in result.values(): | |
result[key] = value | |
print(result) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 5. Find the highest score | |
# Create a Python function named find_max_score that takes a dictionary of names and scores as an argument. | |
# The function should return the name and score of the person with the highest score in the form of a dictionary. | |
# Sample test_scores dictionary | |
test_scores = { | |
'James': 83, | |
'Julia': 91, | |
'Ryan': 90, | |
'Maria': 80, | |
'David': 79, | |
'Adam': 96, | |
'Jennifer': 97, | |
'Susan': 77 | |
} | |
# Find the person with the highest test score and display both their name and score | |
# Steps: | |
# - Define a function called find_max_score that takes one argument, scores_dict, which is a dictionary of names | |
# (as keys) and scores (as values). | |
# - Create an empty result variable | |
# - Assume the initial maximum score is 0 | |
# - Iterate over each key-value pair in the test_scores, using the .items() method | |
# - Check if the current score (v) is >= to the current maximum score | |
# - If so, update the max score and assign the key-value pair to the result | |
# - Return result and test the function | |
def find_max_score(scores_dict): | |
result = {} | |
max_score = 0 | |
for key, value in scores_dict.items(): | |
if value >= max_score: | |
max_score = value | |
result = {"name": key, "score": value} | |
return result | |
print(find_max_score(test_scores)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Homework Lesson 12: Classes | |
# Read carefully until the end before you start solving the exercises. | |
# Practice the Basics | |
# Basic Class | |
# - Create an empty class HouseForSale | |
# - Create two instances. | |
# - Add number_of_rooms and price as instance attributes. | |
# - Create print statements that show the attribute values for the instances. | |
class HouseForSale: | |
pass | |
house1 = HouseForSale() | |
house2 = HouseForSale() | |
house1.number_of_rooms = 3 | |
house1.price = 300000 | |
house2.number_of_rooms = 4 | |
house2.price = 400000 | |
print(f"House 1 - Rooms: {house1.number_of_rooms}, Price: ${house1.price}") | |
print(f"House 2 - Rooms: {house2.number_of_rooms}, Price: ${house2.price}") | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Instance Methods | |
# - Create a Computer class. | |
# - Create method: | |
# - turn_on that prints Computer has Turned On | |
# - turn_off that prints Computer has Turned Off | |
# - Create an instance of the Computer class then call each method. | |
class Computer: | |
def turn_on(self): | |
print("Computer has Turned On") | |
def turn_off(self): | |
print("Computer has Turned Off") | |
my_computer = Computer() | |
my_computer.turn_on() | |
my_computer.turn_off() | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Constructor with Parameters | |
# - Create a Dog class. | |
# - Dog should have a constructor with a name parameter. | |
# - Dog should have a method say_name that prints the name of the dog. | |
class Dog: | |
def __init__(self, name): | |
self.name = name | |
def say_name(self): | |
print(f"{self.name}") | |
dog_name = Dog("Charizard") | |
dog_name.say_name() | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Inheritance | |
# Create the classes that would make the following code possible, with the caveat that | |
# both Dog and Cat must inherit from Animal. | |
class Animal: | |
def __init__(self, name=None): | |
self.name = name | |
def say_name(self): | |
if self.name is None: | |
print("I don't have a name yet.") | |
else: | |
print(self.name) | |
def speak(self): | |
print("I can't speak!") | |
class Dog(Animal): | |
def __init__(self, name): | |
super().__init__(name) | |
def speak(self): | |
print("Woof!") | |
class Cat(Animal): | |
def __init__(self, name): | |
super().__init__(name) | |
def speak(self): | |
print("Meow!") | |
animal = Animal() | |
animal.say_name() # Prints: I don't have a name yet. | |
animal.speak() # Prints: I can't speak! | |
dog = Dog('Fido') | |
dog.say_name() # Prints: Fido | |
dog.speak() # Prints: Woof! | |
cat = Cat('Max') | |
cat.say_name() # Prints: Max | |
cat.speak() # Prints: Meow! | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercises | |
# Exercise 1: Books and Authors | |
# Create an empty class called Book. Then create three instances. | |
# Add the following attributes for each of the instances: title, author, and publication_year. | |
# Create print statements to display the attributes of each one of the instances. | |
# Pre-code: | |
class Book: | |
pass | |
# book1 = Book() | |
# book1.t??? = 'To Kill a Mockingbird' | |
# book1.a??? = 'Harper Lee' | |
# book1.p??? = 1960 | |
# Your code here | |
book1 = Book() | |
book1.title = 'To Kill a Mockingbird' | |
book1.author = 'Harper Lee' | |
book1.publication_year = 1960 | |
book2 = Book() | |
book2.title = 'The Hobbit' | |
book2.author = 'J. R. R. Tolkien' | |
book2.publication_year = 1937 | |
book3 = Book() | |
book3.title = 'A Tale of Two Cities' | |
book3.author = 'Charles Dickens' | |
book3.publication_year = 1859 | |
print("Book 1:") | |
print("Title:", book1.title) | |
print("Author:", book1.author) | |
print("Publication Year:", book1.publication_year) | |
print() | |
print("Book 2:") | |
print("Title:", book2.title) | |
print("Author:", book2.author) | |
print("Publication Year:", book2.publication_year) | |
print() | |
print("Book 3:") | |
print("Title:", book3.title) | |
print("Author:", book3.author) | |
print("Publication Year:", book3.publication_year) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 2. Vehicle and Types of Vehicles | |
# Create a Vehicle class. | |
# - Its constructor should take the name and type of the vehicle and store them as instance attributes. | |
# - This Vehicle class should also have a show_type() instance method that prints out the | |
# message: "<NAME_OF_VEHICLE> is a <TYPE_OF_VEHICLE>" | |
# - Create Car and Bike classes that inherit from Vehicle. | |
# - Create instances of Car and Bike and make them show their types. | |
class Vehicle: | |
def __init__(self, name, vehicle_type): | |
self.name = name | |
self.vehicle_type = vehicle_type | |
def show_type(self): | |
print(f"{self.name} is a {self.vehicle_type}") | |
class Car(Vehicle): | |
pass | |
class Bike(Vehicle): | |
pass | |
car = Car("Toyota Camry", "Car") | |
bike = Bike("Harley Davidson", "Bike") | |
car.show_type() | |
bike.show_type() | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 3. Spot and correct the mistakes | |
# - You are given a task to create a Car class. | |
# - Each car will have attributes for model and year. | |
# - Unfortunately, the given code below contains several mistakes. | |
# - Your task is to find and correct these mistakes to make the code run successfully. | |
# - Please include a comment in the code explaining the corrections you made and why. | |
# Pre-code | |
# (1) added self to first parameter of init method; | |
# (2) assigned model to self.model instance attribute; | |
# (3) assigned year to self.year instance attribute | |
# (4) need both arguments to create Car instance so added year | |
# (5) | |
class Car: | |
def __init__(self, model, year): | |
self.model = model | |
self.year = year | |
my_car = Car("Toyota", 2024) | |
print(my_car.model) | |
print(my_car.year) | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 4. SmartHome with Constructor | |
# Create a SmartHome class that has a constructor __init__ and a send_notification() method. | |
# | |
# The constructor should initialize the attributes: | |
# - home_name | |
# - location | |
# - number_of_devices | |
# | |
# send_notification() should print a notification including the home_name and location. | |
# Create instances for the following: | |
# Home Name Location Number of Devices | |
# Villa Rosa New York 15 devices | |
# Green House California 10 devices | |
# Sea View Florida 20 devices | |
# Call the send_notification() method for each instance, | |
# passing a message reminding to turn off the lights. | |
class SmartHome: | |
def __init__(self, home_name, location, number_of_devices): | |
self.home_name = home_name | |
self.location = location | |
self.number_of_devices = number_of_devices | |
def send_notification(self, message): | |
print(f"{self.home_name}, {self.location}: {message}") | |
home1 = SmartHome("Villa Rosa", "New York", 15) | |
home2 = SmartHome("Green House", "California", 10) | |
home3 = SmartHome("Sea View", "Florida", 20) | |
home1.send_notification("Please remember to turn off the lights.") | |
home2.send_notification("Please remember to turn off the lights.") | |
home3.send_notification("Please remember to turn off the lights.") | |
# ---------------------------------------------------------------------------------------------------------------------- | |
# Exercise 5. Inheritance. Spot and correct mistakes | |
# You should have the following hierarchy of classes: | |
# Animal | |
# │ | |
# ├── Mammal | |
# │ | |
# ├── Bird | |
# │ | |
# └── Fish | |
# Each class has the following attributes: | |
# - Animal name | |
# - Mammal name, age, number of legs | |
# - Bird name, age, can fly or not | |
# - Fish name, age, number of fins | |
# But, the provided code for these classes and their instances has several mistakes | |
# related to hierarchy, class attributes, and instance creation. | |
# Find and correct these mistakes to make the code work properly. | |
# Leave a comment in the code explaining what the problems were and why it wouldn't work. | |
# There are seven mistakes in the pre-code. | |
# Pre-code | |
# (1) name needs to be assigned to self.name instance attribute | |
# (2) age needs to be assigned to self.age instance attribute | |
# (3) Mammal class needs to inherit from Animal class (Animals class doesn't exist) | |
# (4) According to the instructions, the bird class should have name and age attributes | |
# (5) According to the hierarchy, fish should be a subclass of Animal | |
# (6) need name and age arguments to sparrow Car instance so added name and age | |
# (7) num_fins should be an integer; goldfish have 5 fins | |
class Animal: | |
def __init__(self, name, age): | |
self.name = name | |
self.age = age | |
class Mammal(Animal): | |
def __init__(self, name, age, num_legs): | |
super().__init__(name, age) | |
self.num_legs = num_legs | |
class Bird(Animal): | |
def __init__(self, name, age, can_fly): | |
super().__init__(name, age) | |
self.can_fly = can_fly | |
class Fish(Animal): | |
def __init__(self, name, age, num_fins): | |
super().__init__(name, age) | |
self.num_fins = num_fins | |
tiger = Mammal('Tiger', 5, 4) | |
sparrow = Bird('Sparrow', 3, True) | |
goldfish = Fish('Goldfish', 2, 5) | |
print(f"Mammal: {tiger.name}, Age: {tiger.age}, Legs: {tiger.num_legs}") | |
print(f"Bird: {sparrow.name}, Age: {sparrow.age}, Can Fly: {sparrow.can_fly}") | |
print(f"Fish: {goldfish.name}, Age: {goldfish.age}, Fins: {goldfish.num_fins}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Homework Lesson 13 - Workshop - Homework | |
# READ CAREFULLY THE EXERCISE DESCRIPTION AND SOLVE IT RIGHT AFTER IT | |
################################################################################ | |
### When solving coding challenges, think about the time complexity (Big O). ### | |
################################################################################ | |
# Challenge 1 | |
# Common Elements Finder | |
# Given two lists of integers, find and return a new list containing elements that appear in both lists. | |
# Make sure the resulting list does not contain duplicates. | |
# Example: | |
# Input: | |
# List 1: [1, 2, 3, 4, 5] | |
# List 2: [4, 5, 6, 7, 8] | |
# Output: [4, 5] | |
# Hints: | |
# You'll need to use nested loops: The outer loop will iterate over elements in the first list, | |
# and the inner loop will check if that element exists in the second list. | |
# Keep track of the common elements found so far to ensure no duplicates are added to the resulting list. | |
# To ensure no duplicates are added to the resulting list, | |
# check if an element is already present in the "common" list before appending it. | |
def find_common_elements(list1, list2): | |
common = [] | |
for i in list1: | |
for j in list2: | |
if i == j and i not in common: | |
common.append(i) | |
return common | |
print(find_common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])) | |
# --------------------------------------------------------------------- | |
# Refresher | |
# One of the key skills during job interviews | |
# is to be able to modify the code you've created. | |
# The following two tasks are the extension of the recipe problem you solved in class. | |
# Let's refresh the problem you solved in the class. | |
# You have a list of recipes, where each recipe contains the ingredients each recipe needs: | |
# recipes = [ | |
# ["yeast","flour"], | |
# ["bread","meat"], | |
# ["flour","meat"] | |
# ] | |
# Solution | |
def find_makeable_recipes(recipes, ingredients): | |
makeable_recipes = [] | |
for recipe in recipes: | |
can_make = True | |
for ingredient in recipe: | |
if ingredient not in ingredients: | |
can_make = False | |
break | |
if can_make: | |
makeable_recipes.append(recipe) | |
return makeable_recipes | |
test_recipes = [["yeast", "flour"], ["bread", "meat"], ["flour", "meat"]] | |
test_ingredients = ["yeast", "flour", "meat"] | |
test_result = find_makeable_recipes(test_recipes, test_ingredients) | |
print(test_result) | |
# --------------------------------------------------------------------- | |
# Challenge 2 | |
# Missing ingredients | |
# You have a new list of recipes and ingredients. | |
# recipes = [ | |
# ["yeast", "flour"], | |
# ["bread", "meat", "flour"] | |
# ] | |
# ingredients = ["yeast","bread"] | |
# Return the list of missing ingredients for all the recipes. | |
# Output: ["flour","meat"] | |
def find_missing_ingredients(recipes, ingredients): | |
# Create an empty list to store the missing ingredients | |
missing = [] | |
# In the outer loop iterate through each recipe in the list of recipes. | |
for recipe in recipes: | |
# In the inner loop check each ingredient in the recipe. | |
for ingredient in recipe: | |
# Check if the ingredient is not in the list of available ingredients | |
# and is not already in the list of missing ingredients. | |
if ingredient not in ingredients and ingredient not in missing: | |
# If both conditions are met, add the ingredient to the missing_ingredients list. | |
missing.append(ingredient) | |
# Return the list of missing ingredients required for all the recipes. | |
return missing | |
recipes = [ | |
["yeast", "flour"], | |
["bread", "meat", "flour"] | |
] | |
ingredients = ["yeast","bread"] | |
print(find_missing_ingredients(recipes, ingredients)) | |
# --------------------------------------------------------------------- | |
# Challenge 3 | |
# The best recipe | |
# You have a new list of recipes, where each recipe contains the ingredients it needs. | |
# recipes = [ | |
# ["yeast","flour"], | |
# ["bread","meat"], | |
# ["flour","meat", "yeast"] | |
# ] | |
# You also have a list of available ingredients. | |
# ingredients = ["yeast","flour", "meat", "salt"] | |
# Return the list of the best recipe (the one that uses most of ingredients). | |
# Output: ["flour","meat", "yeast"] | |
def find_best_recipe(recipes, ingredients): | |
# Initialize variables to remember the best recipe and the most ingredients used. | |
best_recipe = None | |
max_used_ingredients = 0 | |
# Create an outer for loop to go through each recipe in the list of recipes. | |
for recipe in recipes: | |
# Create an empty list (used_ingredients) to store the ingredients we can use from this recipe. | |
used_ingredients = [] | |
# Create an inner foor loop to look at each ingredient in this recipe. | |
for ingredient in recipe: | |
# Check if the ingredient is in our list of available ingredients. | |
if ingredient in ingredients: | |
# If it's available, add it to our list of used ingredients. | |
used_ingredients.append(ingredient) | |
# Check if the current recipe uses more ingredients (using `len` to count) | |
# than the highest count we've recorded so far (max_used_ingredients). | |
if len(used_ingredients) > max_used_ingredients: | |
# If the current recipe has a higher ingredient count, update max_used_ingredients. | |
# Then set this recipe as the new best. | |
max_used_ingredients = len(used_ingredients) | |
best_recipe = recipe | |
# Finally, return the best recipe that uses the most ingredients. | |
return best_recipe | |
# Define the list of recipes and available ingredients. | |
recipes = [ | |
["yeast","flour"], | |
["bread","meat"], | |
["flour","meat", "yeast"] | |
] | |
ingredients = ["yeast","flour", "meat", "salt"] | |
# Call the function to find the best recipe and print the result. | |
print(find_best_recipe(recipes, ingredients)) | |
# --------------------------------------------------------------------- | |
# Challenge 4 | |
# Find a peak element | |
# You are given an array of integers, and your goal is to find a "peak" element in the array. | |
# A peak element is an element that is strictly greater than its adjacent elements (elements on the left and on the right). | |
# Write a Python function find_peak_element(arr) that takes an array of integers as input | |
# and returns the index of the peak element in the array. | |
# Handle edge cases: | |
# - If the array has fewer than three elements, return -1. | |
# Check each element in the array: | |
# - If an element is strictly greater than both its adjacent elements (if they exist), consider it a peak element. | |
# - Return the index of the first peak element you find. | |
# - If no peak elements are found, return -1. | |
# Example: | |
# arr1 = [1, 3, 20, 4, 1, 0] | |
# result1 = find_peak_element(arr1) | |
# print(result1) # Output: 2 (Peak element: 20) | |
# arr2 = [1, 2, 3, 4, 5] | |
# result2 = find_peak_element(arr2) | |
# print(result2) # Output: -1 (No peak elements) | |
# arr3 = [5, 10, 20, 15] | |
# result3 = find_peak_element(arr3) | |
# print(result3) # Output: 2 (Peak element: 20) | |
def find_peak_element(arr): | |
n = len(arr) # Find out how many elements are in the array | |
# Check for the edge case (less than 3 elements) | |
if n < 3: | |
return -1 | |
# Check the first and last element separately as they don't have neighbors | |
for i in range(1, n - 1): | |
# Iterate over the range, excluding the first and last indices, as they lack one neighbor. | |
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: | |
return i | |
# Return -1 # if no peak element is found. | |
return -1 | |
print(find_peak_element([1, 3, 20, 4, 1, 0])) | |
print(find_peak_element([1, 2, 3, 4, 5])) | |
print(find_peak_element([5, 10, 20, 15])) | |
# --------------------------------------------------------------------- | |
# Challenge 5 (optional) | |
# Delete duplicates in sorted lists | |
# Given a sorted list of integers, write a program that: | |
# - Removes all duplicate values from the list. | |
# - Shifts the unique values to the left to fill any emptied indices. | |
# - Fills the remaining rightmost indices with zeroes. | |
# - Returns the count of unique values in the list. | |
# - Example: | |
# Input: [1, 2, 2, 3, 4, 4, 4, 5] | |
# Output: [1, 2, 3, 4, 5, 0, 0, 0], 5 (5 unique values) | |
# Hints: | |
# - Sequential Comparison: Since the list is sorted, duplicates will always be adjacent to each other. | |
# Compare each element to the previous one to detect duplicates. | |
# - Updating in Place: You can modify the original list as you find unique numbers | |
# and move them to the correct position. Think of this position as where the next unique number should go. | |
def delete_duplicates(arr): | |
# 'write_index' points to where the next unique element should be written. | |
write_index = 1 | |
# Iterate over the list's length, starting from the second element because | |
# the first element doesn't have a previous element to compare against. | |
for i in range(1, len(arr)): | |
# Compare the current element with its immediate previous element. | |
if arr[i] != arr[i - 1]: | |
# If they're different, it's not a duplicate. | |
# Place the current element at the 'write_index' position. | |
arr[write_index] = arr[i] | |
# Then increment 'write_index' by 1 to prepare for the next unique element. | |
write_index += 1 | |
# Once you have shifted all unique elements to the left, | |
# fill the remaining positions in the list with zeroes. | |
for i in range(write_index, len(arr)): | |
arr[i] = 0 | |
# Return the modified list for visualization and the count of unique elements. | |
return arr, write_index | |
print(delete_duplicates([1, 2, 2, 3, 4, 4, 4, 5])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment