Skip to content

Instantly share code, notes, and snippets.

@denstream-io
Last active September 4, 2023 15:57
Show Gist options
  • Save denstream-io/a4388a6661c3507e754a752d6f364b9e to your computer and use it in GitHub Desktop.
Save denstream-io/a4388a6661c3507e754a752d6f364b9e to your computer and use it in GitHub Desktop.
HarvardX CS50 [CS50P] Problem Sets 2022
# INDOOR
input_ = input() # Prompt User for input
output = input_.lower() # Convert input to lower case
print(output) # Display output on screen
# PLAYBACK
input_ = input() # Prompt user for input
output = input_.replace(" ", "...") # Replace "..." with empty space " "
print(output) # Display output on screen
# FACES
def convert(input_): # Pass user input to convert function
if ":)" or ":(" in input_: # Check if the input was ":)" or ":("
return input_.replace(":)","🙂").replace(":(","🙁") # replace ":)" with 🙂 and ":(" with 🙁
def main():
input_ = input() # Prompt user for input
output = convert(input_) # Calling convert function with user input as arguiment
print(output) # Display output on screen
main()
# EINSTEIN
SPEED_OF_LIGHT = 300000000
mass = input("m: ") # Prompt user for input
mass = int(mass) # convert user input to integer
energy = SPEED_OF_LIGHT**2 * mass # Evaluate Albert Einstein formula E = mc^2
print(f"E: {energy}") # Display output on screen
# TIP
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
tip = (dollars * percent) / 100
print(f"Leave ${tip:.2f}") # Display tips in 2dp
def dollars_to_float(d): # Removes "$"
return float(d.lstrip("$"))
def percent_to_float(p): # Removes "%"
return float(p.rstrip("%"))
main()
# BANK
greeting = input("Greeting: ")
greeting = greeting.strip()
if "Hello" in greeting:
print("$0")
elif greeting[0] == "H":
print("$20")
else:
print("$100")
# DEEP
question = input("What is the answer to the Great Question of Life, the Universe, and Everything? ")
question = question.strip().lower()
if question in ["forty two", "forty-two", "42"]:
print("Yes")
else:
print("No")
# EXTENTIONS
filename = input("File name: ")
filename = filename.strip()
if filename.endswith(".gif"):
print("image/gif")
elif filename.endswith(".jpg"):
print("image/jpeg")
elif filename.endswith(".jpeg"):
print("image/jpeg")
elif filename.endswith(".png"):
print("image/png")
elif filename.endswith(".pdf"):
print("application/pdf")
elif filename.endswith(".txt"):
print("text/plain")
elif filename.endswith(".zip"):
print("application/zip")
elif filename.endswith(".bin"):
print("application/octet-stream")
elif filename.endswith(".PDF"):
print("application/pdf")
# INTERPRETER
interpreter = input("Expression: ")
x, y, z = interpreter.split(" ")
x = float(x)
z = float(z)
if y == "+":
print(x + z)
elif y == "-":
print(x - z)
elif y == "*":
print(x * z)
elif y == "/":
print(x / z)
# MEAL
HOUR = 60
def main():
time = input("What time is it? ")
time = convert(time)
if time >= 7.00 and time <= 8.00:
print("breakfast time")
elif time >= 12.00 and time <= 13.00:
print("lunch time")
elif time >= 18.00 and time <= 19.00:
print("dinner time")
def convert(time):
hours, minutes = time.split(":")
hours = float(hours)
minutes = float(minutes) / HOUR
return hours + minutes
if __name__ == "__main__":
main()
# CAMELCASE
name = input("camelCase: ")
for i in name:
if i.isupper():
name = name.replace(i, "_" + i.lower())
print(f"snake_case: {name}")
# COKE
coke = 50
while True:
amount = int(input("Insert Coin: "))
if amount == 30:
print(f"Amount Due: {coke}")
continue
coke = coke - amount
if coke > 0:
print(f"Amount Due: {coke}")
else:
print(f"Change Owed: {-1*coke}")
break
# NUTRITION
fruits = {
"apple": 130,
"avocado" : 50,
"banana" : 110,
"cantaloupe" : 50,
"grapefruit" : 60,
"grapes" : 90,
"honeydew melon" : 50,
"kiwifruit" : 90,
"lemon" : 15,
"lime" : 20,
"Nectarine" : 60,
"orange" : 80,
"peach" : 60,
"pear" : 100,
"pineapple" : 50,
"plums" : 70,
"strawberries" : 50,
"sweet cherries" : 100,
"tangerine" : 50,
"watermelon" : 80
}
fruit = input("Item: " ).lower()
for item in fruits:
if item == fruit:
print(f"Calories: { fruits[fruit] }")
break
# PLATES
from string import punctuation
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
n = len([ch for ch in s if ch.isdigit()])
if s[0:2].isalpha() and len(s[0:2]) == 2 and len(s) <= 6 and str(s[n:][0]) != "0"\
and (s[-n:].isdigit() or s[-n:].isalpha()) and not any(ch in punctuation for ch in s):
return True
main()
# FUEL
while True:
(x, y, z) = input("Fraction: ").partition("/")
try:
x = int(x)
z = int(z)
except ValueError:
continue
try:
percentage = (x/z) * 100
except ZeroDivisionError:
pass
else:
if percentage > 99 and percentage <= 100:
print("F")
elif percentage < 1:
print("E")
elif percentage > 100:
continue
else:
print(f"{percentage:.0f}%")
break
# GROCERY
groceries = {}
while True:
try:
grocery = input("")
except EOFError: # When user input is empty
for (key, value) in sorted(groceries.items()):
print(value, key)
break
grocery = grocery.strip().upper()
try:
groceries[grocery]
except KeyError:
groceries[grocery] = 1
else:
groceries[grocery] += 1
# OUTDATED
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
while True:
format = input("Date: ")
if "/" in format:
format = format.split("/")
try:
day = int(format[1])
month = int(format[0])
except ValueError: # When string letters are converted to numbers
pass
else:
day = int(format[1])
year = format[2]
if day > 31:
continue
elif month > 12:
continue
year = format[2]
month = format[0]
day = format[1]
print(f"{year}-{month.zfill(2)}-{day.zfill(2)}")
break
elif " " in format:
format = format.split(",")
year = format[1]
(month, day) = format[0].split(" ")
try:
month = months.index(month) + 1
day = int(day)
except IndexError:
pass
except ValueError:
pass
else:
if day > 31:
continue
print(f"{year}-{month:02}-{day:02}")
break
# TAQUERA
menus = {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00
}
cost = 0
while True:
try:
item = input("Item: ")
except EOFError:
print("")
break
item = item.strip().title()
try:
menus[item]
except KeyError:
pass
else: # else block will run if try was successfull(without exeptions)
cost = cost + menus[item]
print(f"${cost:.2f}")
# ADIEU
import inflect # Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words
p = inflect.engine()
names = ()
while True:
try:
name = input("Name: ")
except EOFError:
adieu = p.join(names)
print(f"Adieu, adieu, to {adieu}")
break
names = names + (name,)
# BITCOIN
import requests
import sys
if len(sys.argv) == 2:
try:
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
except requests.RequestException:
pass
try:
n = float(sys.argv[1])
except ValueError:
pass
data = float( r.json()['bpi']['USD']['rate_float'])
amount = data * n
print(f"${amount:,.4f}")
else:
sys.exit("Usage: python bitcoin.py bitcoin_amount")
# EMOGIZE
from emoji import emojize
emoji = emojize(input("Input: "))
print(f"Output: {emoji}")
# FIGLET
import sys
from random import choice
from pyfiglet import Figlet
figlet = Figlet()
fonts = figlet.getFonts()
if len(sys.argv) == 1:
s = input("Input: ")
f = choice(fonts)
figlet.setFont(font=f)
print(figlet.renderText(s))
elif len(sys.argv) == 3:
if sys.argv[1] in ["-f", "--font"] and sys.argv[2] in fonts:
s = input("Input: ")
f = sys.argv[2]
figlet.setFont(font=f)
print(figlet.renderText(s))
else:
sys.exit("Invalid usage")
else:
sys.exit("Invalid usage")
# GAME
from random import randint
while True:
try:
n = int(input("Level: "))
except ValueError:
continue
if n > 0:
break
level = randint(1, n)
while True:
try:
guess = int(input("Guess: "))
except ValueError:
continue
else:
if guess < level:
print("Too small!", end="")
continue
elif guess > level:
print("Too large!", end="")
continue
else:
print("Just right!", end="")
break
# PROFESSOR
import random
def main():
score = 0
level = get_level()
for _ in range(10):
number1 = generate_integer(level)
number2 = generate_integer(level)
try:
solution = int(input(f"{number1} + {number2} = "))
except ValueError:
continue
else:
if number1 + number2 == solution:
score += 1
continue
else:
print("EEE")
trials = 0
for _ in range(2):
try:
solution = int(input(f"{number1} + {number2} = "))
except ValueError:
pass
if number1 + number2 == solution:
score += 1
break
else:
print("EEE")
trials += 1
if trials == 2:
solution = number1 + number2
print(f"{number1} + {number2} = {solution}")
print(f"Score: {score}")
def get_level():
while True:
try:
n = int(input("Level: "))
except ValueError:
continue
if n > 0 and n <= 3:
return n
def generate_integer(level):
levels = {
1: (0, 9),
2: (10, 99),
3: (100, 999)
}
if level < 0 or level > 3:
raise ValueError
return random.randint(*levels[level]) # Intresting idea of unpacking
if __name__ == "__main__":
main()
# LINES
import sys
if len(sys.argv) < 2:
sys.exit("Too few command-line arguments")
elif len(sys.argv) > 2:
sys.exit("Too many command-line arguments")
lines = 0
if sys.argv[1].endswith(".py"):
try:
f = open(sys.argv[1], "r")
except FileNotFoundError:
sys.exit("File does not exist")
else:
sys.exit("Not a Python file")
for line in f:
if line.lstrip().startswith("#"): # checks for lines that starts with "#"
pass
elif line.isspace(): # checks for empty space
pass
else:
lines += 1
print(lines)
f.close()
# PIZZA
import sys
import csv
from tabulate import tabulate
if len(sys.argv) < 2:
sys.exit("Too few command-line arguments")
elif len(sys.argv) > 2:
sys.exit("Too many command-line arguments")
table = []
if sys.argv[1].endswith(".csv"):
try:
with open(sys.argv[1], "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
table.append(row)
except FileNotFoundError:
sys.exit("File does not exist")
else:
sys.exit("Not a CSV file")
print(tabulate(table, headers="keys", tablefmt="grid"))
# https://pypi.org/project/tabulate/
# SCOURGIFY
import sys
import csv
if len(sys.argv) < 3:
sys.exit("Too few command-line arguments")
elif len(sys.argv) > 3:
sys.exit("Too many command-line arguments")
try:
r_f = open(sys.argv[1], "r")
except FileNotFoundError:
sys.exit("Could not read invalid_file.csv")
reader = csv.reader(r_f, delimiter=',')
next(reader, None) # skiping field name of original file
fieldnames = ["first", "last", "house"]
with open(sys.argv[2], "w") as w_f:
writer = csv.DictWriter(w_f, fieldnames=fieldnames)
writer.writeheader() # writing field names to new file
for row in reader:
name, house = row
last, first = name.strip("\"\"").strip(" ").split(",")
writer.writerow({'first': first.strip(" "), 'last': last, 'house': house})
r_f.close()
# SHIRT
import sys
from PIL import Image, ImageOps
from os.path import splitext
if len(sys.argv) > 3: # Check for valid cmd #
sys.ext("Too many command-line arguments")
elif len(sys.argv) < 3:
sys.ext("Too few command-line arguments")
_, ext1 = splitext(sys.argv[1]) # get input image extension
_, ext2 = splitext(sys.argv[2])
if ext2 not in [".jpg", ".jpeg", ".png"]: # Varify input/output ext
sys.ext("Invalid output")
if ext1 != ext2:
sys.exit("Input and output have different extensions")
try:
input = Image.open(sys.argv[1]) # open input image
except FileNotFoundError:
sys.exit("Input does not exist")
im = Image.open("shirt.png")
input = ImageOps.fit(input, im.size) # resized input image
input.paste(im, im)
input.save(sys.argv[2])
# NUMB3RS
import re
def main():
print(validate(input("IPv4 Address: ")))
def validate(ip):
if re.search(r"^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$", ip):
return True
else:
return False
if __name__ == "__main__":
main()
# TEST_NUMB3RS
from numb3rs import validate
def main():
test_format()
test_range()
test_length()
test_string()
def test_format():
assert validate('127.0.0.1') == True
assert validate('127:0:0:1') == False
assert validate('127.0.0') == False
assert validate('127.0') == False
assert validate('127') == False
def test_range():
assert validate('255.255.255.255') == True
assert validate('256.255.255.255') == False
assert validate('255.256.255.255') == False
assert validate('255.255.256.255') == False
assert validate('255.255.255.256') == False
def test_length():
assert validate('0.0.0.0') == True
assert validate('0.0.0.0.0') == False
def test_string():
assert validate("cat") == False
assert validate("dog") == False
# RESPONSE
from validator_collection import validators, errors
try:
validators.email(input("email: "))
print("Valid", end="")
except Exception:
print("Invalid", end="")
# UM
import re
def main():
print(count(input("Text: ")))
def count(s):
return len(re.findall(r"\b[uU]m", s))
if __name__=="__main__":
main()
# TEST_UM
from um import count
import pytest
def main():
test_substring()
test_case_sensitivity()
test_special_characters()
def test_substring():
assert count("um") == 1
assert count("um um") == 2
assert count("yummy") == 0
def test_case_sensitivity():
assert count("Um") == 1
assert count("Um Um") == 2
assert count("yUmmy") == 0
def test_special_characters():
assert count("um?") == 1
assert count("um!") == 1
# WATCH
import re
def main():
print(parse(input("HTML: ")))
def parse(s):
if s.startswith("<iframe"):
if matches := re.search(r"https?://(?:www\.)?\w+\.(?:com)/embed/(\w+)", s):
return f"https://youtu.be/{matches.group(1)}"
if __name__ == "__main__":
main()
# WORKING
import re
def main():
print(convert(input("Hours: ")))
def convert(s):
if matches := re.search(r"^(\d\d?[:\s][0-5]?\d?\s?[APM]+)\sto\s(\d\d?[:\s][0-5]?\d?\s?(?:AM|PM))$", s):
return f"{to_24(matches.group(1))} to {to_24(matches.group(2))}"
raise ValueError
def to_24(time):
minutes = "00"
if ":" in time:
hour, am_pm = time.split(" ")
hour, minutes = hour.split(":")
else:
hour, am_pm = time.split(" ")
if int(hour) > 12:
raise ValueError
if am_pm == "AM":
if hour == "12":
return '00' + ':' + minutes
else:
return hour.zfill(2) + ':' + minutes
elif am_pm == "PM":
if hour == "12":
return hour.zfill(2) + ':' + minutes
else:
return str(int(hour) + 12) + ':' + minutes
if __name__ == "__main__":
main()
# TEST_WORKING
from working import convert
import pytest
def test_incorrect_hours():
with pytest.raises(ValueError):
assert convert("13 PM to 13 AM")
def test_incorrect_minutes():
with pytest.raises(ValueError):
assert convert("8:60 AM to 4:60 PM")
def test_format():
assert convert("9 AM to 5 PM") == "09:00 to 17:00"
assert convert("9:00 AM to 5:00 PM") == "09:00 to 17:00"
assert convert("8 PM to 8 AM") == "20:00 to 08:00"
def test_incorrect_format():
with pytest.raises(ValueError):
assert convert("9 AM - 5 PM")
# SEASONS
import sys
import re
import inflect
from datetime import date
p = inflect.engine()
def main():
print(get_date(input("Date of Birth: ")))
def get_date(s):
if matches := re.search(r"^([1-2]\d{3})-(0\d|1[0-2])-(0\d|1\d|2\d|30?1?)$", s):
age = date.today() - date(int(matches.group(1)), int(matches.group(2)), int(matches.group(3)))
return f'{p.number_to_words(age.days * 24 * 60, andword="").capitalize()} minutes'
else:
sys.exit("Invalid date")
if __name__ == "__main__":
main()
# TEST_SEASONS
from seasons import get_date
def test_format():
assert get_date("1999-01-01") == "Twelve million, three hundred thirty-two thousand, one hundred sixty minutes"
# JAR
class Jar:
def __init__(self, capacity=12):
self.capacity = capacity # calls setter '@capacity' method
self.cookie_jar = [] # or self.cookie_jar = 0
def __str__(self):
# self.size calls '@property for size()
return self.size * "🍪"
def deposit(self, n): # n arguiment comes from user
for _ in range(n):
self.cookie_jar.append("🍪") # or self.cookie_jar += 1
if self.size > self.capacity:
raise ValueError
def withdraw(self, n):
if n > self.size:
raise ValueError
for _ in range(n):
self.cookie_jar.pop() # or self.cookie_jar -= 1
@property
def capacity(self):
return self._capacity
@capacity.setter
def capacity(self, capacity): # 'capacity' comes from the programmer or user; from __init__()
if capacity < 0:
raise ValueError
self._capacity = capacity
@property
def size(self):
return len(self.cookie_jar) # or self.cookie_jar
jar = Jar()
jar.deposit(5)
print(jar)
jar.withdraw(2)
print(jar)
# Note that it’s not as easy to test instance methods as it is to test functions
# alone, since instance methods sometimes manipulate the same “state” (i.e., instance variables).
# To test one method (e.g., withdraw), then, you might need to call another method first (e.g., deposit).
# But the method you call first might itself not be correct!
# And so programmers sometimes mock (i.e., simulate) state when testing methods, as
# with Python’s own mock object library, so that you can call just the one method
# but modify the underlying state first, without calling the other method to do so.
# For simplicity, though, no need to mock any state. Implement your tests as you normally would!
# When do you need a class in python? .... to represent a physical/imaginary entity(object)
# TEST_JARS
import pytest
from jar import Jar
def main():
test_init()
test_str()
test_deposit()
test_withdraw()
def test_init():
jar = Jar()
assert jar.capacity == 12 # calls the getter method
def test_str():
jar = Jar()
jar.deposit(2)
assert str(jar) == "🍪🍪"
def test_deposit():
jar = Jar()
jar.deposit(2)
assert jar.size == 2
def test_withdraw():
jar = Jar()
jar.deposit(3)
jar.withdraw(1)
assert jar.size == 2
with pytest.raises(ValueError):
jar.withdraw(4)
# To be continued
@denstream-io
Copy link
Author

I wrote these codes just as the specifications defined them - I didn't bother to add, like, extra functions. I'm always open to learning efficient ways to implement the problem sets, if you have read any part of the code and felt there's a better way to implement it, please feel free to give your valuable suggestions 🙂

Written with ❤️ by denstream-io

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment