├── README.md
└── tasks
├── adieu
└── adieu.py
├── bank
└── bank.py
├── bitcoin
└── bitcoin.py
├── camel
└── camel.py
├── coke
└── coke.py
├── deep
└── deep.py
├── einstein
└── einstein.py
├── emojize
└── emojize.py
├── extensions
└── extensions.py
├── faces
└── faces.py
├── figlet
└── figlet.py
├── fuel
└── fuel.py
├── game
└── game.py
├── grocery
└── grocery.py
├── indoor
└── indoor.py
├── interpreter
└── interpreter.py
├── jar
├── jar.py
└── test_jar.py
├── lines
├── a.py
└── lines.py
├── meal
└── meal.py
├── numb3rs
├── numb3rs.py
└── test_numb3rs.py
├── nutrition
└── nutrition.py
├── outdated
└── outdated.py
├── pizza
├── pizza.py
└── regular.csv
├── plates
└── plates.py
├── playback
├── l
└── playback.py
├── professor
└── professor.py
├── project
├── README.md
├── project.py
├── requirements.txt
└── test_project.py
├── response
└── response.py
├── scourgify
├── after.csv
├── before.csv
└── scourgify.py
├── seasons
├── seasons.py
└── test_seasons.py
├── shirt
├── before1.jpg
├── before2.jpg
├── before3.jpg
├── shirt.png
├── shirt.py
└── yeni.jpg
├── shirtificate
├── shirtificate.pdf
├── shirtificate.png
└── shirtificate.py
├── taqueria
└── taqueria.py
├── test_bank
├── bank.py
└── test_bank.py
├── test_fuel
├── fuel.py
└── test_fuel.py
├── test_plates
├── plates.py
└── test_plates.py
├── test_twttr
├── test_twttr.py
└── twttr.py
├── tip
└── tip.py
├── twttr
└── twttr.py
├── um
├── test_um.py
└── um.py
├── watch
└── watch.py
└── working
├── test_working.py
└── working.py
/README.md:
--------------------------------------------------------------------------------
1 |
2 |

