Homework and Popcorn Hacks for Lessons 3.2
Data Abstraction
- Integers : Whole number (cant be decimal) - Floats : Number with a decimal point - Strings : Data type that represents a sequence of character - Lists : Store multiple items in a single variable - Tuples : Similar to lists but can't be changeable. - Dictonaries : A statement containing keys unique and used to access a corresponding value - Sets : A collection of unordered, unique elements - Booleans : Data type that represents one of two possible values: True or False - None : Used to represent the absence of a value
Popcorn Hacks
# Step 1: Create a dictionary to map fruit names to numbers
fruit_dict = {
1: "Bananas",
2: "Apples",
3: "Pears"
}
# Step 2: Access and print the values using their corresponding keys
for key in fruit_dict:
print(f"Key {key}: {fruit_dict[key]}")
This code involves integers as dictionary keys and strings as values, so the integers being the numbers representing the strings (1,2,3), and the strings representing the fruits (Bananas, Apples, Pears). The system goes through the dictionary which I named as ‘fruit_dict’ and prints the fruits corresponding with their number.
%%js
function calculator() {
// Prompt user for the first number
const firstNumber = parseFloat(prompt("Enter the first number:"));
// Prompt user for the second number
const secondNumber = parseFloat(prompt("Enter the second number:"));
// Prompt user for the operation
const operation = prompt("Enter the operation (+, -, *, /):");
let result;
// Perform the calculation based on the operation
switch (operation) {
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
// Check for division by zero
if (secondNumber === 0) {
result = "Error: Division by zero!";
} else {
result = firstNumber / secondNumber;
}
break;
default:
result = "Invalid operation. Please use +, -, *, or /.";
}
// Display the result
console.log(`Result: ${result}`);
}
// Call the calculator function
calculator();
<IPython.core.display.Javascript object>
A calculator in Java script where users can input two numbers and select a mathematical operation to perform on them. The system then calculates and displays the result based on the operation chosen. I used the prompt() function to gather the users input for the two numbers and the desired operation. The input from the user is converted into a float variable used by this command parseFloat(), to have more accurate answers. I also used the switch command to switch between different operators like addition and subtraction.
# Simple Calculator in Python
def get_number(prompt):
while True:
try:
# Prompt user for a number and convert it to float
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a numeric value.")
def calculator():
# Get the first number with validation
first_number = get_number("Enter the first number: ")
# Get the second number with validation
second_number = get_number("Enter the second number: ")
# Prompt user for the operation
operation = input("Enter the operation (+, -, *, /): ")
# Perform the calculation based on the operation
if operation == '+':
result = first_number + second_number
elif operation == '-':
result = first_number - second_number
elif operation == '*':
result = first_number * second_number
elif operation == '/':
# Check for division by zero
if second_number == 0:
result = "Error: Division by zero!"
else:
result = first_number / second_number
else:
result = "Invalid operation. Please use +, -, *, or /."
# Display the result
print(f"Result: {result}")
# Call the calculator function
calculator()
A calculator in python where users can input two numbers and select a mathematical operation to perform on them. The system then calculates and displays the result based on the operation chosen. I used the get_number() function to gather the users input for the two numbers and the desired operation, and make sure they entered a valid numeric value. I also used the switch command to switch between different operators like addition and subtraction. Based on the chosen operation, it performs the corresponding arithmetic calculation.
def repeat_strings(strings, n):
"""
Repeat each string in the list n times.
Parameters:
strings (list of str): The list of strings to be repeated.
n (int): The number of times to repeat each string.
Returns:
list of str: A new list with each string repeated n times.
"""
# Using list comprehension to create the new list
return [s * n for s in strings]
# Example usage
original_list = ["apple", "banana", "cherry"]
n = 3
result = repeat_strings(original_list, n)
print(result)
Repeats each string in a list a specified number of times and returns a new list with the repeated strings. This function, repeat_strings(strings, n), takes 2 values the string and an integer saying how many times it should be repeated, For exampe in the code I put : original_list = [“apple”, “banana”, “cherry”], n = 3; This shows the list of strings and how many times they get repeated, so in this case apple would be appleappleapple.
def compare_sets(set1, set2):
"""
Compare two sets and check if there is a value in set2 that exists in set1.
Parameters:
set1 (set): The first set to compare.
set2 (set): The second set to compare.
Returns:
bool: True if any element in set2 is in set1, otherwise False.
"""
# Check for intersection between the two sets
return any(element in set1 for element in set2)
# Example usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
result = compare_sets(set1, set2)
print(result) # Output: True
set3 = {6, 7, 8}
result2 = compare_sets(set1, set3)
print(result2) # Output: False
This Python program compares two sets and checks if any element in the second set (set2) exists in the first set (set1). It returns True if there is at least one common element between the two sets and False otherwise, return any(element in set1 for element in set2), checks for any similarities between the 2 number sets. In set1 and set 2 there is a common number between 4 and 5, so it would output true.
Homework hacks
# Create variables
name = "Shriya"
age = 15
city = "San Diego"
favorite_color = "pink"
# Create the profile dictionary
profile = {
"name": name,
"age": age,
"city": city,
"favorite_color": favorite_color
}
# Print the profile dictionary
print(profile)
This Python program creates a user profile, with information about me using variables to store information like my name, age, city, and favorite color, and then stores this information in a dictionary by using a dictionary named profile, and storing the values inside. The dictionary is printed to display the profile data.
# Create a list of hobbies
hobbies = ["Hanging out with friends", "basketball", "Cyber Security"]
# Print the hobbies list
print(hobbies)
This was a pretty simple hack, I just set a variable caled hobbies, and set a value to it such as hanging out with friends, then used a print statement to print the value of hobbies.
# Choose a hobby from the hobbies list
chosen_hobby = "basketball" # Example hobby
# Set the availability of the hobby
has_hobby = True
# Print the message
print(f"Is {chosen_hobby} available today? {has_hobby}")
This Python program selects a hobby from a list and checks whether it is available on a particular day. It then prints a message indicating whether the hobby is available based on a Boolean value.
# Create a list of hobbies
hobbies = ["Hanging out with friends", "basketball", "Cyber Security"]
# Calculate the total number of hobbies
total_hobbies = len(hobbies)
# Print the message
print(f"I have {total_hobbies} hobbies.")
This Python program creates a list of hobbies, calculates how many hobbies are in the list, and prints a message displaying the total number of hobbies.
# Create a tuple of favorite hobbies
favorite_hobbies = ("basketball", "hanging out with friends", "Cyber Security")
# Print the favorite_hobbies tuple
print(favorite_hobbies)
Using a variable of favorite_hobbies I set a value of my favorite hobbies then used the print statement to print the value of the variable.
# Create a set of skills
skills = {"Sympathetic", "problem-solving", "reliability"}
# Print the set of skills
print(skills)
The variable skills is a set containing skills, and I used the print statement to print out these skills.
# Create a variable for the new skill and set it to None
new_skill = None
# Print the value of new_skill
print(new_skill)
This Python program creates a variable for a new skill and sets its value to None, then prints the value of that variable.
# Define the costs
hobby_cost = 5.0 # Cost per hobby
skill_cost = 10.0 # Cost per skill
# Calculate the number of hobbies and skills
total_hobbies = 3 # Example number of hobbies
total_skills = 3 # Example number of skills
# Calculate the total cost
total_cost = (total_hobbies * hobby_cost) + (total_skills * skill_cost)
# Print the total cost
print(f"The total cost to develop all hobbies and skills is: ${total_cost:.2f}")
This program calculates the total cost of developing hobbies and skills by multiplying the number of each with their respective costs. It then prints the total, formatted to two decimal places for better readability, showing the final expense.