'''
duration = 30
print("Code sent")
for second in range(duration):
elapsed = second + 1
print("Elapsed:", elapsed)
print("Code expired")
'''
'''
duration = 30
print("Code sent")
for second in range(duration):
countdown = duration - second
print("Countdown:", countdown)
print("Code expired")
'''
'''
duration = 30
print("Code sent")
for second in range(duration):
countdown = duration - second
past_halfway = duration/2 >= countdown
print("Countdown:", countdown, "Halfway?", past_halfway)
print("Code expired")
'''
'''
duration = 30
print("Code sent")
for second in range(duration):
countdown = duration - second
warning = countdown <= 10
print("Countdown:", countdown, "Warning?", warning)
print("Code expired")
'''
'''
duration = 30
for second in range(duration):
countdown = duration - second
print(countdown)
'''
'''
duration = 30
print("Code sent")
for second in range(duration):
countdown = duration - second
warning = countdown <= 10
print("Countdown:", countdown, "Warning?", warning)
print("Code expired")
'''
'''
# 1. Read the first input (the count of numbers)
n = int(input())
# Initialize the running sum to zero
res = 0
# 2. Loop 'n' times
for i in range(n):
# Read the next whole number
a = int(input())
# 3. Add the number 'a' to the running sum 'res'
res += a
# 4. Print the final sum
print(res)
'''
'''
duration = 60
countdown = 30
for second in range(duration):
print("Countdown:", countdown)
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
print("Countdown:", countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown > 0:
status = "active ✅"
else:
status = "expired ❌"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if countdown > 0 and countdown <= 10:
status = "warning ⚠️"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if countdown > 0 and countdown <= 10:
status = "warning ⚠️"
if status == "expired ❌":
left = duration - second
print("Code", status, "Request new code?", left)
else:
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
def sum_numbers():
total = 0
for i in range(1, 10001):
total += i
print(total)
#n = int(input())
n = 5
for i in range(n):
sum_numbers()
'''
'''
duration = 20
countdown = 10
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if countdown > 0 and countdown <= 5:
status = "warning ⚠️"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 30
elapsed = 0
status = "sent"
print("Code", status)
for second in range(duration):
elapsed += 1
status = "active"
print("Code", status, "Elapsed:", elapsed)
status = "expired"
print("Code", status)
'''
'''
#function that returns prime numbers in a given range
def prime_numbers(start, end):
prime_list = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
prime_list.append(num)
return prime_list
#print(prime_numbers(5, 18))
primes = prime_numbers(1, 100)
print(primes)
'''
'''
duration = 60
countdown = 30
for second in range(duration):
print("Countdown:", countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown > 0:
status = "active ✅"
else:
status = "expired ❌"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
duration = 60
countdown = 30
for second in range(duration):
if countdown == 0:
status = "expired ❌"
print("Code", status, "Sending new code 📲")
countdown = 30
status = "active ✅"
else:
status = "active ✅"
if countdown > 0:
print("Code", status, countdown)
countdown -= 1
print("Session expired")
'''
'''
duration = 63
countdown = 30
delay = 3
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if status == "expired ❌" and delay > 0:
print("Code", status, "New code incoming📲")
delay -= 1
if countdown > 0:
print("Code", status, countdown)
countdown -= 1
print("Session expired")
'''
'''
duration = 63
countdown = 30
delay = 3
for second in range(duration):
if delay == 0:
countdown = 30
delay = 3
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if status == "expired ❌" and delay > 0:
print("Code", status, "New code incoming📲")
delay -= 1
if countdown > 0:
print("Code", status, countdown)
countdown -= 1
print("Session expired")
'''
'''
def multiply(num1, num2):
print(num1 * num2)
num1 = 3
num2 = 5
multiply(num1, num2)
'''
'''
def square_number (n):
return n ** 2
#result = square_number(int(input()))
#result = square_number(5)
#print(result)
print(square_number(5))
'''
'''
def sigma(n):
total = 0
for number in range(1, n+1):
total += number
return total
print(sigma(5))
'''
'''
def sigma(n):
total = 0
for number in range(1, n+1):
total += number
return total
print(sigma(5))
'''
'''
def sigma_O_1(n):
"""
Calculates the sum of numbers from 1 to n using the mathematical formula.
This results in Constant Time complexity, O(1).
"""
# Formula: n * (n + 1) / 2
# The calculation is one operation, regardless of how large 'n' is.
return n * (n + 1) // 2 # Use // for integer division
# Test the optimized function
print(sigma_O_1(5))
# For n=5: (5 * (5 + 1)) / 2 = (5 * 6) / 2 = 30 / 2 = 15
'''
'''
def sigma_O_1(n):
return n * (n + 1) // 2
print(sigma_O_1(5))
'''
'''
def is_valid(username, password):
if username == "user" and password == "qweasd":
return True
elif username == "admin":
return True
else:
return False
print(is_valid("user", "qweasd"))
'''
'''
def is_valid(username, password):
if username == "user" and password == "qweasd":
return True
elif username == "admin":
return True
else: # <--- This is the technically unnecessary part
return False
print(is_valid("user", "qweasd"))
'''
'''
def is_valid(username, password):
if username == "user" and password == "qweasd":
return True
if username == "admin": # Can be 'if' instead of 'elif' now
return True
# If neither of the conditions above returned True, we reach here.
return False
print(is_valid("user", "qweasd"))
'''
'''
def is_valid(username, password):
# Condition 1: "admin" is valid with any password.
# OR
# Condition 2: "user" is valid ONLY with "qweasd".
if (username == "admin") or (username == "user" and password == "qweasd"):
return True
return False
print(is_valid("user", "qweasd"))
'''
'''
def is_valid(username, password):
return (username == "admin") or \
(username == "user" and password == "qweasd")
print(is_valid("user", "qweasd"))
'''
'''
# 1. Externalize the data/rules into a dictionary
VALID_CREDENTIALS = {
"user": "qweasd", # Specific password required
"admin": None # 'None' or any placeholder can signify 'any password'
}
def is_valid_flexible(username, password):
# 2. Check if the username exists in our rules data
if username not in VALID_CREDENTIALS:
return False # Invalid username
# Get the required password (could be 'qweasd' or 'None' for admin)
required_password = VALID_CREDENTIALS[username]
# 3. Check the password based on the rule
if required_password is None:
# Rule: If required_password is None (like for 'admin'), any password is valid
return True
elif password == required_password:
# Rule: If a specific password is required (like for 'user'), check for an exact match
return True
return False
# --- Test Cases ---
print(is_valid_flexible("admin", "any_pass")) # True
print(is_valid_flexible("user", "qweasd")) # True
print(is_valid_flexible("user", "wrong")) # False
print(is_valid_flexible("guest", "pass")) # False
'''
'''
VALID_CREDENTIALS = {
"user": "qweasd",
"admin": None
}
def is_valid(username, password):
if username not in VALID_CREDENTIALS:
return False
required_password = VALID_CREDENTIALS[username]
if required_password is None:
return True
elif password == required_password:
return True
return False
# --- Test Cases ---
print(is_valid("admin", "any_pass")) # True
print(is_valid("user", "qweasd")) # True
print(is_valid("user", "wrong")) # False
print(is_valid("guest", "pass")) # False
'''
'''
duration = 10
for second in range(duration):
print("Elapsed:", second + 1)
print("Code expired")
'''
'''
duration = 20
print("Code sent")
for second in range(duration):
countdown = duration - second
warning = countdown <= 10
print("Countdown:", countdown, "Warning?", warning)
print("Code expired")
'''
'''
username = "chiefOfStuff"
past_devices = ["iphone-14-001","ipad-air-002","pixel-8-003"]
print("Devices already used:", past_devices)
'''
'''
username = "chiefOfStuff"
past_devices = ["iphone-14-001", "ipad-air-002", "pixel-8-003"]
device = "iphone-14-001"
print("Device used before?", device in past_devices)
'''
'''
username = "chiefOfStuff"
past_devices = ["iphone-14-001", "ipad-air-002", "pixel-8-003"]
device = "iphone-14-001"
if device in past_devices:
print("Device seen before")
'''
'''
username = "chiefOfStuff"
past_devices = ["iphone-14-001", "ipad-air-002", "pixel-8-003"]
device = "surface-pro-683"
if device in past_devices:
print("Device seen before")
else:
print("ℹ️ Login from a new device")
print("Was this you?")
'''
'''
username = "chiefOfStuff"
past_devices = ["iphone-14-001", "ipad-air-002", "pixel-8-003"]
device = "surface-pro-683"
if device not in past_devices:
print("ℹ️ Login from a new device")
print("Was this you?")
else:
print("Device seen before")
'''
'''
duration = 40
countdown = 15
for second in range(duration):
if countdown == 0:
status = "expired ❌"
else:
status = "active ✅"
if countdown > 0 and countdown <= 8:
status = "warning ⚠️"
print("Code", status, countdown)
if countdown > 0:
countdown -= 1
print("Session expired")
'''
'''
username = "EmilyVP"
times = [812,947,1145,1523,1701]
print("Login times:", times)
'''
'''
username = "EmilyVP"
times = [812, 947, 1145, 1523, 1701]
print("First login today at", times[0])
print("Second login at", times[1])
print("Was this you?")
'''
'''
username = "EmilyVP"
times = [812, 947, 1145, 1523, 1701]
print("You logged in", len(times), "times today")
print("Last login:", times[len(times) - 1])
print("Was this you?")
'''
'''
username = "EmilyVP"
times = [812, 947, 1145, 1523, 1701]
print("You logged in", len(times), "times today")
print("First 3 logins:", times[:3])
print("Last 3 logins:", times[-3:])
print("Was this you?")
'''
'''
def show_info(name, role="User", status="Active"):
print(f"{name} - {role} - {status}")
show_info("Alice", "Admin")
'''
'''
def calculate(x, y=2, z=3):
return x + y + z
result = calculate(1)
print(result)
'''
'''
print("Welcome to FizzBuzz!")
def fizzbuzz(number):
if number / 3 == 0:
return "Fizz"
if number / 7 == 0:
return "Buzz"
if number / 7 == 0 and number / 3 == 0:
return "FizzBuzz"
else:
return str(number)
#input_number = int(input())
input_number = 3
print(fizzbuzz(input_number))
'''
'''
def fizzbuzz(number):
# 1. Check for BOTH 3 and 7 FIRST (Most restrictive condition)
if number % 3 == 0 and number % 7 == 0:
return "FizzBuzz"
# 2. Check for 3
elif number % 3 == 0:
return "Fizz"
# 3. Check for 7
elif number % 7 == 0:
return "Buzz"
# 4. If none of the above are true
else:
return str(number)
# Example usage from your original code
input_number = 3
print(fizzbuzz(input_number))
input_number = 7
print(fizzbuzz(input_number))
input_number = 21 # Divisible by both
print(fizzbuzz(input_number))
input_number = 5
print(fizzbuzz(input_number))
'''
'''
def fizzbuzz(number):
if number % 3 == 0 and number % 7 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 7 == 0:
return "Buzz"
else:
return str(number)
input_number = int(input())
print(fizzbuzz(input_number))
'''
'''
username = "CornerOffice"
times = [110, 317, 1012, 1405, 1659]
for time in times:
print("Login at:", time)
'''
'''
username = "CornerOffice"
times = [110, 317, 1012, 1405, 1659]
for time in times:
print("Login at:", time)
if time > 200 and time < 400:
print("ℹ️ Unusual login time:", time)
print("Was this you?")
'''
'''
username = "CornerOffice"
times = [110, 317, 1012, 1405, 1659]
devices = ["samsung-383", "samsung-383", "thinkpad-219", "samsung-383", "chromebook-239"]
for device in devices:
print("Device used:", device)
'''
'''
username = "CornerOffice"
times = [110, 317, 1012, 1405, 1659]
devices = ["samsung-383", "samsung-383", "thinkpad-219", "samsung-383", "chromebook-239", "apple"]
past_devices = ["samsung-383", "thinkpad-219"]
for device in devices:
print("Device used:", device)
if device not in past_devices:
print("ℹ️ Login from new device:", device)
print("Was this you?")
'''
'''
username = "CornerOffice"
times = [110, 317, 1012, 1405, 1659]
devices = ["samsung-383", "samsung-383", "thinkpad-219", "samsung-383", "chromebook-239"]
past_devices = ["samsung-383", "thinkpad-219"]
for device in devices:
print("Device used:", device)
if device not in past_devices:
print("ℹ️ Login from new device:", device)
print("Was this you?")
'''
'''
def complex_calculation(iterations):
for i in range(iterations):
if (i + 1) % 10 == 0:
print(f"Processing... {i+1} of {iterations} complete.")
complex_calculation(100)
'''
'''
print("Welcome to FizzBuzz!")
def fizzbuzz(number):
if number % 3 == 0 and number % 7 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 7 == 0:
return "Buzz"
elif not(number % 3 == 0 or number % 7 == 0) and "3" in str(number):
return "Almost Fizz"
else:
return str(number)
#input_number = int(input())
input_number = 21
#print(fizzbuzz(input_number))
for i in range(1, input_number + 1):
print(fizzbuzz(i))
'''
'''
for i in range(1, 11):
if i == 7:
continue
print(i)
'''
'''
for i in range(1, 11):
if i != 7:
print(i)
else:
continue
'''
'''
def plant_decision(plant_id):
no_prefix_string = format(plant_id, 'b')
if no_prefix_string[-1] == '1':
return 'plant'
else:
return 'skip'
#plant_id = int(input())
plant_id = 11
print(plant_decision(plant_id))
'''
'''
def plant_decision(plant_id):
binary = bin(plant_id)[2:]
if binary[-1] == '1':
return 'plant'
else:
return 'skip'
'''
'''
my_list = [9, 3.14, "types", False, 1]
length = len(my_list)
print(length)
'''
'''
username = "SynergizerBunny"
past_devices = ["iphone-16-021", "ipad-pro-202"]
print("You have logged in from", len(past_devices), "different devices")
print("List of past devices:", past_devices)
'''
'''
username = "SynergizerBunny"
past_devices = ["iphone-16-021", "ipad-pro-202"]
device = "macbook-pro-299"
past_devices.append(device)
print("ℹ️ Login from new device:", device)
print("Was this you?")
print("You have logged in from", len(past_devices), "different devices")
print("Past devices:", past_devices)
'''
'''
username = "SynergizerBunny"
past_devices = ["iphone-16-021", "ipad-pro-202", "macbook-pro-299"]
devices = ["iphone-16-021", "ipad-pro-202", "macbook-pro-299", "ipad-pro-202", "ipad-pro-202", "macbook-pro-299", "lenovo-yoga-208", "ipad-pro-202", "ipad-pro-202"]
for device in devices:
print("Login from:", device)
'''
'''
username = "SynergizerBunny"
past_devices = ["iphone-16-021", "ipad-pro-202", "macbook-pro-299"]
devices = ["iphone-16-021", "ipad-pro-202", "macbook-pro-299", "ipad-pro-202", "ipad-pro-202", "macbook-pro-299", "lenovo-yoga-208", "ipad-pro-202", "ipad-pro-202"]
for device in devices:
print("Login from:", device)
if device not in past_devices:
past_devices.append(device)
print("ℹ️ Login from new device:", device)
print("Was this you?")
print("You have logged in from", len(past_devices), "different devices")
'''
'''
num1 = 3
num2 = 5
product = 0
product = num1 * num2
print("product =", product) # Don't change this line
'''
'''
username = "VeePeeWee"
times = [362, 454, 728, 948, 1017, 1147, 1201, 1225, 1323, 1826 ]
devices = ["ipad-air-002", "pixel-8-003", "iphone-14-001", "iphone-14-001", "pixel-8-003", "surface-pro-007", "ipad-air-002", "iphone-14-001", "ipad-air-002", "pixel-8-003"]
for i in range(len(times)):
#print("Login", i)
#print("Login at", times[i])
print("Login at", times[i], "with", devices[i])
'''
'''
username = "VeePeeWee"
times = [362, 454, 728, 948, 1017, 1147, 1201, 1225, 1323, 1826 ]
devices = ["ipad-air-002", "pixel-8-003", "iphone-14-001", "iphone-14-001", "pixel-8-003", "surface-pro-007", "ipad-air-002", "iphone-14-001", "ipad-air-002", "pixel-8-003"]
for i in range(len(times)):
time = times[i]
device = devices[i]
print("Login at", time, "with", device)
'''
'''
username = "VeePeeWee"
times = [362, 454, 728, 948, 1017, 1147, 1201, 1225, 1323, 1826 ]
devices = ["ipad-air-002", "pixel-8-003", "iphone-14-001", "iphone-14-001", "pixel-8-003", "surface-pro-007", "ipad-air-002", "iphone-14-001", "ipad-air-002", "pixel-8-003"]
past_devices = [] # empty list
for i in range(len(times)):
time = times[i]
device = devices[i]
if device not in past_devices:
print("ℹ️ Login from new device", device, "at", time)
print("Was this you?")
past_devices.append(device)
num_past_devices = len(past_devices)
print("You have used", num_past_devices, "different devices")
'''
'''
lst = [5, 9, 2, 10, 2]
def values(lst):
for i in range(len(lst)):
print(lst[i])
values(lst)
'''
'''
#number = int(input())
#number = 5
if number % 2 == 0:
print('Even')
else:
print('Odd')
'''
'''
def duplicate_until_x(string):
new_string = ''
for i in string:
if i != 'x':
new_string += i + i
if i == 'x':
new_string += 'x'
break
print(new_string)
index_x = string.find('x')
print(f"'x' is at index: {index_x}")
new_string += string[4:]
print(new_string)
string = 'abcxdef'
#string = 'axdef' #failed because code made for only one solution
duplicate_until_x(string)
'''
'''
def duplicate_until_x(string):
# 1. Check if 'x' exists and find its first index
first_x_index = string.find('x')
# Case 1: 'x' is not present (find returns -1)
if first_x_index == -1:
return string # Return the original string unchanged
# Case 2: 'x' is present
# Slice the string from the start (index 0) UP TO the first 'x' (index is exclusive)
part_to_duplicate = string[:first_x_index]
# Slice the string FROM the first 'x' to the end of the string (index is inclusive)
part_to_append = string[first_x_index:]
# Build the duplicated part using a simple join/list comprehension
duplicated_part = ''.join(char * 2 for char in part_to_duplicate)
# Combine the duplicated part and the rest of the original string
return duplicated_part + part_to_append
# --- Test Cases ---
# Example from the challenge:
result_1 = duplicate_until_x('abcxdef')
print(f"abcxdef -> {result_1}")
# 'x' at the beginning:
result_2 = duplicate_until_x('xstart')
print(f"xstart -> {result_2}")
# 'x' missing (should return original):
result_3 = duplicate_until_x('no_x_here')
print(f"no_x_here -> {result_3}")
# 'x' at the end:
result_4 = duplicate_until_x('endx')
print(f"endx -> {result_4}")
'''
'''
def duplicate_until_x(string):
first_x_index = string.find('x')
if first_x_index == -1:
return string
part_to_duplicate = string[:first_x_index]
part_to_append = string[first_x_index:]
duplicated_part = ''.join(char * 2 for char in part_to_duplicate)
return duplicated_part + part_to_append
result_1 = duplicate_until_x('abcxdef')
print(f"abcxdef -> {result_1}")
result_2 = duplicate_until_x('xstart')
print(f"xstart -> {result_2}")
result_3 = duplicate_until_x('no_x_here')
print(f"no_x_here -> {result_3}")
result_4 = duplicate_until_x('endx')
print(f"endx -> {result_4}")
result_5 = duplicate_until_x('abcxdef')
print(f"abcxdef -> {result_5}")
'''
'''
username = "rubiksCubicle"
times = [832, 915, 915, 1041, 1139, 1228, 159, 159, 242, 310]
if times[2] == times[1]:
print("ℹ️ Two logins at", times[2])
print("Were these both you?")
'''
'''
username = "rubiksCubicle"
times = [832, 915, 915, 1041, 1139, 1228, 159, 159, 242, 310]
i = 4
if times[i] == times[i - 1]:
print("ℹ️ Two logins at", times[i - 1])
print("Were these both you?")
else:
print("Login", i, "OK")
print(times[i])
print(times[i - 1])
'''
'''
username = "rubiksCubicle"
times = [832, 915, 915, 1041, 1139, 1228, 159, 159, 242, 310]
for i in range(len(times)):
if times[i - 1] == times[i]:
print("ℹ️ Two logins at", times[i - 1])
print("Were these both you?")
else:
print("Login", i, "OK")
'''
'''
username = "rubiksCubicle"
times = [832, 915, 915, 1041, 1139, 1228, 159, 159, 242, 310]
for i in range(1, len(times)):
if times[i] == times[i - 1]:
print("ℹ️ Two logins at", times[i])
print("Were these both you?")
else:
print("Login", i, "OK")
print(range(1, len(times)))
'''
'''
def change_element(lst, index, new_element):
lst[index] = new_element
return lst
print(change_element(["a", "b", "c"], 1, "d"))
'''
'''
def create_packing_list(traveler_name, days_per_location):
total_days = sum(days_per_location)
packing_list_string = f'Packing list for {traveler_name}:\n- Clothes for {total_days} days\n- Toiletries\n'
if total_days > 7:
packing_list_string += '- Extra shoes\n'
if total_days > 10:
packing_list_string += '- Laundry soap\n'
packing_list_string.rstrip("\n")
return packing_list_string
print(create_packing_list('Alice', [1]))
'''
'''
def create_packing_list(traveler_name, days_per_location):
total_days = sum(days_per_location)
# 1. Define the list of all lines (including the header)
# We DO NOT add the newline character here.
packing_lines = [
f"Packing list for {traveler_name}:",
f"- Clothes for {total_days} days",
"- Toiletries"
]
# 2. Add conditional items
if total_days > 7:
packing_lines.append("- Extra shoes")
if total_days > 10:
packing_lines.append("- Laundry soap")
# 3. Join the list items using a newline character (\n)
# This guarantees no unnecessary trailing newlines or hyphens.
return "\n".join(packing_lines)
# Test with your example
print(create_packing_list('Alice', [1]))
'''
'''
def create_packing_list(traveler_name, days_per_location):
total_days = sum(days_per_location)
packing_lines = [
f"Packing list for {traveler_name}:",
f"- Clothes for {total_days} days",
"- Toiletries"
]
if total_days > 7:
packing_lines.append("- Extra shoes")
if total_days > 10:
packing_lines.append("- Laundry soap")
return "\n".join(packing_lines)
print(create_packing_list('Alice', [1]))
'''
'''
def create_packing_list(traveler_name, days_per_location):
total_days = sum(days_per_location)
packing_list = f"Packing list for {traveler_name}:\n"
packing_list += f"- Clothes for {total_days} days\n"
packing_list += "- Toiletries\n"
if total_days > 7:
packing_list += "- Extra shoes\n"
if total_days > 10:
packing_list += "- Laundry soap\n"
return packing_list.rstrip("\n")
'''
'''
username = "ChiefInnovator"
past_devices = ["surface-laptop-445", "surface-pro-212"]
devices = ["surface-laptop-445", "dell-xps-783", "surface-pro-212", "surface-laptop-445", "dell-xps-783"]
for device in devices:
print("Login from:", device)
if device not in past_devices:
past_devices.append(device)
print("ℹ️ Login from new device:", device)
print("Was this you?")
print("You have logged in from", len(past_devices), "different devices")
'''
'''
username = "PaperJamMaster"
times = [845, 912, 1056, 1143, 1425, 1608]
devices = ["macbook-pro-042", "surface-go-018", "macbook-pro-042", "ipad-mini-007", "surface-go-018", "macbook-pro-042"]
past_devices = [] # empty list
for i in range(len(times)):
time = times[i]
device = devices[i]
if device not in past_devices:
print("ℹ️ Login from new device", device, "at", time)
print("Was this you?")
past_devices.append(device)
'''
'''
username = "MeetingDoubleBooker"
times = [1015, 1015, 1247, 1247, 1438, 1552]
for i in range(1, len(times)):
if times[i] == times[i - 1]:
print("ℹ️ Two logins at", times[i])
print("Were these both you?")
else:
print("Login", i, "OK")
'''
'''
def merge(lst1, lst2):
#merged_list = []
#for item in lst1:
# merged_list.append(item)
#for item in lst2:
# merged_list.append(item)
merged_list = lst1 + lst2
#merged_list.sort()
#return merged_list
return sorted(merged_list)
#print(merge([2], [1]))
print(merge([100, 99, 88, 77], [1, 9, 2, 8, 3, 7, 5]))
'''
'''
def merge(lst1, lst2):
merged_list = lst1 + lst2
return sorted(merged_list)
print(merge([100, 99, 88, 77], [1, 9, 2, 8, 3, 7, 5]))
'''
'''
def merge(lst1, lst2):
merged_list = []
for item in lst1:
merged_list.append(item)
for item in lst2:
merged_list.append(item)
#merged_list = lst1 + lst2
merged_list.sort()
return merged_list
#return sorted(merged_list)
'''
'''
def prod(lst):
running_product = 1
for i in lst:
running_product *= i
return running_product
print(prod([1, 2, 3]))
'''
'''
def reverse(lst):
n = len(lst)
reversed_list = []
# Correcting the function name!
for i in range(START, STOP, STEP): # <-- You need to fill in these three values
# Access the element in the original list (lst) using the index calculated in the loop.
# This index will take you from the back of 'lst' to the front.
element_to_append = lst[i]
reversed_list.append(element_to_append)
return reversed_list
'''
'''
def reverse(lst):
n = len(lst)
reversed_list = []
for i in range(len(lst) - 1, -1, -1):
element_to_append = lst[i]
reversed_list.append(element_to_append)
return reversed_list
#print(reverse([1, 2, 3]))
print(reverse([3, 5, 7, 1, -4, 98]))
'''
'''
username = "SynergySteve"
times = [929, 1047, 1215, 1503]
print("First:", times[0])
print("Last:", times[-0])
print("Last:", len(times) - 2)
print("Last:", times[-2])
'''
'''
username = "PaperJamMaster"
times = [845, 912, 1056, 1143, 1425, 1608]
devices = ["macbook-pro-042", "surface-go-018", "macbook-pro-042", "ipad-mini-007", "surface-go-018", "macbook-pro-042"]
past_devices = [] # empty list
for i in range(len(times)):
time = times[i]
device = devices[i]
if device not in past_devices:
print("ℹ️ Login from new device", device, "at", time)
print("Was this you?")
past_devices.append(device)
'''
'''
my_data = [90, 85, 95, 80, 75]
print(my_data[len(my_data) - 3])
'''
'''
person = ("John", 25, "New York")
print(person[1])
'''
'''
#lst = input().split(",")
lst = ['pen', 'elephant', 'dolphin', 'giraffe', 'kangaroo']
def five_long (lst):
more_than_five = []
for i in lst:
if len(i) > 5:
more_than_five.append(i)
return more_than_five
print(five_long(lst))
'''
'''
username = "chiefOfStuff"
times = [212, 401, 554, 728, 728, 1201, 1225, 1826]
for i in range(3):
print("Logged in at", times[i])
'''
'''
username = "chiefOfStuff"
times = [212, 401, 554, 728, 728, 1201, 1225, 1826]
i = 0
while i < 5:
print("Logged in at", times[i])
i += 1
'''
'''
username = "chiefOfStuff"
times = [212, 401, 554, 728, 728, 1201, 1225, 1826]
i = 0
while i < len(times):
print("Logged in at", times[i])
i += 1
'''
'''
username = "chiefOfStuff"
times = [212, 401, 554, 728, 728, 1201, 1225, 1826]
i = 0
while times[i] < 500:
print("⚠️ Unusual login at", times[i])
i += 1
'''
'''
username = "chiefOfStuff"
times = [212, 401, 554, 728, 728, 1201, 1225, 1826]
i = 1
while times[i] != times[i - 1]:
print("Logged in at", times[i])
i += 1
print("⚠️ Two logins at", times[i])
'''
'''
def find_special_indices(input_string):
"""
Processes a comma-separated string of numbers and returns the indices
of numbers that are either below 50 OR divisible by 5.
"""
# 1. Handle the input conversion (assuming the input is a string like "80,4,99,36,34")
# This converts the string into a list of integers: [80, 4, 99, 36, 34]
try:
data_list = [int(num.strip()) for num in input_string.split(',')]
except ValueError:
return "Error: Please input a comma-separated list of valid numbers."
# 2. Create an empty list to store the resulting indices
result_indices = []
# 3. Use enumerate() to get both the index (i) and the number (num)
for i, num in enumerate(data_list):
# 4. Check the combined condition: (below 50) OR (divisible by 5)
# The modulo operator (%) gives the remainder. A remainder of 0 means perfect division.
if num < 50 or num % 5 == 0:
# 5. If the condition is met, add the index (i) to the results list
result_indices.append(i)
# 6. Return the final list of indices
return result_indices
# --- Example of how to use it ---
# The input line would typically look like this:
# lst_input = input()
# For the example: "80,4,99,36,34"
test_input = "80,4,99,36,34"
output = find_special_indices(test_input)
# Final printed output: [0, 1, 3, 4]
print(output)
'''
'''
def find_special_indices(input_string):
try:
data_list = [int(num.strip()) for num in input_string.split(',')]
except ValueError:
return
result_indices = []
for i, num in enumerate(data_list):
if num < 50 or num % 5 == 0:
result_indices.append(i)
return result_indices
test_input = "80,4,99,36,34"
output = find_special_indices(test_input)
print(output)
'''
'''
fruits = ["apple", "banana", "orange"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
'''
'''
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
'''
'''
def find_special_indices(input_string):
#lst = list(map(int, input().split(",")))
lst = list(map(int, input_string.split(",")))
new_lst = []
for index, num in enumerate(lst):
if num < 50 or num % 5 == 0:
new_lst.append(index)
return new_lst
test_input = "80,4,99,36,34"
output = find_special_indices(test_input)
print(output)
'''
'''
username = "chiefOfStuff"
times = [212, 212, 401, 554, 728, 728, 1201, 1225, 1826]
i = 1
while times[i] != times[i - 1]:
print("Logged in at", times[i])
i += 1
print("⚠️ Two logins at", times[i])
'''
text = "Peter Piper picked a peck of pickled peppers"
#text = "Happy people play ping pong"
'''
count = 0
for words in text:
lowercase = words.lower()
if lowercase == 'p':
count += 1
print(count)
text = input()
count = 0
for char in text:
if char.lower() == 'p':
count += 1
print(count)
'''
'''
username = "vpOfVibes"
past_devices = ["iphone-14-001", "ipad-air-002"]
devices = ["iphone-14-001"]
i = 0
new = 0
while new < 3:
device = devices[i]
if device not in past_devices:
new += 1
past_devices.append(device)
i += 1
print("New devices so far:", new)
print("⚠️ Logged in from 3 new devices")
'''
'''
username = "vpOfVibes"
past_devices = ["iphone-14-001", "ipad-air-002"]
devices = ["iphone-14-001"]
i = 0
new = 0
while new < 3:
device = devices[i]
if device not in past_devices:
new += 1
past_devices.append(device)
i += 1
print("New devices so far:", new)
print("⚠️ Logged in from 3 new devices")
'''
'''
def create_pattern(numbers, repeats):
combined_list = numbers + numbers
repeated_list = combined_list * repeats
return repeated_list
print(create_pattern([1, 2, 3], 2))
'''
'''
lst1 = [1,2,3,4,5]
lst2 = [2,4,6]
result = []
for number in lst1:
if number not in lst2:
result.append(number)
print(result)
'''
'''
lst1 = input().split(",")
lst2 = input().split(",")
result = []
for number in lst1:
if number not in lst2:
result.append(number)
print(result)
'''
'''
# This part is already provided
print("Welcome to the Daily Expense Tracker!\n")
print("Menu:")
print("1. Add a new expense")
print("2. View all expenses")
print("3. Calculate total and average expense")
print("4. Clear all expenses")
print("5. Exit")
expenses = []
# Your code starts here
while True:
# Get the user's choice
choice = input()
# Check if the choice is to exit
if choice == "5":
# Print the goodbye message
print("Exiting the Daily Expense Tracker. Goodbye!")
# Then, break out of the loop
break
'''
'''
print("Welcome to the Daily Expense Tracker!")
# Display menu once
print("\nMenu:")
print("1. Add a new expense")
print("2. View all expenses")
print("3. Calculate total and average expense")
print("4. Clear all expenses")
print("5. Exit")
# Initialize an empty list to store expenses
import statistics
expenses = []
while True:
# Get user choice
choice = input()
if choice == "1":
# Add a new expense
amount = float(input())
expenses.append(amount)
print("Expense added successfully!")
elif choice == "2":
# View all expenses
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
print("Your expenses:")
for i in range(len(expenses)):
print(f"{i + 1}. {expenses[i]}")
elif choice =="3":
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
print("Total expense:", sum(expenses))
#print("Average expense:", statistics.mean(expenses))
print("Average expense:", sum(expenses)/len(expenses))
elif choice == "5":
# Exit the program
print("Exiting the Daily Expense Tracker. Goodbye!")
break
'''
'''
print("Welcome to the Daily Expense Tracker!")
# Display menu once
print("\nMenu:")
print("1. Add a new expense")
print("2. View all expenses")
print("3. Calculate total and average expense")
print("4. Clear all expenses")
print("5. Exit")
# Initialize an empty list to store expenses
import statistics
expenses = []
while True:
# Get user choice
choice = input()
if choice == "1":
# Add a new expense
amount = float(input())
expenses.append(amount)
print("Expense added successfully!")
elif choice == "2":
# View all expenses
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
print("Your expenses:")
for i in range(len(expenses)):
print(f"{i + 1}. {expenses[i]}")
elif choice == "3":
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
print("Total expense:", sum(expenses))
#print("Average expense:", statistics.mean(expenses))
print("Average expense:", sum(expenses)/len(expenses))
elif choice == "4":
expenses = []
print("All expenses cleared.")
elif choice == "5":
# Exit the program
print("Exiting the Daily Expense Tracker. Goodbye!")
break
'''
'''
username = "entrepreNerd"
past_devices = ["iphone-16-001"]
devices = ["iphone-16-001", "iphone-16-001", "iphone-16-001", "ipad-air-007", "iphone-16-001"]
i = 1
changes = 0
while i < len(devices) and changes < 5:
if devices[i] != devices[i - 1]:
changes += 1
i += 1
print("Device changes so far:", changes)
if changes == 5:
print("⚠️ Changed devices 5 times")
else:
print("✅ All good")
'''
'''
def find_occurrences(text, pattern):
# Write your code here
pass
# Read input
text = input()
pattern = input()
# Call your function and print the result
result = find_occurrences(text, pattern)
print(result)
'''
'''
def find_occurrences(text, pattern):
count = 0
positions = []
for i in range(len(text)):
if text[i : i + len(pattern)] == pattern:
count += 1
positions.append(i)
return (count > 0, count, positions)
# Read input
text = input()
pattern = input()
# Call your function and print the result
result = find_occurrences(text, pattern)
print(result)
'''
'''
prices = input().split(",")
for i in range(len(prices)):
prices[i] = int(prices[i])
items = input().split(",")
budget_per_item = int(input())
affordable_items = []
cant_afford = 0
total_needed = 0
# Write your code below
for i in range(len(prices)):
# Check if the current price is within budget
if prices[i] <= budget_per_item:
# Add the item name to our list
affordable_items.append(items[i])
# Add the price to our total running cost
total_needed += prices[i]
else:
# It's too expensive, increment the "can't afford" counter
cant_afford += 1
print("Can buy:", affordable_items)
print("Total budget needed:", total_needed)
print("Can't afford:", cant_afford)
'''
'''
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
numbers = [1, 2, 3]
print(4 not in numbers) # True
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # True
print("Alice" in my_dict) # False
'''
'''
destination = "Hawaii"
price = 1999
nights = 4
family_preference = False
package_family_friendly = False
if destination == 'Hawaii' or destination == 'Bahamas':
if price < 2000 and nights >= 4:
if family_preference == package_family_friendly:
print("Package is suitable")
else:
print("PackageA is not suitable")
else:
print("PackagB is not suitable")
else:
print("PackageC is not suitable")
'''
'''
def manage_set(set1, element_to_add, element_to_remove):
set1.add(element_to_add)
set1.remove(element_to_remove)
if 5 in set1:
print("5 is in the set")
else:
print("5 is not in the set")
set1 = {1, 2, 3, 4}
element_to_add = 5
element_to_remove = 2
manage_set(set1, element_to_add, element_to_remove)
'''
'''
def remove_duplicates(numbers):
#new_set = set(numbers)
#new_list = list(new_set)
#print(new_list)
return list(set(numbers))
'''
'''
def manage_list(list1, element_to_append, index_to_remove):
list1.append(element_to_append)
if 0 <= index_to_remove < len(list1):
list1.pop(index_to_remove)
if len(list1) > 3:
print('"The list" has more than 3 elements')
else:
print("The list has 3 or fewer elements")
manage_list([1,2,3],4,5)
'''
'''
def manage_list(list1, element_to_append, index_to_remove):
list1.append(element_to_append)
if 0 <= index_to_remove < len(list1):
list1.pop(index_to_remove)
if len(list1) > 3:
print("The list has more than 3 elements")
else:
print("The list has 3 or fewer elements")
'''
'''
messages = [
"Is there any further action required on this invoice?",
"Action required: please confirm payment details.",
"Special offer: boost your energy. Click here for details",
"Please share the updated draft before the end of the day.",
"Urgent action required! Hurry, don't miss this free offer.",
"The agenda draft looks fine, just add one more topic."
]
senders = [
"chiefOfStuff",
"entrepreNerd",
"rubiksCubicle",
"middlingManager",
"MagnumKPI",
"ExecEnvy"
]
recipients = [
"middlingManager",
"MagnumKPI",
"ExecEnvy",
"rubiksCubicle",
"entrepreNerd",
"chiefOfStuff"
]
folders = [
"✉️ Inbox",
"✉️ Inbox",
"⚠️ Spam",
"✉️ Inbox",
"⚠️ Spam",
"✉️ Inbox"
]
timestamps = [
430929,
449891,
451220,
456188,
483838,
493564
]
# build message_log ...
message_log = []
for i in range(len(messages)):
message_dict = {}
message_dict["text"] = messages[i].lower()
message_dict["sender"] = senders[i]
message_dict["recipient"] = recipients[i]
message_dict["folder"] = folders[i]
message_dict["timestamp"] = timestamps[i]
message_log.append(message_dict)
for messag in message_log: #line 52
sender = messag ["sender"]
recipient = messag ["recipient"]
folder = messag ["folder"]
#Let’s see if any spam messages are still slipping through the cracks.
#Print the sender and timestamp of all messages that contain “action required”
#but didn't get flagged as spam.
timestamp = messag["timestamp"]
text = messag["text"]
if folder == "⚠️ Spam":
print(f"{sender} sent spam to {recipient}")
if "action required" in text and folder != "⚠️ Spam":
print(f"From {sender} at {timestamp}:")
print(text)
#Let's explore a larger data set to investigate spam activity.
#Print the number of messages in the message_log list,
#and also the last message.
num_messages = len(message_log)
print(f"Found {num_messages} messages")
print("Last message:")
print(message_log[-1])
'''
'''
def check_inventory(inventory, item):
if item in inventory:
print(f"{item} is in stock. Quantity: {inventory[item]}")
else:
print(f"{item} is not in stock.")
check_inventory({"apple":10,"banana":5,"orange":7}, "banana")
'''
'''
region1 = eval(input())
region2 = eval(input())
region3 = eval(input())
shared_treasures = region1 & region2 & region3
unique_treasures_region1 = region1 - region2 - region3
all_treasures = region1 | region2 | region3
unique_treasures_region2 = region2 - region1 - region3
unique_treasures_region3 = region3 - region1 - region2
#exclusive_treasures = region1 ^ region2 ^ region3
exclusive_treasures = unique_treasures_region1 | unique_treasures_region2 | unique_treasures_region3
# Print the results
print("Shared treasures:", sorted(list(shared_treasures)))
print("Unique treasures in region1:", sorted(list(unique_treasures_region1)))
print("All treasures:", sorted(list(all_treasures)))
print("Exclusive treasures:", sorted(list(exclusive_treasures)))
'''
'''
def iterate_and_filter_set(input_set):
new_set = set()
for item in input_set:
if item <= 10:
new_set.add(item)
return new_set
input_set = {5, 12, 7, 15, 3, 10}
print(iterate_and_filter_set(input_set))
'''
'''
match1 = {"Alice", "Bob", "Charlie", "Diana"}
match2 = {"Charlie", "Diana", "Eve", "Frank"}
match3 = {"Alice", "Diana", "Frank", "George"}
# 1. Find players who participated in all three matches
intersection_set = match1 & match2 & match3
# 2. Find players who participated in exactly two matches
pair_1_2 = match1 & match2
pair_1_3 = match1 & match3
pair_2_3 = match2 & match3
union_set = pair_1_2 | pair_1_3 | pair_2_3
two_matches = union_set - intersection_set
# 3. Find players who participated in only one match
only_in_match_1 = match1 - match2 - match3
only_in_match_2 = match2 - match1 - match3
only_in_match_3 = match3 - match1 - match2
only_in_result = only_in_match_1 | only_in_match_2 | only_in_match_3
# 4. Count total unique players
all = match1 | match2 | match3
# 5. Find players in Match 1 only
# Print results in the specified format
#print(intersection_set)
print(f"Players in all matches: {sorted(list(intersection_set))}")
#print(pair_1_2)
#print(pair_1_3)
#print(pair_2_3)
#print(union_set)
#print(two_matches)
#print(sorted(list(two_matches)))
print(f"Players in exactly two matches: {sorted(list(two_matches))}")
#print(only_in_match_1)
#print(only_in_match_2)
#print(only_in_match_3)
#print(sorted(list(only_in_result)))
print(f"Players in only one match: {sorted(list(only_in_result))}")
#print(len(all))
print(f"Total unique players: {len(all)}")
print(f"Players in Match 1 only: {sorted(list(only_in_match_1))}")
#print this
#Players in all matches: ['Diana']
#Players in exactly two matches: ['Alice', 'Charlie', 'Frank']
#Players in only one match: ['Bob', 'Eve', 'George']
#Total unique players: 7
#Players in Match 1 only: ['Bob']
'''
'''
# Basic For Loop
def filter_and_square_set(input_set):
squared_set = set()
for n in input_set:
if n % 2 != 0:
squared_set.add(n * n)
return squared_set
print(filter_and_square_set({1, 2, 3, 4, 5}))
# List Comprehension (Recommended)
#Set Comprehension:
#This is the most "Pythonic" and concise method.
#It uses curly braces {} to define a new set and iterates through an
#existing iterable while applying the squaring operation.
def filter_and_square_set(input_set):
odd_numbers = {n for n in input_set if n % 2 != 0}
squared_set = {n**2 for n in odd_numbers}
return squared_set
print(filter_and_square_set({1, 2, 3, 4, 5}))
#Using the filter() Function
#The set() and map() Functions:
#You can use the map() function to apply a square operation (often via a lambda)
#to every item in an iterable, then wrap the result in set() to convert it from
#a map object into a set.
def filter_and_square_set(input_set):
odd_numbers = set(filter(lambda n: n % 2 != 0, input_set))
squared_set = set(map(lambda n: n**2, odd_numbers))
return squared_set
print(filter_and_square_set({1, 2, 3, 4, 5}))
'''
'''
student_records = {}
def add_student (name, age, courses):
if name not in student_records:
#student_records[name]["age"] = age
#student_records[name]["grades"] = set()
#student_records[name]["courses"] = set(courses)
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
else:
print(f"Student '{name}' already exists.")
#add_student("Alice", 20, ["Math", "Physics"])
#add_student("Bob", 22, ["Biology", "Chemistry"])
#print(student_records)
def add_grade(name, grade):
if name in student_records:
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
else:
print(f"Student '{name}' not found.")
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Charlie", 80) # Non-existent student
print(student_records)
'''
'''
student_records = {}
def add_student(name, age, courses):
if name not in student_records:
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
else:
print(f"Student '{name}' already exists.")
def add_grade(name, grade):
if name in student_records:
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
else:
print(f"Student '{name}' not found.")
def is_enrolled(name,course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
else:
return course in student_records[name]["courses"]
#if course in student_records[name]["courses"]:
#return True
#else:
#return False
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Charlie", 80) # Non-existent student
print(is_enrolled("Alice", "Math")) # Should return True
print(is_enrolled("Alice", "Biology")) # Should return False
print(is_enrolled("Bob", "Biology")) # Should return True
print(is_enrolled("Charlie", "Math")) # Non-existent student, should print message and return False
'''
'''
student_records = {}
def add_student(name, age, courses):
if name not in student_records:
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
else:
print(f"Student '{name}' already exists.")
def add_grade(name, grade):
if name in student_records:
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
else:
print(f"Student '{name}' not found.")
def is_enrolled(name,course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
else:
if course in student_records[name]["courses"]:
return True
else:
return False
def calculate_average_grade(name):
if name in student_records:
if student_records[name]["grades"] == 0:
return 0
else:
all_grades = student_records[name]["grades"]
avg_grade = sum(all_grades) / len(all_grades)
return float(avg_grade)
else:
print(f"Student '{name}' not found.")
return None
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
print(calculate_average_grade("Alice")) # Should return 87.5
print(calculate_average_grade("Bob")) # Should return 75.0
print(calculate_average_grade("Charlie")) # Non-existent student, should print message and return None
print(calculate_average_grade("Alice")) # Should return 87.5 again
'''
'''
birth_year = int(input('what year were you born?'))
age = 2026 - birth_year
print(f"Your age is {age}")
'''
'''
student_records = {}
def add_student(name, age, courses):
if name not in student_records:
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
else:
print(f"Student '{name}' already exists.")
def add_grade(name, grade):
if name in student_records:
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
else:
print(f"Student '{name}' not found.")
def is_enrolled(name,course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
else:
if course in student_records[name]["courses"]:
return True
else:
return False
def calculate_average_grade(name):
if name not in student_records:
print(f"Student '{name}' not found.")
return None
grades = student_records[name]["grades"]
if not grades:
return 0
return sum(grades) / len(grades)
#def list_students_by_course(course):
#students_enrolled_in_course = []
#for name, info in student_records.items():
#if course in student_records[name]["courses"]:
#students_enrolled_in_course.append(name)
#return students_enrolled_in_course
def list_students_by_course(course):
students_enrolled_in_course = []
for name,info in student_records.items():
if is_enrolled(name,course):
students_enrolled_in_course.append(name)
return students_enrolled_in_course
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Math", "Biology"])
add_student("Diana", 23, ["Chemistry", "Physics"])
print(list_students_by_course("Math")) # Should return ["Alice", "Bob"]
print(list_students_by_course("Physics")) # Should return ["Alice", "Diana"]
print(list_students_by_course("Biology")) # Should return ["Bob"]
print(list_students_by_course("History")) # Should return an empty list
'''
'''
student_records = {}
def add_student(name, age, courses):
if name not in student_records:
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
else:
print(f"Student '{name}' already exists.")
def add_grade(name, grade):
if name in student_records:
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
else:
print(f"Student '{name}' not found.")
def is_enrolled(name,course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
else:
if course in student_records[name]["courses"]:
return True
else:
return False
def calculate_average_grade(name):
if name not in student_records:
print(f"Student '{name}' not found.")
return 0
grades = student_records[name]["grades"]
if not grades:
return 0
return sum(grades) / len(grades)
#def list_students_by_course(course):
#students_enrolled_in_course = []
#for name, info in student_records.items():
#if course in student_records[name]["courses"]:
#students_enrolled_in_course.append(name)
#return students_enrolled_in_course
def list_students_by_course(course):
students_enrolled_in_course = []
for name,info in student_records.items():
if is_enrolled(name,course):
students_enrolled_in_course.append(name)
return students_enrolled_in_course
def filter_top_students(threshold):
top_students = []
for name, details in student_records.items():
if calculate_average_grade(name) > threshold:
top_students.append(name)
return top_students
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Math", "Biology"])
add_student("Diana", 23, ["Chemistry", "Physics"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Diana", 95)
print(filter_top_students(80)) # Should return ["Alice", "Diana"]
print(filter_top_students(90)) # Should return ["Diana"]
print(filter_top_students(100)) # Should return an empty list
'''
'''
library_catalog = {}
def add_book(title, author, year, genres):
if title in library_catalog:
print(f"Book '{title}' is already in the system.")
else:
library_catalog[title] = {"author": author, "year": year, "genres": set(genres), "available": True}
print(f"Book '{title}' added to the library.")
def find_books_by_genre(target_genre):
books_with_genres = []
for books, about in library_catalog.items():
if target_genre in about["genres"]:
books_with_genres.append(books)
return books_with_genres
add_book("The Hobbit", "J.R.R. Tolkien", 1937, {"Fantasy", "Adventure"})
add_book("1984", "George Orwell", 1949, {"Dystopian", "Sci-Fi"})
add_book("The Great Gatsby", "F. Scott Fitzgerald", 1925, {"Classic", "Drama"})
print(find_books_by_genre("Fantasy")) # Should return ["The Hobbit"]
print(find_books_by_genre("Sci-Fi")) # Should return ["1984"]
print(find_books_by_genre("Mystery")) # Should return []
'''
'''
sales = [100, 200, 150, 300]
starting_cash = 50
total = sum(sales, starting_cash)
print(total)
'''
'''
def calculate_average_score(scores):
if scores == []:
return 0
else:
total = sum(scores)
number_of_scores = len(scores)
avg = total / number_of_scores
return avg
scores = [80,82,78,79,77,81]
print(calculate_average_score(scores))
'''
'''
username = 'jayjay'
password = 'secret'
#hidden_password = '*' * len(password)
print(f"Hey {username}! your password {'*' * len(password)} is {len(password)} characters long!")
'''
'''
numbers = [42, 17, 23, 56, 9, 34]
words = ["kiwi", "apple", "banana", "cherry", "date"]
print(f"Smallest number: {min(numbers)}")
print(f"Largest number: {max(numbers)}")
print(f"Smallest word: {min(words)}")
print(f"Largest word: {max(words)}")
'''
'''
temperatures = [72, 68, 75, 80, 65, 70, 78]
humidity = [60, 55, 65, 70, 50, 58, 62]
print(f"Highest temperature: {max(temperatures)}°F")
print(f"Lowest temperature: {min(temperatures)}°F")
print(f"Highest humidity: {max(humidity)}%")
print(f"Lowest humidity: {min(humidity)}%")
'''
'''
def dictionary_sorter(data_dict):
new_tuple = data_dict.items()
sorted_tuple = sorted(new_tuple, key=lambda item: item[1])
sorted_dict = {}
for key, value in sorted_tuple:
sorted_dict[key] = value
#data = sorted_tuple
#sorted_dict = dict(data)
return sorted_dict
print(dictionary_sorter({'a': 3, 'b': 1, 'c': 2}))
'''