3 |
2022
4 |
Harvard CS50: Introduction to Programing with Python
5 |
6 |
7 |
13 |
14 |
15 |
16 | ⚖️ [Academical honesty](https://cs50.harvard.edu/x/2023/honesty/)
17 |
18 |
19 |
20 |
21 | |Weeks|Topic|Problem Sets|
22 | |-----|-----------|----|
23 | |Week 0 | Functions / Variables|[Indoor Voice](https://github.com/5ah1n/CS50_Python/blob/main/tasks/indoor/indoor.py) - [Playback](https://github.com/5ah1n/CS50_Python/blob/main/tasks/playback/playback.py) - [Faces](https://github.com/5ah1n/CS50_Python/blob/main/tasks/faces/faces.py) - [Einstein](https://github.com/5ah1n/CS50_Python/blob/main/tasks/einstein/einstein.py) - [Tip Calculator](https://github.com/5ah1n/CS50_Python/blob/main/tasks/tip/tip.py)|
24 | |Week 1| Conditionals |[Deep Thought](https://github.com/5ah1n/CS50_Python/blob/main/tasks/deep/deep.py) - [Home Federal Savings Bank](https://github.com/5ah1n/CS50_Python/blob/main/tasks/bank/bank.py) - [File Extensions](https://github.com/5ah1n/CS50_Python/blob/main/tasks/extensions/extensions.py) - [Math Interpreter](https://github.com/5ah1n/CS50_Python/blob/main/tasks/interpreter/interpreter.py) - [Meal Time](https://github.com/5ah1n/CS50_Python/blob/main/tasks/meal/meal.py)
25 | |Week 2 | Loops |[camelCase](https://github.com/5ah1n/CS50_Python/blob/main/tasks/camel/camel.py) - [Coke Machine](https://github.com/5ah1n/CS50_Python/blob/main/tasks/coke/coke.py) - [ Just setting up my twttr](https://github.com/5ah1n/CS50_Python/blob/main/tasks/twttr/twttr.py) - [Vanity Plates](https://github.com/5ah1n/CS50_Python/blob/main/tasks/plates/plates.py) - [Nutrition Facts](https://github.com/5ah1n/CS50_Python/blob/main/tasks/nutrition/nutrition.py)|
26 | |Week 3| Exceptions | [Fuel Gauge](https://github.com/5ah1n/CS50_Python/blob/main/tasks/fuel/fuel.py) - [Felipe’s Taqueria](https://github.com/5ah1n/CS50_Python/blob/main/tasks/taqueria/taqueria.py) - [Grocery List](https://github.com/5ah1n/CS50_Python/blob/main/tasks/grocery/grocery.py) - [Outdated](https://github.com/5ah1n/CS50_Python/blob/main/tasks/outdated/outdated.py)|
27 | |Week 4 | Libraries | [Emojize](https://github.com/5ah1n/CS50_Python/blob/main/tasks/emojize/emojize.py) - [Frank, Ian and Glen’s Letters](https://github.com/5ah1n/CS50_Python/blob/main/tasks/figlet/figlet.py) - [Adieu, Adieu](https://github.com/5ah1n/CS50_Python/blob/main/tasks/adieu/adieu.py) - [Guessing Game](https://github.com/5ah1n/CS50_Python/blob/main/tasks/game/game.py) - [Little Professor](https://github.com/5ah1n/CS50_Python/blob/main/tasks/professor/professor.py) - [Bitcoin Price Index](https://github.com/5ah1n/CS50_Python/blob/main/tasks/bitcoin/bitcoin.py)
28 | | Week 5 | Unit Tests | [Testing my twittr](https://github.com/5ah1n/CS50_Python/blob/main/tasks/twttr/twttr.py) - [Back to the Bank](https://github.com/5ah1n/CS50_Python/blob/main/tasks/bank/bank.py) - [Re-requesting a Vanity Plate](https://github.com/5ah1n/CS50_Python/blob/main/tasks/plates/plates.py) - [Refueling](https://github.com/5ah1n/CS50_Python/blob/main/tasks/fuel/fuel.py)|
29 | |Week 6 | File I/O | [Lines of Code](https://github.com/5ah1n/CS50_Python/tree/main/tasks/lines) - [Pizza Py](https://github.com/5ah1n/CS50_Python/tree/main/tasks/pizza) - [Scourgify](https://github.com/5ah1n/CS50_Python/blob/main/tasks/scourgify/scourgify.py) - [CS50 P-Shirt](https://github.com/5ah1n/CS50_Python/blob/main/tasks/shirt/shirt.py)
30 | |Week 7 | Regular Expressions | [NUMB3RS](https://github.com/5ah1n/CS50_Python/blob/main/tasks/numb3rs/numb3rs) - [Watch on YouTube](https://github.com/5ah1n/CS50_Python/blob/main/tasks/watch/watch.py) - [Working 9 to 5](https://github.com/5ah1n/CS50_Python/tree/main/tasks/working) - [Regular, um, Expressions](https://github.com/5ah1n/CS50_Python/tree/main/tasks/um) - [Response Validation](https://github.com/5ah1n/CS50_Python/blob/main/tasks/response/response.py)
31 | |Week 8 | OOP | [Seasons of Love](https://github.com/5ah1n/CS50_Python/tree/main/tasks/seasons) - [Cookie Jar](https://github.com/5ah1n/CS50_Python/tree/main/tasks/jar) - [CS50 Shirtificate](https://github.com/5ah1n/CS50_Python/blob/main/tasks/shirtificate/shirtificate.py)
32 | |Week 9 | ET Cetera | [Final Project](https://github.com/5ah1n/CS50_Python/tree/main/tasks/project)
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/tasks/adieu/adieu.py:
--------------------------------------------------------------------------------
1 | import inflect
2 |
3 | l = []
4 | p = inflect.engine()
5 |
6 | while True:
7 | try:
8 | a = str(input("Input: "))
9 | l.append(a)
10 | except EOFError:
11 | print()
12 | break
13 |
14 | result = p.join(l)
15 | print("Adieu, adieu, to",result)
16 |
--------------------------------------------------------------------------------
/tasks/bank/bank.py:
--------------------------------------------------------------------------------
1 | a = input("Greeting:")
2 |
3 | b = a.lower().replace(" ","")
4 |
5 | if not b.find("hello"):
6 | print("$0")
7 |
8 | elif b[0] == "h":
9 | print("$20")
10 |
11 | else:
12 | print("$100")
--------------------------------------------------------------------------------
/tasks/bitcoin/bitcoin.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import requests
3 | import json
4 |
5 | def main():
6 | g = get_coin()
7 | req_coin(g)
8 |
9 | def get_coin():
10 | #print(sys.argv)
11 | if len(sys.argv) == 2:
12 | try:
13 | if float(sys.argv[1]):
14 | return sys.argv[1]
15 | except ValueError:
16 | print("Command-line argument is not a number")
17 | sys.exit(1)
18 | else:
19 | print("Missing command-line argument")
20 | sys.exit(1)
21 |
22 | def req_coin(gcoin):
23 | req = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
24 | data = req.json()
25 | usd = data["bpi"]["USD"]["rate_float"]
26 | result = float(usd) * float(gcoin)
27 | print(gcoin)
28 | print(f"${result:,.4f}")
29 |
30 | main()
--------------------------------------------------------------------------------
/tasks/camel/camel.py:
--------------------------------------------------------------------------------
1 | text = input("camelCase: ")
2 | text = "".join(["_" + a.lower() if a.isupper() else a for a in text]).strip("_")
3 | print(f"snake_case: {text}")
--------------------------------------------------------------------------------
/tasks/coke/coke.py:
--------------------------------------------------------------------------------
1 | cash = 50
2 |
3 | while cash > 0:
4 | print(f"Amount due: {cash}")
5 | cent = int(input("Amount Due:"))
6 | if cent == 10 or cent == 25 or cent == 5:
7 | cash -= cent
8 |
9 | print(f"Change owed: {abs(cash)}")
--------------------------------------------------------------------------------
/tasks/deep/deep.py:
--------------------------------------------------------------------------------
1 | a = input("What is the Answer to the Great Question of Life, the Universe, and Everything?")
2 |
3 | b = a.lower().replace("-","").replace(" ","")
4 |
5 | if b == "fortytwo" or b == "42":
6 | print("Yes")
7 | else:
8 | print("No")
--------------------------------------------------------------------------------
/tasks/einstein/einstein.py:
--------------------------------------------------------------------------------
1 | a = int(input(""))
2 |
3 | c = 3 * 10 ** 8
4 | print(int(a * (c ** 2)))
5 |
--------------------------------------------------------------------------------
/tasks/emojize/emojize.py:
--------------------------------------------------------------------------------
1 | from emoji import emojize
2 | user_input = input("Enter your text: ")
3 | print("Output:", emojize(user_input, language="alias"))
4 |
5 | # edited again according to the suggestion/correction here
6 | # https://github.com/sahinyes/CS50_Python/issues/2
7 |
--------------------------------------------------------------------------------
/tasks/extensions/extensions.py:
--------------------------------------------------------------------------------
1 | a = input("File name: ")
2 |
3 | b = a.split(".")
4 |
5 | match b[-1].lower().strip():
6 | case "gif":
7 | print("image/gif")
8 | case "jpg" | "jpeg":
9 | print("image/jpeg")
10 | case "png":
11 | print("image/png")
12 | case "pdf":
13 | print("application/pdf")
14 | case "txt":
15 | print("text/plain")
16 | case "zip":
17 | print("application/zip")
18 | case "txt":
19 | print("text/plain")
20 | case "bin" | _ :
21 | print("application/octet-stream")
--------------------------------------------------------------------------------
/tasks/faces/faces.py:
--------------------------------------------------------------------------------
1 | a = input("")
2 | print(a.replace(":(","🙁").replace(":)","🙂"))
--------------------------------------------------------------------------------
/tasks/figlet/figlet.py:
--------------------------------------------------------------------------------
1 | from pyfiglet import Figlet
2 | import sys
3 | import random
4 |
5 | figlet = Figlet()
6 | figlet.getFonts()
7 |
8 |
9 | if len(sys.argv) == 1:
10 | is_random = True
11 | elif len(sys.argv) == 3 and (sys.argv[1] == "-f" or sys.argv[1] == "--font"):
12 | is_random = False
13 | else:
14 | print("Invalid Usage")
15 | sys.exit(1)
16 |
17 | if is_random == False:
18 | try:
19 | figlet.setFont(font=sys.argv[2])
20 | except:
21 | print("Invalid usage")
22 | sys.exit(1)
23 | else:
24 | font = random.choice(figlet.getFonts())
25 |
26 |
27 | text = input("Input:")
28 | print("Output:", figlet.renderText(text))
29 |
30 |
--------------------------------------------------------------------------------
/tasks/fuel/fuel.py:
--------------------------------------------------------------------------------
1 | def main():
2 | x = get_int()
3 | print(f"{x}")
4 |
5 | def get_int():
6 | while True:
7 | try:
8 | a = input("a: ").split("/")
9 | c = float((int(a[0]) / int(a[1]))*100)
10 | if int(a[0]) <= int(a[1]):
11 | if c >= 99:
12 | print("F")
13 | elif c <= 1:
14 | print("E")
15 | else:
16 | print(f"{round(float(c))}%")
17 | exit()
18 | else:
19 | return get_int()
20 | except (ValueError, ZeroDivisionError):
21 | continue
22 | main()
--------------------------------------------------------------------------------
/tasks/game/game.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | while True:
4 | try:
5 | i = int(input("Level: "))
6 | if i > 0:
7 | break
8 | except:
9 | pass
10 |
11 | r = random.randint(1,i)
12 |
13 | while True:
14 | try:
15 | a = int(input("Guess: "))
16 | if a != 0:
17 | if a < r:
18 | print("Too small!")
19 | elif a > r:
20 | print("Too large!")
21 | else:
22 | print("Just Right!")
23 | break
24 | except:
25 | pass
--------------------------------------------------------------------------------
/tasks/grocery/grocery.py:
--------------------------------------------------------------------------------
1 | l = []
2 | c = {}
3 |
4 |
5 | while True:
6 | try:
7 | a = input().upper()
8 | l.append(a)
9 | except EOFError:
10 | print("")
11 | for i in l:
12 | if not i in c:
13 | c[i] = 1
14 | else:
15 | c[i] += 1
16 |
17 | for key, value in sorted(c.items()):
18 | print(value,key)
19 | exit()
--------------------------------------------------------------------------------
/tasks/indoor/indoor.py:
--------------------------------------------------------------------------------
1 | a = input("")
2 | print(f"{a.lower()}")
--------------------------------------------------------------------------------
/tasks/interpreter/interpreter.py:
--------------------------------------------------------------------------------
1 | x, y, z = input("Expression: ").split(" ")
2 |
3 | if y == "+":
4 | print(float(x) + float(z))
5 | elif y == "-":
6 | print(float(x) - float(z))
7 | elif y == "*":
8 | print(float(x) * float(z))
9 | elif y == "/":
10 | print(float(x) / float(z))
--------------------------------------------------------------------------------
/tasks/jar/jar.py:
--------------------------------------------------------------------------------
1 | class Jar:
2 | def __init__(self, capacity=12):
3 | if capacity > 0:
4 | self._capacity = capacity
5 | self._size = 0
6 | else:
7 | raise ValueError("Wrong capacity")
8 |
9 | def __str__(self):
10 | return self.size * '🍪'
11 |
12 | def deposit(self, n):
13 | if n > self.capacity or (self.size + n) > self.capacity:
14 | raise ValueError("Over capacity")
15 | self._size += n
16 |
17 | def withdraw(self, n):
18 | if n > self.size:
19 | raise ValueError
20 | self._size -= n
21 | @property
22 | def capacity(self):
23 | return self._capacity
24 |
25 | @property
26 | def size(self):
27 | return self._size
28 |
--------------------------------------------------------------------------------
/tasks/jar/test_jar.py:
--------------------------------------------------------------------------------
1 | from jar import Jar
2 |
3 | def test_init():
4 | jar = Jar()
5 | assert jar.capacity == 12
6 | jar1 = Jar(1)
7 | assert jar1.capacity == 1
8 |
9 | def test_str():
10 | jar = Jar()
11 | assert str(jar) == ""
12 | jar.deposit(1)
13 | assert str(jar) == "🍪"
14 | jar.deposit(11)
15 | assert str(jar) == "🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪"
16 |
17 |
18 | def test_deposit():
19 | jar = Jar()
20 | jar.deposit(5)
21 | assert jar.size == 5
22 | jar.deposit(5)
23 | assert jar.size == 10
24 |
25 |
26 | def test_withdraw():
27 | jar = Jar()
28 | jar.deposit(10)
29 | jar.withdraw(5)
30 | assert jar.size == 5
31 | jar.withdraw(5)
32 | assert jar.size == 0
33 |
34 |
--------------------------------------------------------------------------------
/tasks/lines/a.py:
--------------------------------------------------------------------------------
1 | asdf
2 | asdf
3 | asd
4 | f
5 | sadf
6 | sa
7 | df
8 | #asd
9 | 3fas
10 | dfa
11 | sdf
12 | #isa
13 | #dfas
14 | dfas
15 |
16 |
--------------------------------------------------------------------------------
/tasks/lines/lines.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | if len(sys.argv) <= 1:
4 | sys.exit("Too few command-line arguments")
5 | elif len(sys.argv) >= 3:
6 | sys.exit("Too many command-line arguments")
7 | elif sys.argv[1].rsplit(".")[1] != "py":
8 | sys.exit("Not a Python file")
9 | try:
10 | with open(sys.argv[1], "r") as file:
11 | count = 0
12 | for line in file:
13 | if not line.lstrip().startswith("#") and line.lstrip() != "":
14 | count += 1
15 | print(count)
16 |
17 | except:
18 | raise FileNotFoundError
--------------------------------------------------------------------------------
/tasks/meal/meal.py:
--------------------------------------------------------------------------------
1 | def main():
2 | time = input("What time is it? ")
3 | meal = convert(time)
4 | if meal >= 7 and meal <=8:
5 | print("breakfast time")
6 | elif meal >= 12 and meal <=13:
7 | print("lunch time")
8 | elif meal >= 18 and meal <= 19:
9 | print("dinner time")
10 |
11 | def convert(time):
12 | hour, min = time.split(":")
13 | hour = float(hour) + (float(min) / 60)
14 | return hour
15 |
16 | if __name__ == "__main__":
17 | main()
--------------------------------------------------------------------------------
/tasks/numb3rs/numb3rs.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | def main():
4 | print(validate(input("IPv4 Address: ")))
5 |
6 | def validate(ip):
7 | if numbers := re.search(r"^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$", ip):
8 | for i in range(1,5):
9 | if int(numbers.group(i)) > 255 or int(numbers.group(i)) < 0 :
10 | return False
11 | return True
12 | else:
13 | return False
14 |
15 |
16 | if __name__ == "__main__":
17 | main()
18 |
--------------------------------------------------------------------------------
/tasks/numb3rs/test_numb3rs.py:
--------------------------------------------------------------------------------
1 | from numb3rs import validate
2 |
3 | def main():
4 | test_validate1()
5 | test_validate2()
6 |
7 | def test_validate1():
8 |
9 | assert validate(r"127.0.0.1") == True
10 | assert validate(r"cat") == False
11 | assert validate(r"255.255.255.255") == True
12 | assert validate(r"512.512.512.512") == False
13 | assert validate(r"1.2.3.1000") == False
14 | assert validate(r"140.247.235.144") == True
15 | assert validate(r"2001:0db8:85a3:0000:0000:8a2e:0370:7334") == False
16 | assert validate(r"64.128.256.512") == False
17 |
18 | def test_validate2():
19 |
20 | assert validate(r"255.255.255.275") == False
21 | assert validate(r"256.255.255.255") == False
22 | assert validate(r"255.255.275.255") == False
23 | assert validate(r"255.275.255.255") == False
24 | assert validate(r"275.255.255.255") == False
25 | assert validate(r"1.275.275.275") == False
26 | assert validate(r"255.255.255.255") == True
27 |
28 | if __name__ == "__main__":
29 | main()
30 |
--------------------------------------------------------------------------------
/tasks/nutrition/nutrition.py:
--------------------------------------------------------------------------------
1 | poster = {
2 | "apple": 130,
3 | "avocado": 50,
4 | "banana": 110,
5 | "cantaloupe": 50,
6 | "grapefruit": 60,
7 | "grapes": 90,
8 | "honeydew melon": 50,
9 | "kiwifruit": 90,
10 | "lemon": 15,
11 | "lime": 20,
12 | "nectarine": 60,
13 | "orange": 80,
14 | "peach": 60,
15 | "pear": 100,
16 | "pineapple": 50,
17 | "plumns": 70,
18 | "strawberries": 50,
19 | "sweet cherries": 100,
20 | "tangerine": 50,
21 | "watermelon": 80
22 | }
23 |
24 | a = input("Fruit: ").lower()
25 |
26 | if a in poster:
27 | print(f"Calories {poster[a]}")
28 |
--------------------------------------------------------------------------------
/tasks/outdated/outdated.py:
--------------------------------------------------------------------------------
1 | l = [
2 | "January",
3 | "February",
4 | "March",
5 | "April",
6 | "May",
7 | "June",
8 | "July",
9 | "August",
10 | "September",
11 | "October",
12 | "November",
13 | "December"
14 | ]
15 |
16 | while True:
17 | date = input("Date: ")
18 | try:
19 | if "/" in date:
20 | month, day, year = date.split("/")
21 | if int(month) >= 1 and int(month) <= 12 and int(day) >= 1 and int(day) <= 31:
22 | break
23 |
24 | elif "," in date:
25 | date = date.replace(",", "")
26 | month,day,year = date.split(" ")
27 | if month in l and int(day) <= 31:
28 | month = l.index(month) + 1
29 | break
30 | except:
31 | print()
32 | pass
33 |
34 |
35 | print(f"{int(year)}-{int(month):02}-{int(day):02}")
36 |
--------------------------------------------------------------------------------
/tasks/pizza/pizza.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import tabulate
3 | import csv
4 |
5 | if len(sys.argv) <= 1:
6 | sys.exit("Too few command-line arguments")
7 | elif len(sys.argv) > 2:
8 | sys.exit("Too many command-line arguments")
9 | elif sys.argv[1].rsplit(".")[1] != "csv":
10 | sys.exit("Not a CSV file")
11 |
12 | try:
13 | with open(sys.argv[1], "r") as file:
14 | reader = csv.DictReader(file)
15 | print(tabulate.tabulate(reader, headers="keys", tablefmt="grid"))
16 | except:
17 | raise FileNotFoundError
18 |
19 |
--------------------------------------------------------------------------------
/tasks/pizza/regular.csv:
--------------------------------------------------------------------------------
1 | Regular Pizza,Small,Large
2 | Cheese,$13.50,$18.95
3 | 1 topping,$14.75,$20.95
4 | 2 toppings,$15.95,$22.95
5 | 3 toppings,$16.95,$24.95
6 | Special,$18.50,$26.95
7 |
--------------------------------------------------------------------------------
/tasks/plates/plates.py:
--------------------------------------------------------------------------------
1 | def main():
2 | plate = input("Plate: ")
3 | if is_valid(plate):
4 | print("Valid")
5 | else:
6 | print("Invalid")
7 |
8 | def is_valid(s):
9 | if len(s) <= 6 and len(s) >= 2 and s[0:2].isalpha() and s.isalnum():
10 | for i in s:
11 | if i.isdigit():
12 | result = s.index(i)
13 | if s[result:].isdigit() and int(i) != 0:
14 | return True
15 | else:
16 | return False
17 | return True
18 |
19 | main()
20 |
21 |
--------------------------------------------------------------------------------
/tasks/playback/l:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/playback/l
--------------------------------------------------------------------------------
/tasks/playback/playback.py:
--------------------------------------------------------------------------------
1 | a = input("")
2 | print(a.replace(" ","..."))
--------------------------------------------------------------------------------
/tasks/professor/professor.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 |
4 | def main():
5 | level = get_level()
6 | generate_integer(level)
7 |
8 | def get_level():
9 | while True:
10 | try:
11 | level = int(input("Level: "))
12 | if level in [1,2,3]:
13 | return level
14 | except ValueError:
15 | pass
16 |
17 | def generate_integer(level):
18 | counter = 3
19 | score = 0
20 | for i in range(10):
21 | if level == 1:
22 | a = random.randint(0,9)
23 | b = random.randint(0,9)
24 | elif level == 2:
25 | a = random.randint(10,99)
26 | b = random.randint(10,99)
27 | elif level == 3:
28 | a = random.randint(100,999)
29 | b = random.randint(100,999)
30 | while True:
31 | try:
32 | answer = input(f"{a} + {b} = ")
33 | if int(answer) == (a+b):
34 | score += 1
35 | break
36 | elif answer != (a+b):
37 | counter -= 1
38 | print("EEE")
39 | if counter <= 0:
40 | print(f"{a} + {b} = {a+b}")
41 | break
42 | except ValueError:
43 | pass
44 | else:
45 | print(f"Score: {score}")
46 |
47 | if __name__ == "__main__":
48 | main()
--------------------------------------------------------------------------------
/tasks/project/README.md:
--------------------------------------------------------------------------------
1 |
2 | # cs50 Final
3 | #### Video Demo: https://youtu.be/n8XVfozVkgU
4 |
5 | ## Description
6 | This is my final project for "Harvard CS50 Introduction to programming with Python". This project makes websites scraping easier. You can see quickly the comment lines or directories which the page has.
7 |
8 | This project will also print requests and responses for you. From the URL addresse that you gave as an input, it will print the website response code from the URL link and the page sizes.
9 |
10 | You need to be careful when you use it because it will look inside the directories which are found and sometimes it takes a lot of time and too much request. WAF (Web Application Firewall) can easily detect you, and probably you will get an IP ban.
11 |
12 | ## Installation & Use
13 | 1. Clone the code.
14 | 1. Run the command `pip install -r requirements.txt` in the app directory.
15 | 2. Than run it: `python3 ./project.py -u https://example.com`
16 |
17 | ## Overviews
18 | ```
19 | project/ $ python3 project.py
20 | +-+-+-+-+ +-+-+-+-+-+-+-+-+-+
21 | |C|S|5|0| |@|s|a|h|i|n|y|e|s|
22 | +-+-+-+-+ +-+-+-+-+-+-+-+-+-+
23 | +-+-+-+-+-+ +-+-+-+-+-+-+-+
24 | |F|i|n|a|l| |P|r|o|j|e|c|t|
25 | +-+-+-+-+-+ +-+-+-+-+-+-+-+
26 |
27 | python ./project.py
28 | python ./project.py -u
29 | python ./project.py --url
30 |
31 | URL:
32 | ```
33 |
34 | ```
35 | project/ $ python3 ./project.py --url https://cs50.harvard.edu/course
36 | +-+-+-+-+ +-+-+-+-+-+-+-+-+-+
37 | |C|S|5|0| |@|s|a|h|i|n|y|e|s|
38 | +-+-+-+-+ +-+-+-+-+-+-+-+-+-+
39 | +-+-+-+-+-+ +-+-+-+-+-+-+-+
40 | |F|i|n|a|l| |P|r|o|j|e|c|t|
41 | +-+-+-+-+-+ +-+-+-+-+-+-+-+
42 |
43 | python ./project.py
44 | python ./project.py -u
45 | python ./project.py --url
46 |
47 | https://cs50.harvard.edu/course Status: 404 Size: 623
48 | # COMMENT LINES
49 | # https://github.com/httpcats/http.cat
50 | ```
51 |
--------------------------------------------------------------------------------
/tasks/project/project.py:
--------------------------------------------------------------------------------
1 | import re
2 | import sys
3 | import requests
4 | from colorama import Fore, Style
5 | import pyfiglet
6 |
7 | #Banner
8 | print(pyfiglet.figlet_format("CS50 @sahinyes\nFinal Project", font= "digital"))
9 | print(f"{Fore.YELLOW}python ./project.py\npython ./project.py -u \npython ./project.py --url \n{Style.RESET_ALL}")
10 |
11 | def main():
12 | global l
13 | l = []
14 | is_regex(url_valid())
15 | if int(len(l)) != 0:
16 | for i in range(len(l)):
17 | req(l[i])
18 | i += 1
19 | else:
20 | pass
21 |
22 |
23 | #URL validation
24 | def url_valid():
25 | if len(sys.argv) == 1:
26 | url = input("URL:")
27 | return url
28 | elif len(sys.argv) != 3:
29 | sys.exit(f"{Fore.RED}Should be three argument <>{Style.RESET_ALL}")
30 | elif str(sys.argv[1]) != "-u" and str(sys.argv[1]) != "--url":
31 | sys.exit(f"{Fore.RED}Need -u or --url flag{Style.RESET_ALL}")
32 | else:
33 | url = str(sys.argv[2])
34 | return url
35 |
36 | def is_regex(url):
37 | if re_url := re.findall(r"^https?://.*", url):
38 | global g_url
39 | g_url = re_url[0]
40 | return req(g_url)
41 | else:
42 | print(f"{Fore.RED}URL is not valid{Style.RESET_ALL}")
43 | return False
44 |
45 |
46 | #Request
47 | def req(url):
48 | try:
49 | r = requests.get(url)
50 | if int(r.status_code) <= 302:
51 | print(f"{url} {Fore.GREEN}Status: {r.status_code}{Style.RESET_ALL} Size: {len(r.content)}")
52 | elif int(r.status_code) >= 500:
53 | print(f"{url} {Fore.YELLOW}Status: {r.status_code}{Style.RESET_ALL} Size: {len(r.content)}")
54 | elif int(r.status_code) == 403 :
55 | print(f"{url} {Fore.RED}Status: {r.status_code}{Style.RESET_ALL} Size: {len(r.content)}")
56 | elif int(r.status_code) == 404:
57 | print(f"{url} {Fore.WHITE}Status: {r.status_code}{Style.RESET_ALL} Size: {len(r.content)}")
58 | else:
59 | print(f"{url} {Fore.YELLOW}Status: {r.status_code}{Style.RESET_ALL} Size: {len(r.content)}")
60 | return dir(r), comment(r), True
61 | except:
62 | sys.exit(f"{Fore.RED}Cannot not request to website{Style.RESET_ALL}")
63 |
64 | #Comment lines
65 | def comment(r):
66 | comments = re.findall(r"", r.text)
67 | global com_l
68 | com_l = []
69 |
70 | if len(comments) == 0:
71 | print(f"{Fore.YELLOW}No comment line founded{Style.RESET_ALL}")
72 | else:
73 | print(f"{Fore.GREEN}# COMMENT LINES{Style.RESET_ALL}")
74 | for comment in comments:
75 | a = comment.replace("","")
76 | if a not in com_l: com_l.append(a)
77 | print(f"{Fore.CYAN}{a}{Style.RESET_ALL}")
78 |
79 |
80 | #Check Directories
81 | def dir(r):
82 | try:
83 | dirs = re.findall(r"href=[\"']?(?!http|mailto)([^\"'#@>]+\.?\w+)", r.text)
84 | #print(f"{Fore.YELLOW}Possible Directories: {len(dirs)}{Style.RESET_ALL}")
85 | return scanner(dirs)
86 | except:
87 | print("Cannot discover directories")
88 |
89 |
90 | #Dirscanner
91 | def scanner(dirs):
92 | for dir in dirs:
93 | new_u = str(g_url).removesuffix("/") + "/" + str(dir).replace("/","",1).replace(".","",1)
94 | if new_u not in l:
95 | l.append(new_u)
96 | else:
97 | pass
98 |
99 |
100 | if __name__ == "__main__":
101 | main()
102 |
103 |
--------------------------------------------------------------------------------
/tasks/project/requirements.txt:
--------------------------------------------------------------------------------
1 | requests
2 | colorama
3 | pyfiglet
--------------------------------------------------------------------------------
/tasks/project/test_project.py:
--------------------------------------------------------------------------------
1 | from project import is_regex, req, url_valid
2 | import pytest
3 |
4 | def main():
5 | test_is_regex()
6 | test_req()
7 | test_url_valid()
8 |
9 |
10 | @pytest.fixture(autouse=True)
11 | def mock_args(monkeypatch):
12 | monkeypatch.setattr("sys.argv", ["pytest", "example_input"])
13 |
14 | #With not enought or more argument
15 | def test_url_valid():
16 | with pytest.raises(SystemExit, match="Should be three argument <>"):
17 | url_valid()
18 |
19 | #Input validation
20 | def test_is_regex():
21 | assert is_regex("http") == False
22 | assert is_regex("https") == False
23 | assert is_regex("www.sahinyes.com") == False
24 | assert is_regex("http:/www.sahinyes.com") == False
25 |
26 | #If website doesnt give some responses or errors
27 | def test_req():
28 | #Example for valid website
29 | assert req("https://www.sahinyes.com") == (None, None, True)
30 |
31 | with pytest.raises(SystemExit, match="Cannot not request to website"):
32 | req("invalidwebsite.comq")
33 | req("htpp://invalidwebsite.com")
34 | req("www.invalidwebsite.com")
35 |
36 |
37 | if __name__ == "__main__":
38 | main()
--------------------------------------------------------------------------------
/tasks/response/response.py:
--------------------------------------------------------------------------------
1 | from validator_collection import checkers
2 |
3 | def main():
4 | print(is_valid(input("email: ")))
5 |
6 |
7 | def is_valid(s):
8 | if checkers.is_email(s):
9 | return "Valid"
10 | else:
11 | return "Invalid"
12 |
13 |
14 |
15 | if __name__ == "__main__":
16 | main()
--------------------------------------------------------------------------------
/tasks/scourgify/after.csv:
--------------------------------------------------------------------------------
1 | first,last,house
2 | Hannah,Abbott,Hufflepuff
3 | Katie,Bell,Gryffindor
4 | Susan,Bones,Hufflepuff
5 | Terry,Boot,Ravenclaw
6 | Lavender,Brown,Gryffindor
7 | Millicent,Bulstrode,Slytherin
8 | Cho,Chang,Ravenclaw
9 | Penelope,Clearwater,Ravenclaw
10 | Vincent,Crabbe,Slytherin
11 | Colin,Creevey,Gryffindor
12 | Dennis,Creevey,Gryffindor
13 | Cedric,Diggory,Hufflepuff
14 | Marietta,Edgecombe,Ravenclaw
15 | Justin,Finch-Fletchley,Hufflepuff
16 | Seamus,Finnigan,Gryffindor
17 | Anthony,Goldstein,Ravenclaw
18 | Gregory,Goyle,Slytherin
19 | Hermione,Granger,Gryffindor
20 | Angelina,Johnson,Gryffindor
21 | Lee,Jordan,Gryffindor
22 | Neville,Longbottom,Gryffindor
23 | Luna,Lovegood,Ravenclaw
24 | Remus,Lupin,Gryffindor
25 | Draco,Malfoy,Slytherin
26 | Scorpius,Malfoy,Slytherin
27 | Ernie,Macmillan,Hufflepuff
28 | Minerva,McGonagall,Gryffindor
29 | Eloise,Midgen,Gryffindor
30 | Cormac,McLaggen,Gryffindor
31 | Graham,Montague,Slytherin
32 | Theodore,Nott,Slytherin
33 | Pansy,Parkinson,Slytherin
34 | Padma,Patil,Gryffindor
35 | Parvati,Patil,Gryffindor
36 | Harry,Potter,Gryffindor
37 | Tom,Riddle,Slytherin
38 | Demelza,Robins,Gryffindor
39 | Newt,Scamander,Hufflepuff
40 | Horace,Slughorn,Slytherin
41 | Zacharias,Smith,Hufflepuff
42 | Severus,Snape,Slytherin
43 | Alicia,Spinnet,Gryffindor
44 | Pomona,Sprout,Hufflepuff
45 | Dean,Thomas,Gryffindor
46 | Romilda,Vane,Gryffindor
47 | Myrtle,Warren,Ravenclaw
48 | Fred,Weasley,Gryffindor
49 | George,Weasley,Gryffindor
50 | Ginny,Weasley,Gryffindor
51 | Percy,Weasley,Gryffindor
52 | Ron,Weasley,Gryffindor
53 | Oliver,Wood,Gryffindor
54 | Blaise,Zabini,Slytherin
55 |
--------------------------------------------------------------------------------
/tasks/scourgify/before.csv:
--------------------------------------------------------------------------------
1 | name,house
2 | "Abbott, Hannah",Hufflepuff
3 | "Bell, Katie",Gryffindor
4 | "Bones, Susan",Hufflepuff
5 | "Boot, Terry",Ravenclaw
6 | "Brown, Lavender",Gryffindor
7 | "Bulstrode, Millicent",Slytherin
8 | "Chang, Cho",Ravenclaw
9 | "Clearwater, Penelope",Ravenclaw
10 | "Crabbe, Vincent",Slytherin
11 | "Creevey, Colin",Gryffindor
12 | "Creevey, Dennis",Gryffindor
13 | "Diggory, Cedric",Hufflepuff
14 | "Edgecombe, Marietta",Ravenclaw
15 | "Finch-Fletchley, Justin",Hufflepuff
16 | "Finnigan, Seamus",Gryffindor
17 | "Goldstein, Anthony",Ravenclaw
18 | "Goyle, Gregory",Slytherin
19 | "Granger, Hermione",Gryffindor
20 | "Johnson, Angelina",Gryffindor
21 | "Jordan, Lee",Gryffindor
22 | "Longbottom, Neville",Gryffindor
23 | "Lovegood, Luna",Ravenclaw
24 | "Lupin, Remus",Gryffindor
25 | "Malfoy, Draco",Slytherin
26 | "Malfoy, Scorpius",Slytherin
27 | "Macmillan, Ernie",Hufflepuff
28 | "McGonagall, Minerva",Gryffindor
29 | "Midgen, Eloise",Gryffindor
30 | "McLaggen, Cormac",Gryffindor
31 | "Montague, Graham",Slytherin
32 | "Nott, Theodore",Slytherin
33 | "Parkinson, Pansy",Slytherin
34 | "Patil, Padma",Gryffindor
35 | "Patil, Parvati",Gryffindor
36 | "Potter, Harry",Gryffindor
37 | "Riddle, Tom",Slytherin
38 | "Robins, Demelza",Gryffindor
39 | "Scamander, Newt",Hufflepuff
40 | "Slughorn, Horace",Slytherin
41 | "Smith, Zacharias",Hufflepuff
42 | "Snape, Severus",Slytherin
43 | "Spinnet, Alicia",Gryffindor
44 | "Sprout, Pomona",Hufflepuff
45 | "Thomas, Dean",Gryffindor
46 | "Vane, Romilda",Gryffindor
47 | "Warren, Myrtle",Ravenclaw
48 | "Weasley, Fred",Gryffindor
49 | "Weasley, George",Gryffindor
50 | "Weasley, Ginny",Gryffindor
51 | "Weasley, Percy",Gryffindor
52 | "Weasley, Ron",Gryffindor
53 | "Wood, Oliver",Gryffindor
54 | "Zabini, Blaise",Slytherin
55 |
--------------------------------------------------------------------------------
/tasks/scourgify/scourgify.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import csv
3 |
4 | students = []
5 |
6 | if len(sys.argv) < 3:
7 | sys.exit("Too few command-line arguments")
8 | elif len(sys.argv) > 3:
9 | sys.exit("Too many command-line arguments")
10 | elif len(sys.argv) == 3:
11 | try:
12 | with open(sys.argv[1], "r") as rfile, open(sys.argv[2], "w") as wfile:
13 | reader = csv.DictReader(rfile)
14 | for row in reader:
15 | splited = row["name"].split(",")
16 | students.append({
17 | "first": splited[1].lstrip(),
18 | "last": splited[0],
19 | "house": row["house"
20 | ]})
21 | writer = csv.DictWriter(wfile, fieldnames=["first", "last", "house"])
22 | writer.writerow({
23 | "first": "first",
24 | "last": "last",
25 | "house": "house"
26 | })
27 | for row in students:
28 | writer.writerow({
29 | "first": row["first"],
30 | "last": row["last"],
31 | "house": row["house"]
32 | })
33 |
34 | except FileNotFoundError:
35 | sys.exit("Could not read invalid_file.csv")
--------------------------------------------------------------------------------
/tasks/seasons/seasons.py:
--------------------------------------------------------------------------------
1 | from datetime import date
2 | import inflect
3 | import sys
4 |
5 | p = inflect.engine()
6 |
7 |
8 | def main():
9 | birthday = input("Date: ")
10 | return diff(birthday)
11 |
12 | def diff(birthday):
13 | try:
14 | year, month, day = birthday.split("-")
15 | birthday = date(int(year), int(month), int(day))
16 | except:
17 | return sys.exit("Invalid")
18 | difference = (date.today() - birthday).days * 24 * 60
19 | result = p.number_to_words(difference, andword="").capitalize()
20 | print(result + " minutes")
21 | return result + " minutes"
22 |
23 |
24 | if __name__ == "__main__":
25 | main()
--------------------------------------------------------------------------------
/tasks/seasons/test_seasons.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from seasons import diff
3 |
4 | def main():
5 | test()
6 |
7 | def test():
8 | assert diff("2022-01-20") == "Five hundred twenty-five thousand, six hundred minutes"
9 | assert diff("2021-01-20") == "One million, fifty-one thousand, two hundred minutes"
10 | with pytest.raises(SystemExit, match="Invalid"):
11 | diff("Januar 6th, 1998")
12 |
13 |
14 |
15 | if __name__ == "__main__":
16 | main()
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/tasks/shirt/before1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirt/before1.jpg
--------------------------------------------------------------------------------
/tasks/shirt/before2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirt/before2.jpg
--------------------------------------------------------------------------------
/tasks/shirt/before3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirt/before3.jpg
--------------------------------------------------------------------------------
/tasks/shirt/shirt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirt/shirt.png
--------------------------------------------------------------------------------
/tasks/shirt/shirt.py:
--------------------------------------------------------------------------------
1 | from PIL import Image, ImageOps
2 | import sys
3 |
4 | if len(sys.argv) == 3:
5 | a = sys.argv[1].split(".")[1]
6 | b = sys.argv[2].split(".")[1]
7 | if a == b:
8 | if b in ["jpg", "jpeg", "png"]:
9 | try:
10 | image = Image.open(sys.argv[1])
11 | except FileNotFoundError:
12 | sys.exit("Input does not exist")
13 | shirt = Image.open("shirt.png")
14 | size = shirt.size
15 | puppet = ImageOps.fit(image, size)
16 | puppet.paste(shirt, shirt)
17 | puppet.save(sys.argv[2])
18 | else:
19 | sys.exit("Invalid Output")
20 | else:
21 | sys.exit("Input and output have different extensions")
22 |
23 | elif len(sys.argv) <= 2:
24 | sys.exit("Too few command-line arguments")
25 | elif len(sys.argv) > 3:
26 | sys.exit("Too many command-line arguments")
27 |
--------------------------------------------------------------------------------
/tasks/shirt/yeni.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirt/yeni.jpg
--------------------------------------------------------------------------------
/tasks/shirtificate/shirtificate.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirtificate/shirtificate.pdf
--------------------------------------------------------------------------------
/tasks/shirtificate/shirtificate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sahinyes/CS50_Python/4eb9efa3b30bfcda8061e5fd3896e33bddc362cb/tasks/shirtificate/shirtificate.png
--------------------------------------------------------------------------------
/tasks/shirtificate/shirtificate.py:
--------------------------------------------------------------------------------
1 | from fpdf import FPDF
2 |
3 |
4 | class generate():
5 | def __init__(self, name):
6 |
7 | pdf = FPDF()
8 | pdf.add_page()
9 | pdf.set_font("helvetica", "B", 45)
10 | pdf.cell(0, 60, "CS50 Shirtificate", align="C")
11 | pdf.image("shirtificate.png", x=0, y=70)
12 | pdf.set_font_size(30)
13 | pdf.set_text_color(255,255,255)
14 | pdf.text(x=45, y=140, txt=f"{name} took CS50")
15 | pdf.output("shirtificate.pdf")
16 |
17 | name = input("Name: ")
18 | pdf = generate(name)
--------------------------------------------------------------------------------
/tasks/taqueria/taqueria.py:
--------------------------------------------------------------------------------
1 | def taqo():
2 | cash = 0
3 | menu = {
4 | "Baja Taco": 4.00,
5 | "Burrito": 7.50,
6 | "Bowl": 8.50,
7 | "Nachos": 11.00,
8 | "Quesadilla": 8.50,
9 | "Super Burrito": 8.50,
10 | "Super Quesadilla": 9.50,
11 | "Taco": 3.00,
12 | "Tortilla Salad": 8.00
13 | }
14 | while True:
15 | try:
16 | a = input("Item: ").title()
17 | if a in menu:
18 | cash += menu[a]
19 | print(f"Total: $",f"{cash:.2f}", sep="")
20 | except:
21 | return taqo
22 |
23 | taqo()
24 |
--------------------------------------------------------------------------------
/tasks/test_bank/bank.py:
--------------------------------------------------------------------------------
1 | def main():
2 | a = input("Greeting: ")
3 | print(value(a))
4 |
5 | def value(a):
6 | b = a.lower().strip()
7 |
8 | if not b.find("hello"):
9 | return 0
10 |
11 | elif b[0] == "h":
12 | return 20
13 |
14 | else:
15 | return 100
16 |
17 | if __name__ == "__main__":
18 | main()
19 |
--------------------------------------------------------------------------------
/tasks/test_bank/test_bank.py:
--------------------------------------------------------------------------------
1 | from bank import value
2 |
3 | def main():
4 | test_value()
5 | test_value_20()
6 | test_value_100()
7 |
8 | def test_value():
9 | assert value("hello") == 0
10 | assert value("hello Hi") == 0
11 | assert value("HeLLo") == 0
12 |
13 | def test_value_20():
14 | assert value("hi") == 20
15 | assert value("HoI") == 20
16 | assert value("Hi") == 20
17 |
18 | def test_value_100():
19 | assert value("What's up") == 100
20 | assert value("Good Morning") == 100
21 | assert value("Welcome!") == 100
22 |
23 |
24 | if __name__ == "__main__":
25 | main()
--------------------------------------------------------------------------------
/tasks/test_fuel/fuel.py:
--------------------------------------------------------------------------------
1 | def main():
2 | i = input("a: ")
3 | gauge(convert(i))
4 |
5 | def convert(fraction):
6 | while True:
7 | try:
8 | x = fraction.split("/")
9 | c = (int(x[0]) / int(x[1])) *100
10 | if int(x[0]) <= int(x[1]):
11 | return c
12 | else:
13 | continue
14 | except (ValueError, ZeroDivisionError):
15 | raise
16 |
17 | def gauge(percentage):
18 | if percentage >= 99:
19 | return "F"
20 | elif percentage <= 1:
21 | return "E"
22 | else:
23 | return str(percentage) + "%"
24 |
25 | if __name__ == "__main__":
26 | main()
--------------------------------------------------------------------------------
/tasks/test_fuel/test_fuel.py:
--------------------------------------------------------------------------------
1 | from fuel import convert, gauge
2 | import pytest
3 |
4 | def main():
5 | test_convert()
6 | test_gauge()
7 |
8 | def test_convert():
9 | assert convert("1/4") == 25
10 | assert convert("2/4") == 50
11 | assert convert("3/4") == 75
12 | assert convert("1/100") == 1
13 | assert convert("99/100") == 99
14 | with pytest.raises(ValueError):
15 | convert("one/zero")
16 | with pytest.raises(ZeroDivisionError):
17 | convert("1/0")
18 |
19 | def test_gauge():
20 | assert gauge(50) == "50%"
21 | assert gauge(1) == "E"
22 | assert gauge(100) == "F"
23 | assert gauge(99) == "F"
24 |
25 | if __name__ == "__main__":
26 | main()
--------------------------------------------------------------------------------
/tasks/test_plates/plates.py:
--------------------------------------------------------------------------------
1 | def main():
2 | plate = input("Plate: ")
3 | if is_valid(plate):
4 | print("Valid")
5 | return True
6 | else:
7 | print("Invalid")
8 | return False
9 |
10 | def is_valid(s):
11 | if len(s) <= 6 and len(s) >= 2 and s[0:2].isalpha() and s.isalnum():
12 | for i in s:
13 | if i.isdigit():
14 | result = s.index(i)
15 | if s[result:].isdigit() and int(i) != 0:
16 | return True
17 | else:
18 | return False
19 | return True
20 | else:
21 | return False
--------------------------------------------------------------------------------
/tasks/test_plates/test_plates.py:
--------------------------------------------------------------------------------
1 | from plates import is_valid
2 |
3 | def main():
4 | test_isvalid1()
5 | test_isvalid2()
6 | test_isvalid3()
7 |
8 |
9 | def test_isvalid1():
10 | assert is_valid("AA") == True
11 | assert is_valid("A1") == False
12 | assert is_valid("1A") == False
13 | assert is_valid("11") == False
14 | assert is_valid("a") == False
15 | assert is_valid("A") == False
16 |
17 | def test_isvalid2():
18 | assert is_valid("some word") == False
19 | assert is_valid("cs50") == True
20 | assert is_valid(".!") == False
21 | assert is_valid("cs50!") == False
22 | assert is_valid("cs 50") == False
23 | assert is_valid("cs05") == False
24 |
25 |
26 | def test_isvalid3():
27 | assert is_valid("ABCDEF") == True
28 | assert is_valid("ABCDEFABC") == False
29 | assert is_valid("AAA111") == True
30 | assert is_valid("111AAA") == False
31 | assert is_valid("AAA11A") == False
32 | assert is_valid("AAA11") == True
33 |
34 | if __name__ == "__main__":
35 | main()
--------------------------------------------------------------------------------
/tasks/test_twttr/test_twttr.py:
--------------------------------------------------------------------------------
1 | from twttr import shorten
2 |
3 | def main():
4 | test_twttr()
5 |
6 | def test_twttr():
7 | assert shorten("word") == "wrd"
8 | assert shorten("WORD") == "WRD"
9 | assert shorten("WorD") == "WrD"
10 | assert shorten("1234") == "1234"
11 | assert shorten(".!?,") == ".!?,"
12 |
13 | if __name__ == "__main__":
14 | main()
--------------------------------------------------------------------------------
/tasks/test_twttr/twttr.py:
--------------------------------------------------------------------------------
1 | def main():
2 | text = input("Input: ")
3 | shorten(text)
4 |
5 | def shorten(word):
6 | #text = input("Input: ")
7 | l = ["a", "A", "E", "e", "I", "i", "O", "o", "U", "u"]
8 | out = ""
9 |
10 | for i in word:
11 | if not i in l[:]:
12 | out += i
13 | return out
14 |
15 | if __name__ == "__main__":
16 | main()
--------------------------------------------------------------------------------
/tasks/tip/tip.py:
--------------------------------------------------------------------------------
1 | def main():
2 | dollars = dollars_to_float(input("How much was the meal? "))
3 | percent = percent_to_float(input("What percentage would you like to tip? "))
4 | tip = dollars * percent
5 | print(f"Leave ${tip:.2f}")
6 |
7 |
8 | def dollars_to_float(dollars):
9 | #TODO
10 | return float(dollars.strip("$"))
11 |
12 | def percent_to_float(percent):
13 | # TODO
14 | return float(percent.strip("%")) / 100
15 |
16 | main()
--------------------------------------------------------------------------------
/tasks/twttr/twttr.py:
--------------------------------------------------------------------------------
1 | text = input("Input: ")
2 | l = ["a", "A", "E", "e", "I", "i", "O", "o", "U", "u"]
3 | out = ""
4 |
5 | for i in text:
6 | if not i in l[:]:
7 | out += i
8 | print(out)
--------------------------------------------------------------------------------
/tasks/um/test_um.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from um import count
3 |
4 | def main():
5 | test1()
6 |
7 |
8 |
9 | def test1():
10 | assert count("um") == 1
11 | assert count("um?") == 1
12 | assert count("Um, thanks for the album") == 1
13 | assert count("Um, thanks, um...") == 2
--------------------------------------------------------------------------------
/tasks/um/um.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | def main():
4 | print(count(input("Text: ")))
5 |
6 | def count(s):
7 | text = re.findall(r"\b([U-u]m)\b", s)
8 | return len(text)
9 |
10 | if __name__ == "__main__":
11 | main()
--------------------------------------------------------------------------------
/tasks/watch/watch.py:
--------------------------------------------------------------------------------
1 | import re
2 | import sys
3 |
4 |
5 | def main():
6 | print(parse(input("HTML: ")))
7 |
8 |
9 | def parse(s):
10 | if result := re.search(r'.+src="https?://(?:www\.)?youtube\.com/embed/([a-z0-9A-Z]+)"',s):
11 | return "https://youtu.be/" + result.group(1)
12 |
13 |
14 | if __name__ == "__main__":
15 | main()
--------------------------------------------------------------------------------
/tasks/working/test_working.py:
--------------------------------------------------------------------------------
1 | from working import convert
2 | import pytest
3 |
4 | def main():
5 | test1()
6 | test2()
7 |
8 | def test1():
9 | assert convert("9 AM to 5 PM") == "09:00 to 17:00"
10 | assert convert("9:00 AM to 5:00 PM") == "09:00 to 17:00"
11 | assert convert("10 PM to 8 AM") == "22:00 to 08:00"
12 | assert convert("10:30 PM to 8:50 AM") == "22:30 to 08:50"
13 |
14 | def test2():
15 | with pytest.raises(ValueError):
16 | convert("9:60 AM to 5:60 PM")
17 | with pytest.raises(ValueError):
18 | convert("9:60 AM to 5:60 PM")
19 | with pytest.raises(ValueError):
20 | convert("9 AM - 5 PM")
21 | with pytest.raises(ValueError):
22 | convert("09:00 AM - 17:00 PM")
23 |
--------------------------------------------------------------------------------
/tasks/working/working.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def main():
5 | print(convert(input("Hours: ")))
6 |
7 | def convert(s):
8 |
9 | if hours := re.search(r"^([0-9][0-2]?):?([0-5][0-9])? (AM|PM)? to ([0-9][0-2]?):?([0-5][0-9])? (AM|PM)?$",s):
10 | if int(hours.group(1)) > 12 or int(hours.group(4)) > 12:
11 | raise ValueError
12 |
13 | first = create(int(hours.group(1)), hours.group(2), hours.group(3))
14 | second = create(int(hours.group(4)), hours.group(5), hours.group(6))
15 | return first + " to " + second
16 |
17 | else:
18 | raise ValueError
19 |
20 | def create(hour,minute,time):
21 | if time == "PM":
22 | if hour == 12:
23 | hour = 12
24 | else:
25 | hour += 12
26 | else:
27 | if hour == 12:
28 | hour = 0
29 |
30 | if minute == None:
31 | minute = ":00"
32 | result = f"{hour:02}{minute:02}"
33 |
34 | else:
35 | result = f"{hour:02}:{minute:02}"
36 |
37 | return result
38 |
39 | if __name__ == "__main__":
40 | main()
41 |
--------------------------------------------------------------------------------