diff --git a/lesson02/exercise2.py b/lesson02/exercise2.py index 6d7a91a..3f0f938 100644 --- a/lesson02/exercise2.py +++ b/lesson02/exercise2.py @@ -1,4 +1,5 @@ print(1+2*3) print(3/2*7) print(3**2*7/2) -print(3-2*7+2) \ No newline at end of file +print(3-2*7+2) +print(3-2*(7+2)) diff --git a/lesson02/string_concatenation3.py b/lesson02/string_concatenation3.py index bfc4981..803ab3c 100644 --- a/lesson02/string_concatenation3.py +++ b/lesson02/string_concatenation3.py @@ -1,3 +1,4 @@ name = "Alan" surname = "Turing" -print(name + " " + surname) +full_name = name + " " + surname +print(full_name) diff --git a/lesson03/exercise6.py b/lesson03/exercise6.py index 7d9f5e5..ebb5a86 100644 --- a/lesson03/exercise6.py +++ b/lesson03/exercise6.py @@ -1,15 +1,15 @@ -x = input("Dwse x: ") +x = int(input("Dwse x: ")) maximum = x -y = input("Dwse y: ") +y = int(input("Dwse y: ")) if y > maximum: maximum = y -z = input("Dwse z: ") +z = int(input("Dwse z: ")) if z > maximum: maximum = z -print(maximum) \ No newline at end of file +print(maximum) diff --git a/lesson06/exercise1.py b/lesson06/exercise1.py index 1e54831..f9f5f69 100644 --- a/lesson06/exercise1.py +++ b/lesson06/exercise1.py @@ -1,13 +1,19 @@ my_list = [] -for number in range(10): - user_input = int(input("Give " + str(number) + ": ")) +for i in range(10): + user_input = int(input("Give a number: ")) + while user_input < 10 or user_input > 20: + user_input = int(input("Give a number(10...20): ")) my_list.append(user_input) +print(my_list) + my_tuple = tuple(my_list) +print(my_tuple) list_squares = [] -for element in my_tuple: - list_squares.append(element ** 2) +for i in range(10): + list_squares.append(my_list[i]**2) +list_squares.sort() tuple_squares = tuple(list_squares) -print(tuple_squares) \ No newline at end of file +print(tuple_squares) diff --git a/lesson07/exercise2.py b/lesson07/exercise2.py index 0c2d257..662c6a6 100644 --- a/lesson07/exercise2.py +++ b/lesson07/exercise2.py @@ -4,7 +4,9 @@ seed(datetime.now()) # once, before randint call -for _ in range(10): +i = 0 +columns = [] +while True: column = set() # 10-19 @@ -29,15 +31,22 @@ column.add(rand_number) break - # 1 - 9 + # 1-9 EVEN - rand_number = randrange(1,10) + rand_number = 2 * randrange(1,5) column.add(rand_number) + # 41-49 ODD - # 40 - 49 - - rand_number = randrange(40,50) + rand_number = randrange(41,49+1,2) column.add(rand_number) - print(column) \ No newline at end of file + if column not in columns: + columns.append(column) + i += 1 + if i==10: + break + + +for column in columns: + print(column) diff --git a/lesson08/exercise05.py b/lesson08/exercise05.py index e730b96..1bdf669 100644 --- a/lesson08/exercise05.py +++ b/lesson08/exercise05.py @@ -7,6 +7,6 @@ rate = 2.2 -new_values = { key: value*rate for key, value in merchandise.items()} +new_values = { key: value*(1+rate) for key, value in merchandise.items()} print(new_values) diff --git a/lesson08/exercise09.04.py b/lesson08/exercise09.04.py index 3646346..b521de8 100644 --- a/lesson08/exercise09.04.py +++ b/lesson08/exercise09.04.py @@ -12,46 +12,50 @@ print("Round " + str(round)) # Eisodos xristi - player_input = int(input("Choose (0-rock, 1-scissors, 2-paper: ")) - while player_input not in [0,1,2]: + player_input_str = input("Choose: ") + while player_input_str not in ["rock", "scissors", "paper"]: print("Wrong input. Choices: rock, scissors, paper") - player_input = int(input("Choose (0-rock, 1-scissors, 2-paper: ")) + player_input_str = input("Choose: ") - # Epilogi ipologisti - computer_random = randrange(3) - if computer_random == 0: - computer_choice = "rock" - elif computer_random == 1: - computer_choice = "scissors" + if player_input_str == "rock": + player_input_int = 0 + elif player_input_str == "scissors": + player_input_int = 1 else: - computer_choice = "paper" + player_input_int = 2 + # Epilogi ipologisti + computer_choice_int = randrange(3) + if computer_choice_int == 0: + computer_choice_str = "rock" + elif computer_choice_int == 1: + computer_choice_str = "scissors" + else: + computer_choice_str = "paper" # Elegxos toy poios nikise - - diff = player_input - computer_choice + diff = player_input_int - computer_choice_int if diff == -1 or diff == 2: winner = "player" - elif diff == 1 or diff == -2: + elif diff == -2 or diff == 1: winner = "computer" else: winner = "no winner" - # Diorthosi tou skor + if winner == "player": score[0] += 1 elif winner == "computer": score[1] += 1 - # enimerwsi tou istorikou - history.append("Round " + str(round) + ": Player: " + player_input + ", Computer: " + computer_choice + ", Score: " + str(score[0]) + "-" + str(score[1])) - + history.append("Round " + str(round) + ": Player: " + player_input_str + ", Computer: " + computer_choice_str + ", Score: " + str(score[0]) + "-" + str(score[1])) # Ektypwsi toy nikiti kai tou skor - print("Computer picks: " + computer_choice) + + print("Computer picks: " + computer_choice_str) print("Player-Computer: " + str(score[0]) + "-" + str(score[1])) if score[0] == 3: @@ -67,4 +71,4 @@ print(history_item) break - print("====================\n") \ No newline at end of file + print("====================\n") diff --git a/lesson09/string.escape.characters.py b/lesson09/string.escape.characters.py index d07afb3..a9b5a69 100644 --- a/lesson09/string.escape.characters.py +++ b/lesson09/string.escape.characters.py @@ -3,5 +3,3 @@ print("tabs:\n\t|\t|a\t|aa\t|aaa\t|") print("change line: \n newline \r CR") print("Backspace: bb\baa\bc\b\baa\b") - -ba \ No newline at end of file diff --git a/lesson11/exercise05.py b/lesson11/exercise05.py index 46e56a6..dd0e585 100644 --- a/lesson11/exercise05.py +++ b/lesson11/exercise05.py @@ -9,7 +9,7 @@ def is_even(number): def is_prime(number): if number == 0 or number == 1: return False - for i in range(2, int(number / 2)): + for i in range(2, int(number / 2) + 1): if number % i == 0: return False return True diff --git a/lesson11/exercise06.py b/lesson11/exercise06.py index a31efa0..901a059 100644 --- a/lesson11/exercise06.py +++ b/lesson11/exercise06.py @@ -1,16 +1,15 @@ PI = 3.14159265359 - def triangle_area(base, height): - return (base * height)/2 + return base*height/2 def square_perimeter(edge): - return 4*a + return 4*edge def square_area(edge): - return a ** 2 + return edge ** 2 def circle_perimeter(radius): @@ -18,7 +17,7 @@ def circle_perimeter(radius): def circle_area(radius): - return PI*(radius ** 2) + return PI * radius ** 2 -print(circle_area(3)) \ No newline at end of file +print(circle_area(1)) diff --git a/lesson11/local2.py b/lesson11/local2.py new file mode 100644 index 0000000..667adc5 --- /dev/null +++ b/lesson11/local2.py @@ -0,0 +1,7 @@ +#local2.py +def f(): + x = 5 + + +f() +print(x) diff --git a/lesson11/mutable.arguments.assignment.py b/lesson11/mutable.arguments.assignment.py index 457a0ea..6499e09 100644 --- a/lesson11/mutable.arguments.assignment.py +++ b/lesson11/mutable.arguments.assignment.py @@ -1,3 +1,4 @@ +# mutable.arguments.assignment.py def f(arg): print(arg) arg = [3] @@ -6,4 +7,4 @@ def f(arg): l = [1,2] print(l) f(l) -print(l) \ No newline at end of file +print(l) diff --git a/lesson16/private.py b/lesson16/private.py index 1357f03..e14c95e 100644 --- a/lesson16/private.py +++ b/lesson16/private.py @@ -1,4 +1,4 @@ -# public.py +# private.py class Cow: def __init__(self, weight, hunger): self.weight = weight @@ -14,4 +14,4 @@ def express(self): molly = Cow(100, 5) print(molly.__hunger) print(molly.weight) -molly.express() \ No newline at end of file +molly.express() diff --git a/lesson17/binary.py b/lesson17/binary.py index 966027e..ff1b2ca 100644 --- a/lesson17/binary.py +++ b/lesson17/binary.py @@ -44,8 +44,8 @@ def __add__(self, other): if isinstance(other, Time): carry = (self.second + other.second) // 60 new_second = (self.second + other.second) % 60 - carry = (self.minute + other.minute + carry) // 60 new_minute = (self.minute + other.minute + carry) % 60 + carry = (self.minute + other.minute + carry) // 60 new_hour = (self.hour + other.hour + carry) % 24 return Time(new_hour, new_minute, new_second) elif isinstance(other, int): diff --git a/lesson17/del.py b/lesson17/del.py new file mode 100644 index 0000000..a5c2413 --- /dev/null +++ b/lesson17/del.py @@ -0,0 +1,21 @@ +class A: + def __init__(self, n): + self.name = n + def __del__(self): + print(self.name + " destroyed") + del self + + +def f(): + t = A("t") + +f() + +x = A("x") +del x +y = A("y") +z = y +print(z, y) +ar = [y, 2] +del y +print(ar,ar[0]) \ No newline at end of file diff --git a/lesson17/exercise04.initial.py b/lesson17/exercise04.initial.py new file mode 100644 index 0000000..a554b7b --- /dev/null +++ b/lesson17/exercise04.initial.py @@ -0,0 +1,9 @@ +a = Point3D(1,1,1) +b = Point3D(2,2,2) +print(a+b) +c = a + b +print(c) +a = a + b +print(a) +a += b +print(a) \ No newline at end of file diff --git a/lesson17/exercise04.py b/lesson17/exercise04.py new file mode 100644 index 0000000..d5d3beb --- /dev/null +++ b/lesson17/exercise04.py @@ -0,0 +1,32 @@ +class Point3D: + def __init__(self,x=0,y=0,z=0): + self.x = x + self.y = y + self.z = z + + def __str__(self): + return f"({self.x},{self.y},{self.z})" + + def __add__(self, other): + new_point = Point3D() + new_point.x = self.x + other.x + new_point.y = self.y + other.y + new_point.z = self.z + other.z + return new_point + + def __iadd__(self, other): + self.x += other.x + self.y += other.y + self.z += other.z + return self + +a = Point3D(1,1,1) +b = Point3D(2,2,2) +print(a+b) +c = a + b +print(c) +print(a, id(a)) +a = a + b +print(a, id(a)) +a += b +print(a, id(a)) \ No newline at end of file diff --git a/lesson17/exercise05.py b/lesson17/exercise05.py new file mode 100644 index 0000000..096a1e3 --- /dev/null +++ b/lesson17/exercise05.py @@ -0,0 +1,58 @@ +class Byte: + def __init__(self, s = ""): + if s == "": + self.array = [0 for i in range(8)] + else: + self.array = [int(c) for c in s] + + def __str__(self): + st = [str(c) for c in self.array] + return "".join(st) + + def __lshift__(self, other): + for i in range(other): + self.array.pop(0) + self.array.append(0) + + def __rshift__(self, other): + for i in range(other): + self.array.pop() + self.array.insert(0,0) + + def __and__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] & other.array[i] + return new_byte + + def __or__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] | other.array[i] + return new_byte + + def __xor__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] ^ other.array[i] + return new_byte + + def __invert__(self): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = 1 if self.array[i]==0 else 0 + return new_byte + +b = Byte() +b2 = Byte("00010011") +print(b, b2) + +b2 >> 2 +print(b2) + +b2 = Byte("00010011") +b3 = Byte("00110101") +print(f"\n{b2}\n{b3}(&)\n{'-'*8}\n{b2&b3}") +print(f"\n{b2}\n{b3}(|)\n{'-'*8}\n{b2|b3}") +print(f"\n{b2}\n{b3}(^)\n{'-'*8}\n{b2^b3}") +print(f"\n{b3}(~)\n{'-'*8}\n{~b3}") \ No newline at end of file diff --git a/lesson17/exercise06.py b/lesson17/exercise06.py new file mode 100644 index 0000000..04f80b0 --- /dev/null +++ b/lesson17/exercise06.py @@ -0,0 +1,23 @@ +class Counter: + def __init__(self): + self.counter = 0 + + def __str__(self): + return str(self.counter) + + def __pos__(self): + self.counter += 1 + + def __neg__(self): + self.counter -= 1 + +c = Counter() + ++c ++c ++c +print(c) + +-c +-c +print(c) \ No newline at end of file diff --git a/lesson17/exercise07.py b/lesson17/exercise07.py new file mode 100644 index 0000000..dbe2848 --- /dev/null +++ b/lesson17/exercise07.py @@ -0,0 +1,30 @@ +class Length: + def __init__(self, val, m): + if m == "m": + self.val = val + elif m == "cm": + self.val = val / 100 + elif m == "in": + self.val = val * 0.0254 + else: + self.val = 0 + + def __str__(self): + return f"{self.val}m" + + def __add__(self, other): + return Length(self.val + other.val, "m") + + def __round__(self, n=None): + return round(self.val, n) + + def __int__(self): + return int(self.val) + +l1 = Length(1,"m") +l2 = Length(50, "cm") +l3 = Length(100, "in") + +print(l1 + l2) +print(round(l2 + l3 + l3 + l1,1)) +print(l3, int(l3)) diff --git a/lesson17/exercise08.py b/lesson17/exercise08.py new file mode 100644 index 0000000..0a166ad --- /dev/null +++ b/lesson17/exercise08.py @@ -0,0 +1,73 @@ +class Byte: + def __init__(self, s = ""): + if s == "": + self.array = [0 for i in range(8)] + else: + self.array = [int(c) for c in s] + + def __str__(self): + st = [str(c) for c in self.array] + return "".join(st) + + def __lshift__(self, other): + for i in range(other): + self.array.pop(0) + self.array.append(0) + + def __rshift__(self, other): + for i in range(other): + self.array.pop() + self.array.insert(0,0) + + def __and__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] & other.array[i] + return new_byte + + def __or__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] | other.array[i] + return new_byte + + def __xor__(self, other): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = self.array[i] ^ other.array[i] + return new_byte + + def __invert__(self): + new_byte = Byte("") + for i in range(8): + new_byte.array[i] = 1 if self.array[i]==0 else 0 + return new_byte + + def __len__(self): + return 8 + + def __getitem__(self, item): + return self.array[item] + + def __setitem__(self, key, value): + self.array[key] = value + +b = Byte() +b2 = Byte("00010011") +print(b, b2) + +b2 >> 2 +print(b2) + +b2 = Byte("00010011") +b3 = Byte("00110101") +print(f"\n{b2}\n{b3}(&)\n{'-'*8}\n{b2&b3}") +print(f"\n{b2}\n{b3}(|)\n{'-'*8}\n{b2|b3}") +print(f"\n{b2}\n{b3}(^)\n{'-'*8}\n{b2^b3}") +print(f"\n{b3}(~)\n{'-'*8}\n{~b3}") + +for bit in b3: + print(bit) + +b3[0] = 1 +print(b3) \ No newline at end of file diff --git a/lesson17/exercise09.py b/lesson17/exercise09.py new file mode 100644 index 0000000..71b044f --- /dev/null +++ b/lesson17/exercise09.py @@ -0,0 +1,51 @@ +class Point3D: + def __init__(self,x=0,y=0,z=0): + self.x = x + self.y = y + self.z = z + + def __str__(self): + return f"({self.x},{self.y},{self.z})" + + def __add__(self, other): + new_point = Point3D() + new_point.x = self.x + other.x + new_point.y = self.y + other.y + new_point.z = self.z + other.z + return new_point + + def __iadd__(self, other): + self.x += other.x + self.y += other.y + self.z += other.z + return self + + def __getitem__(self, item): + if item == 0: + return self.x + elif item == 1: + return self.y + elif item == 2: + return self.z + return None + + def __setitem__(self, key, value): + if key == 0: + self.x = value + elif key == 1: + self.y = value + elif key == 2: + self.z = value + +a = Point3D(1,1,1) +b = Point3D(2,2,2) +print(a+b) +c = a + b +print(c) +print(a, id(a)) +a = a + b +print(a, id(a)) +a += b +print(a, id(a)) +a[0]=7 +print(a) \ No newline at end of file diff --git a/lesson17/exercise10.py b/lesson17/exercise10.py new file mode 100644 index 0000000..5d0d5af --- /dev/null +++ b/lesson17/exercise10.py @@ -0,0 +1,40 @@ +from math import sqrt + +class Cycle: + def __init__(self, c): + self.c = c + + def __str__(self): + return f"x^2+y^2={c}^2" + + def __eq__(self, other): + return self.c == other.c + + def __lt__(self, other): + return self.c < other.c + + def __call__(self, x, y=None): + if y is None: + if isinstance(x, (int,float)): + if abs(x) < self.c: + return (x,sqrt(self.c**2-x**2)), (x,-sqrt(self.c**2-x**2)) + elif abs(x) == self.c: + return (x, 0) + else: + return None + else: + if isinstance(x, (int, float)): + if x**2+y**2 other.hour: + return True + elif self.hour == other.hour: + if self.minute > other.minute: + return True + elif self.minute == other.minute: + if self.second > other.second: + return True + return False + + def __ge__(self, other): + if self.hour > other.hour: + return True + elif self.hour == other.hour: + if self.minute > other.minute: + return True + elif self.minute == other.minute: + if self.second >= other.second: + return True + return False + + def __eq__(self, other): + if isinstance(other, Time): + if self.hour == other.hour and self.minute == other.minute and self.second == other.second: + return True + return False + elif isinstance(other, int): + return self == Time(other, 0, 0) + + +class Date: + def __init__(self, day, month, year): + self.day = day + self.month = month + self.year = year + + def __str__(self): + return f"{self.day}/{self.month}/{self.year}" + + def __repr__(self): + return f"Date({self.day},{self.month},{self.year})" + + def __eq__(self, other): + return self.day == other.day and self.month == other.month and self.year == other.year + +class DateTime: + def __init__(self, date, time): + self.date = date + self.time = time + + def __str__(self): + return str(self.date) + " " + str(self.time) + + def __repr__(self): + return f"DateTime({repr(self.date)},{repr(self.time)})" + + +d = Date(11,1,2020) +print(d, repr(d)) + +t = Time(11,1,1) + +dt = DateTime(d,t) +print(dt, repr(dt)) \ No newline at end of file diff --git a/lesson17/exercise12.py b/lesson17/exercise12.py new file mode 100644 index 0000000..c060730 --- /dev/null +++ b/lesson17/exercise12.py @@ -0,0 +1,51 @@ +from queue import Queue +from random import randrange, seed +from datetime import datetime + +class Bank: + def __init__(self, N): + self.N = N + self.cash_desks = [Queue() for i in range(N)] + + def customer_enters(self, full_name): + cash_desk = randrange(self.N) + self.cash_desks[cash_desk] += full_name + print(full_name + " entered! To be served by cash desk: " + str(cash_desk)) + + def customer_served(self): + not_empty_cash_desks = [i for i in range(self.N) if len(self.cash_desks[i]) > 0] + + if len(not_empty_cash_desks) > 0: + cash_desk = not_empty_cash_desks[randrange(len(not_empty_cash_desks))] + customer = - self.cash_desks[cash_desk] + print(f"{customer} served by cash desk {cash_desk}") + else: + print("No customers.") + + def __str__(self): + st = "\n" + "=" * 20 + for i in range(self.N): + st += "\nCash Desk " + str(i) +": " + st += str(self.cash_desks[i]) + st += "\n" + "=" * 20 + return st + + +def main(): + seed(datetime.now()) + + bank = Bank(3) + + for i in range(100): + num = randrange(100) + if num <=29: + bank.customer_served() + else: + bank.customer_enters("Cust" + str(randrange(1000))) + + if i % 10 == 0: + print(bank) + + print("BANK CLOSED") + +main() \ No newline at end of file diff --git a/lesson17/function.py b/lesson17/function.py new file mode 100644 index 0000000..de0febc --- /dev/null +++ b/lesson17/function.py @@ -0,0 +1,24 @@ +class Polynomial: + def __init__(self, *coeff): + self.coeff = [c for c in coeff] + print(self.coeff) + + def __str__(self): + st = [] + for i in range(len(self.coeff)): + st.append(f"{self.coeff[i]}*x^{len(self.coeff)-i-1}") + return " + ".join(st) + + def __call__(self, x): + res = 0 + for i in range(len(self.coeff)): + res += self.coeff[i] * x ** (len(self.coeff)-i-1) + return res + + +p = Polynomial(5,1,2) +print(str(p)) +print(p(2)) + +p2 = Polynomial(4,5,4,1,2,3) +print(p2) \ No newline at end of file diff --git a/lesson17/iterate.py b/lesson17/iterate.py new file mode 100644 index 0000000..1d88569 --- /dev/null +++ b/lesson17/iterate.py @@ -0,0 +1,13 @@ +class X: + def __init__(self): + self.ar = [x for x in range(5)] + + def __len__(self): + return len(self.ar) + + def __getitem__(self, item): + return self.ar[item] + +obj = X() +for item in obj: + print(item) \ No newline at end of file diff --git a/lesson17/lesson17.exercise13/arena.py b/lesson17/lesson17.exercise13/arena.py new file mode 100644 index 0000000..0201c49 --- /dev/null +++ b/lesson17/lesson17.exercise13/arena.py @@ -0,0 +1,85 @@ +from character import Character +from random import randrange + +class Arena: + def __init__(self, team_A, team_B): + self.team_A = team_A + self.team_B = team_B + + def __str__(self): + st = "\n" + "-" * 15 + st += "\nTEAM A" + for character in self.team_A: + st += "\n" + str(character) + st += "\n" + ("-" * 15) + for character in self.team_B: + st += "\n" + str(character) + st += "\n" + ("-" * 15) + return st + + def __repr__(self): + st = f"Arena([" + st += ", ".join([repr(character) for character in self.team_A]) + st += "],[" + st += ", ".join([repr(character) for character in self.team_B]) + st += "])" + return st + + + def play(self): + time = -1 + while True: + time += 1 + print("=" * 20) + print("Time = " + str(time)) + print("=" * 20) + print(self) + + # create list of characters to play + chars_to_play = [] + for character in self.team_A: + if character.delay == 0: + chars_to_play.append(('A', character)) + for character in self.team_B: + if character.delay == 0: + chars_to_play.append(('B', character)) + + # active characters attack + + for character in chars_to_play: + attacking = character[1] + if character[0] == 'A': + defending = self.team_B[randrange(len(self.team_B))] + else: + defending = self.team_A[randrange(len(self.team_A))] + + damage = attacking.attack() + defending.health -= damage + print(f"{attacking.character_name} dealt {damage} to {defending.character_name}") + + # check for dead characters + + for pos in range(len(self.team_A)-1,-1,-1): + if self.team_A[pos].is_dead(): + print(f"{self.team_A[pos].character_name} is dead!") + self.team_A.pop(pos) + for pos in range(len(self.team_B)-1,-1,-1): + if self.team_B[pos].is_dead(): + print(f"{self.team_B[pos].character_name} is dead!") + self.team_B.pop(pos) + + # check if game ended + if len(self.team_A) == 0: + print("Team B won!") + break + elif len(self.team_B) == 0: + print("Team A won!") + break + + # end round! + for character in self.team_A: + character.end_round() + for character in self.team_B: + character.end_round() + + input("Press Enter to Continue") \ No newline at end of file diff --git a/lesson17/lesson17.exercise13/character.py b/lesson17/lesson17.exercise13/character.py new file mode 100644 index 0000000..213e81e --- /dev/null +++ b/lesson17/lesson17.exercise13/character.py @@ -0,0 +1,36 @@ +from random import randrange + + +class Character: + def __init__(self, character_name, equipment, attack_speed=2, delay=0): + self.character_name = character_name + self.equipment = equipment + self.max_health = 100 * self.equipment.cape + self.health = 100 * self.equipment.cape + self.attack_speed = attack_speed + self.delay = delay + + def attack(self): + self.delay = 5 - self.attack_speed + return round(randrange(3, 11) * self.equipment.sword) + + def is_dead(self): + return self.health <= 0 + + def end_round(self): + self.health = self.health+1 if self.health+1<=self.max_health else self.max_health + self.delay -= 1 + + def __str__(self): + return f"{self.character_name} H:{round(self.health)} D:{self.delay}" + + def __repr__(self): + return f"Character({self.character_name},{self.attack_speed}, {self.delay}, {round(self.max_health)}, {round(self.health)})" + + def __iadd__(self, other): + self.health += other + return self + + def __isub__(self, other): + self.health -= other + return self diff --git a/lesson17/lesson17.exercise13/equipment.py b/lesson17/lesson17.exercise13/equipment.py new file mode 100644 index 0000000..4f85f40 --- /dev/null +++ b/lesson17/lesson17.exercise13/equipment.py @@ -0,0 +1,5 @@ +class Equipment: + def __init__(self, sword, cape): + self.sword = sword + self.cape = cape + diff --git a/lesson17/lesson17.exercise13/main.py b/lesson17/lesson17.exercise13/main.py new file mode 100644 index 0000000..cd9f1ec --- /dev/null +++ b/lesson17/lesson17.exercise13/main.py @@ -0,0 +1,18 @@ +from character import Character +from arena import Arena +from equipment import Equipment +from random import randrange, seed, uniform +from datetime import datetime + + +def main(): + seed(datetime.now()) + + orcs = [Character("Orc-" + str(i+1),Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 2,randrange(4)) for i in range(5)] + night_elves = [Character("Night-Elf-" + str(i + 1),Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 3, randrange(3)) for i in range(3)] + + a = Arena(orcs, night_elves) + a.play() + + +main() \ No newline at end of file diff --git a/lesson17/lesson17.exercise14/exercise14.py b/lesson17/lesson17.exercise14/exercise14.py new file mode 100644 index 0000000..6c29ed6 --- /dev/null +++ b/lesson17/lesson17.exercise14/exercise14.py @@ -0,0 +1,161 @@ +from teachers import Teachers +from pupils import Pupils + + +def main(): + + pupils = Pupils() + teachers = Teachers() + + while True: + print("\n===============") + print(" MENU ") + print("1 - Create Pupil") + print("2 - Print") + print("3 - Update Pupil") + print("4 - Delete Pupil") + print("5 - Create Teacher") + print("6 - Read Teacher") + print("7 - Update Teacher") + print("8 - Delete Teacher") + print("9 - Exit") + choice = int(input("Pick one: ")) + + if choice == 1: + print("NEW PUPIL") + print("===========") + pupil = pupils.create_pupil() + if pupil is None: + continue + else: + print("NEW PUPIL") + print(pupil) + + elif choice == 2: + print("\n===============") + print(" SUB-MENU (PRINT) ") + print("1 - Print Pupil") + print("2 - Print all pupils (details)") + print("3 - Print all pupils (just the names)") + print_choice = input("Give your choice: ") + if print_choice.strip().isdigit(): + print_choice = int(print_choice) + else: + print("Wrong input!") + continue + + if print_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Pupil does not exist (with this id)") + else: + print(" PUPIL ") + print(pupil) + + elif print_choice == 2: + print(pupils) + elif print_choice == 3: + pupils.print_pupils_names() + else: + print("Wrong input! ") + continue + + elif choice == 3: + print("\n===============") + print(" SUB-MENU (UPDATE) ") + print("1 - Update Pupil (search by id)") + print("2 - Update Pupil (search by surname)") + update_choice = input("Give your choice: ") + if update_choice.strip().isdigit(): + update_choice = int(update_choice) + else: + print("Wrong input!") + continue + + if update_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif update_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: update + pupils.pupil_update(pupil) + + elif choice == 4: + print("\n===============") + print(" SUB-MENU (DELETE) ") + print("1 - Delete Pupil (search by id)") + print("2 - Delete Pupil (search by surname)") + delete_choice = input("Give your choice: ") + if delete_choice.strip().isdigit(): + delete_choice = int(delete_choice) + else: + print("Wrong input!") + continue + + if delete_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif delete_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: delete + pupils.delete_pupil_by_id(pupil.pupil_id) + elif choice==5: + first_name = input("Give name: ") + surname = input("Give surname: ") + teachers.create_teacher(first_name, surname) + elif choice==6: + teacher_id = int(input("Give id: ")) + teacher = teachers.read_teacher(teacher_id) + if teacher is None: + print("No such teacher exists!") + else: + print(teacher) + elif choice==7: + teacher_id = int(input("Give id: ")) + teachers.update_teacher(teacher_id) + elif choice==8: + teacher_id = int(input("Give id: ")) + teachers.delete_teacher(teacher_id) + elif choice==9: + print("Bye bye!") + pupils.save_pupils_data() + teachers.save_teachers_data() + break + + +main() \ No newline at end of file diff --git a/lesson17/lesson17.exercise14/pupil.py b/lesson17/lesson17.exercise14/pupil.py new file mode 100644 index 0000000..ecde02f --- /dev/null +++ b/lesson17/lesson17.exercise14/pupil.py @@ -0,0 +1,42 @@ +class Pupil: + def __init__(self, first_name="", last_name="", fathers_name="", + age=-1, class_name="", id_number=None, pupil_id=-1): + self.first_name = first_name + self.last_name = last_name + self.fathers_name = fathers_name + self.age = age + self.class_name = class_name + self.id_number = id_number + self.pupil_id = pupil_id + + def from_dict(self, pupil_dict): + self.first_name = pupil_dict["first_name"] + self.last_name = pupil_dict["last_name"] + self.fathers_name = pupil_dict["fathers_name"] + self.age = pupil_dict["age"] + self.class_name = pupil_dict["class_name"] + if "id_number" in pupil_dict: + self.id_number = pupil_dict["id_number"] + self.pupil_id = pupil_dict["pupil_id"] + + def to_dict(self): + pupil_dict = {"first_name": self.first_name, + "last_name": self.last_name, + "fathers_name": self.fathers_name, + "age": self.age, + "class_name": self.class_name, + "pupil_id": self.pupil_id} + if self.id_number is not None: + pupil_dict["id_number"] = self.id_number + return pupil_dict + + def __str__(self): + + st = f"\nName : {self.first_name}" + st += f"\nLast Name : {self.last_name}" + st += f"\nFather's Name : {self.fathers_name}" + st += f"\nAge : {self.age}" + st += f"\nClass : {self.class_name}" + if self.id_number is not None: + st += f"\nID card number: {self.id_number}" + return st diff --git a/lesson17/lesson17.exercise14/pupils.json b/lesson17/lesson17.exercise14/pupils.json new file mode 100644 index 0000000..d8ffad4 --- /dev/null +++ b/lesson17/lesson17.exercise14/pupils.json @@ -0,0 +1 @@ +[{"first_name": "John", "last_name": "Cm", "fathers_name": "Wick", "age": 44, "class_name": 1, "pupil_id": 1001, "id_number": "12131234"}, {"first_name": "Bob", "last_name": "Hope", "fathers_name": "Charles", "age": 12, "class_name": 2, "pupil_id": 1002}, {"first_name": "1", "last_name": "1", "fathers_name": "1", "age": 1, "class_name": 1, "pupil_id": 1003}] \ No newline at end of file diff --git a/lesson17/lesson17.exercise14/pupils.py b/lesson17/lesson17.exercise14/pupils.py new file mode 100644 index 0000000..19aeef0 --- /dev/null +++ b/lesson17/lesson17.exercise14/pupils.py @@ -0,0 +1,121 @@ +from pupil import Pupil +import json + + +class Pupils: + def __init__(self): + try: + with open("pupils.json") as f: + pupils_list = json.load(f) + + self.pupils = [] + for pupil_dict in pupils_list: + p = Pupil() + p.from_dict(pupil_dict) + self.pupils += [p] + except FileNotFoundError: + self.pupils = [] + + def __str__(self): + st = "" + for pupil in self.pupils: + st += "\n" + "=" * 15 + st += str(pupil) + return st + + def save_pupils_data(self): + list_to_write = [] + for pupil in self.pupils: + list_to_write += [pupil.to_dict()] + + with open("pupils.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.pupils: + return 1001 + else: + ids = [] + for p in self.pupils: + ids.append(p.pupil_id) + return max(ids) + 1 + + def create_pupil(self): + first_name = input("Give name: ") + last_name = input("Give surname: ") + fathers_name = input("Give father's name: ") + + for p in self.pupils: + if first_name == p.first_name and last_name == p.last_name and fathers_name == p.fathers_name: + print("This pupil already exists.") + ch = input("Do you want to continue? (y-yes, n-no): ") + if ch == "n": + return None + + age = int(input("Give age: ")) + class_name = int(input("Give class: ")) + id_card = input("Does he/she has an id card: (y-true, n-false): ") + if id_card == "y": + id_number = input("Give id card number: ") + else: + id_number = None + + pupil = Pupil(first_name,last_name,fathers_name,age,class_name,id_number,self.next_id()) + + self.pupils.append(pupil) + return pupil + + def search_pupil_by_id(self, pupil_id): + for pupil in self.pupils: + if pupil_id == pupil.pupil_id: + return pupil + return None + + def search_pupil_by_surname(self, last_name): + match_pupils = [] + for pupil in self.pupils: + if last_name == pupil.last_name: + match_pupils.append(pupil) + return match_pupils + + def pupil_update(self, pupil): + print(pupil) + print("=" * 15) + print("1-name") + print("2-surname") + print("3-father's name") + print("4-age") + print("5-class") + print("6-id number") + print("=" * 15) + update_choice = int(input("Pick something to update: ")) + if update_choice == 1: + pupil.first_name = input("Give new name: ") + elif update_choice == 2: + pupil.last_name = input("Give new surname: ") + elif update_choice == 3: + pupil.fathers_name = input("Give new father's name: ") + elif update_choice == 4: + pupil.age = input("Give new age: ") + elif update_choice == 5: + pupil.class_name = input("Give new class: ") + elif update_choice == 6: + pupil.id_number = input("Give new id number: ") + + print("=" * 15) + print(pupil) + print("Pupil updated! ") + + def delete_pupil_by_id(self, pupil_id): + for i in range(len(self.pupils)): + if pupil_id == self.pupils[i].pupil_id: + self.pupils.pop(i) + print("Pupil deleted!") + return + else: + print("No teacher with this id!") + + def print_pupils_names(self): + for pupil in self.pupils: + print(f"{pupil.first_name} {pupil.fathers_name[0]}. {pupil.last_name}") + diff --git a/lesson17/lesson17.exercise14/teacher.py b/lesson17/lesson17.exercise14/teacher.py new file mode 100644 index 0000000..bfdfb5e --- /dev/null +++ b/lesson17/lesson17.exercise14/teacher.py @@ -0,0 +1,22 @@ +class Teacher: + def __init__(self, first_name="", surname="", teacher_id=-1): + self.first_name = first_name + self.surname = surname + self.teacher_id = teacher_id + + def from_dict(self, teacher_dict): + self.first_name = teacher_dict["first_name"] + self.surname = teacher_dict["surname"] + self.teacher_id = teacher_dict["teacher_id"] + + def to_dict(self): + teacher_dict = {"first_name": self.first_name, + "surname": self.surname, + "teacher_id":self.teacher_id} + return teacher_dict + + def __str__(self): + st = f"Name : {self.first_name}" + st += f"\nSurname: {self.surname}" + st += f"\nid : {self.teacher_id}" + return st diff --git a/lesson17/lesson17.exercise14/teachers.json b/lesson17/lesson17.exercise14/teachers.json new file mode 100644 index 0000000..fd7e825 --- /dev/null +++ b/lesson17/lesson17.exercise14/teachers.json @@ -0,0 +1 @@ +[{"first_name": "Severus", "surname": "Snape", "teacher_id": 1001}, {"first_name": "Charles", "surname": "Xavier", "teacher_id": 1002}, {"first_name": "Sergio", "surname": "Marquina", "teacher_id": 1003}] \ No newline at end of file diff --git a/lesson17/lesson17.exercise14/teachers.py b/lesson17/lesson17.exercise14/teachers.py new file mode 100644 index 0000000..0fb4cca --- /dev/null +++ b/lesson17/lesson17.exercise14/teachers.py @@ -0,0 +1,72 @@ +import json +from teacher import Teacher + + +class Teachers: + def __init__(self): + try: + with open("teachers.json") as f: + teachers_list = json.load(f) + + self.teachers = [] + for teacher_dict in teachers_list: + t = Teacher() + t.from_dict(teacher_dict) + self.teachers += [t] + except FileNotFoundError: + self.teachers = [] + + def save_teachers_data(self): + list_to_write = [] + for teacher in self.teachers: + list_to_write += [teacher.to_dict()] + + with open("teachers.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.teachers: + return 1001 + else: + ids = [] + for t in self.teachers: + ids.append(t.teacher_id) + return max(ids) + 1 + + def create_teacher(self,first_name, surname): + for teacher in self.teachers: + if teacher.first_name == first_name and teacher.surname == surname: + print("Error. Teacher already exists! ") + return None + + t = Teacher(first_name, surname, self.next_id()) + self.teachers.append(t) + return t + + def read_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + return teacher + else: + return None + + def update_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + print(teacher) + choice = int(input("Update 1-name, 2-surname: ")) + if choice == 1: + teacher.first_name = input("Give new name: ") + elif choice == 2: + teacher.surname = input("Give new surname: ") + return + + def delete_teacher(self, teacher_id): + for i in range(len(self.teachers)): + if teacher_id == self.teachers[i].teacher_id: + self.teachers.pop(i) + return + else: + print("No teacher with this id!") + + diff --git a/lesson17/new.py b/lesson17/new.py new file mode 100644 index 0000000..38c637c --- /dev/null +++ b/lesson17/new.py @@ -0,0 +1,8 @@ +class A: + def __new__(cls): + print("A.__new__ called") + return super(A, cls).__new__(cls) + def __init__(self): + print("A.__init__ called") + +A() diff --git a/lesson17/python17.oop.methods.pdf b/lesson17/python17.oop.methods.pdf new file mode 100644 index 0000000..7b0d7b7 Binary files /dev/null and b/lesson17/python17.oop.methods.pdf differ diff --git a/lesson17/queue.py b/lesson17/queue.py new file mode 100644 index 0000000..079b6c3 --- /dev/null +++ b/lesson17/queue.py @@ -0,0 +1,31 @@ +class Queue: + def __init__(self): + self.array = [] + + def enqueue(self, elem): + self.array.append(elem) + + def dequeue(self): + if not self.array: + return None + else: + return self.array.pop(0) + + def __str__(self): + return ", ".join(self.array) + + def __add__(self, other): + new_q = Queue() + new_q.array = self.array[:] + new_q.enqueue(other) + return new_q + + def __iadd__(self, other): + self.enqueue(other) + return self + + def __neg__(self): + return self.dequeue() + + def __len__(self): + return len(self.array) \ No newline at end of file diff --git a/lesson17/repr.py b/lesson17/repr.py new file mode 100644 index 0000000..eea57c2 --- /dev/null +++ b/lesson17/repr.py @@ -0,0 +1,49 @@ +class Time: + def __init__(self, hour, minute, second): + self.hour = hour + self.minute = minute + self.second = second + + def __str__(self): + return f"{str(self.hour).zfill(2)}:" \ + f"{str(self.minute).zfill(2)}:" \ + f"{str(self.second).zfill(2)}" + + def __repr__(self): + return f"Time({self.hour},{self.minute},{self.second})" + + + def __gt__(self, other): + if self.hour > other.hour: + return True + elif self.hour == other.hour: + if self.minute > other.minute: + return True + elif self.minute == other.minute: + if self.second > other.second: + return True + return False + + def __ge__(self, other): + if self.hour > other.hour: + return True + elif self.hour == other.hour: + if self.minute > other.minute: + return True + elif self.minute == other.minute: + if self.second >= other.second: + return True + return False + + def __eq__(self, other): + if isinstance(other, Time): + if self.hour == other.hour and self.minute == other.minute and self.second == other.second: + return True + return False + elif isinstance(other, int): + return self == Time(other, 0, 0) + + +t = Time(11,1,2) +print(t) +print(repr(t)) diff --git a/lesson18/abstract.class.py b/lesson18/abstract.class.py new file mode 100644 index 0000000..c1f3ec3 --- /dev/null +++ b/lesson18/abstract.class.py @@ -0,0 +1,14 @@ +# abstract.class.py +from abc import ABC, abstractmethod + + +class MyAbstractClass(ABC): + def __init__(self, attr): + self.attr = attr + + @abstractmethod + def my_abstract_method(self): + pass + + +ob = MyAbstractClass(1) diff --git a/lesson18/exercise01.py b/lesson18/exercise01.py new file mode 100644 index 0000000..1951e49 --- /dev/null +++ b/lesson18/exercise01.py @@ -0,0 +1,50 @@ +class Animal: + def __init__(self, weight, height): + self.weight = weight + self.height = height + + +class Horse(Animal): + def __init__(self, weight, height, color, tail): + super().__init__(weight, height) + self.color = color + self.tail = tail + + +class Dog(Animal): + def __init__(self, weight, height, db): + super().__init__(weight, height) + self.db = db + + def bark(self): + print("Woof woof") + + +class Doberman(Dog): + def __init__(self, weight, height, db): + super().__init__(weight, height, db) + + def run(self): + print("Doberman is running") + + +class Bulldog(Dog): + def __init__(self, weight, height, db, ear_length): + super().__init__(weight, height, db) + self.ear_length = ear_length + + def sleep(self): + print("Bulldog is sleeping") + + +dolly = Horse(300,2,"white",1) +tobie = Doberman(50,1.1,8) +buddy = Bulldog(70,1,9,0.4) + +print(dolly.color) +tobie.bark() +tobie.run() +tobie.bark() +buddy.bark() +buddy.sleep() +buddy.sleep() \ No newline at end of file diff --git a/lesson18/exercise02.py b/lesson18/exercise02.py new file mode 100644 index 0000000..865270a --- /dev/null +++ b/lesson18/exercise02.py @@ -0,0 +1,57 @@ +from random import randrange, seed +from datetime import datetime + +class Video: + def __init__(self, artist, title, duration): + self.artist = artist + self.title = title + self.duration = duration + + def __str__(self): + return f"{self.artist} - {self.title} ({self.duration})" + +class Playlist: + def __init__(self, title, descr, duration, videos): + self.title = title + self.descr = descr + self.duration = duration + self.videos = videos + + def __str__(self): + st = f"{self.title} ({self.descr}). Duration: {self.duration}" + st += "\n" + "-" * 20 + for video in self.videos: + st += "\n" + str(video) + return st + + def add_video(self, video): + self.videos += [video] + + def recommendation(self): + return f"I recommend: {self.videos[randrange(len(self.videos))]}" + + +class ClassicalPlaylist(Playlist): + def __init__(self, title, descr, duration, videos, period): + super().__init__(title, descr, duration, videos) + self.period = period + + def recommendation(self): + return f"I recommend: {self.videos[0]} !!" + + +seed(datetime.now()) + +p = Playlist("Zouzounia","Paidika tragoudia", "45.18", + [Video("ZouzTV", "Xarwpa ta dio mou xeria ta xtipw", "03.22"), Video("ZouzTv", "Magia i melissa", "04.17")]) + + +print(p) +print(p.recommendation()) + +c = ClassicalPlaylist("Beethoven No.9", "", "88.13", + [Video("Beethoven", "Track 01", "03.22"), + Video("Beethoven", "Track 02", "04.17")], "baroque") + +print(c) +print(c.recommendation()) \ No newline at end of file diff --git a/lesson18/exercise03.py b/lesson18/exercise03.py new file mode 100644 index 0000000..a3a6e16 --- /dev/null +++ b/lesson18/exercise03.py @@ -0,0 +1,37 @@ +class Animal: + def make_sound(self): + print("") + + +class Cat(Animal): + def make_sound(self): + print("Meow") + + +class HimalayanCat(Cat): + def make_sound(self): + super().make_sound() + print("Miouw Miouw") + + +class Dog(Animal): + def make_sound(self): + print("Woof woof") + + +class Doberman(Dog): + pass + + +class KingDoberman(Doberman): + def make_sound(self): + super().make_sound() + print("WOOAAAAAAAFFF") + + +Animal().make_sound() +Cat().make_sound() +HimalayanCat().make_sound() +Dog().make_sound() +Doberman().make_sound() +KingDoberman().make_sound() \ No newline at end of file diff --git a/lesson18/exercise04.py b/lesson18/exercise04.py new file mode 100644 index 0000000..f7a1110 --- /dev/null +++ b/lesson18/exercise04.py @@ -0,0 +1,14 @@ +# protected.py +class Base: + def __init__(self): + self.__bpr_attr = 1 + + +class Derived(Base): + def __init__(self): + super().__init__() + + +d = Derived() +print(d._Base__bpr_attr) +print(d.__bpr_attr) \ No newline at end of file diff --git a/lesson18/exercise05.py b/lesson18/exercise05.py new file mode 100644 index 0000000..f1762df --- /dev/null +++ b/lesson18/exercise05.py @@ -0,0 +1,69 @@ +class Customer: + def __init__(self, full_name, address, orders=None): + self.full_name = full_name + self.address = address + if orders is None: + self.orders = [] + else: + self.orders = orders + + def place_order(self, order): + self.orders += [order] + + def __str__(self): + st = f"Name: {self.full_name}, Address: {self.address}" + st += "\n" + "-" * 35 + s = 0 + for order in self.orders: + st += "\n" + str(order) + s += order.payment.amount + st += "\n" + "-" * 35 + st += f"\nTotal: {s}" + return st + + +class Order: + def __init__(self, date, payment): + self.date = date + self.payment = payment + + def __str__(self): + return f"Date: {self.date}. Payment: {self.payment}" + + +class Payment: + def __init__(self, amount): + self.amount = amount + + def __str__(self): + return str(self.amount) + + +class Credit(Payment): + def __init__(self, amount, number, exp_date): + super().__init__(amount) + self.number = number + self.exp_date = exp_date + + def __str__(self): + return super().__str__() + ". CREDIT: Number: " + self.number + " Exp.Date" + self.exp_date + + +class Check(Payment): + def __init__(self, amount, number, bank_code): + super().__init__(amount) + self.number = number + self.bank_code = bank_code + + def __str__(self): + return super().__str__() + ". CHECK: Number: " + self.number + " Bank Code" + self.bank_code + + +def main(): + c = Customer("Jim Psoun", "Papadaki 78") + c.place_order(Order("20201020", Payment(12.12))) + c.place_order(Order("20201021", Credit(22.12, "12937-2139883-388", "20231203"))) + c.place_order(Order("20201022", Check(32.12, "12389-123898-239", "3834720-98/3"))) + print(c) + +main() \ No newline at end of file diff --git a/lesson18/exercise06.py b/lesson18/exercise06.py new file mode 100644 index 0000000..ccca827 --- /dev/null +++ b/lesson18/exercise06.py @@ -0,0 +1,29 @@ +class King: + def __init__(self, realm): + self.realm = realm + + def rule(self): + print("Now, I rule") + + +class Philosopher: + def __init__(self, school): + self.school = school + + def think(self): + print("Now, I think") + + +class PhilosopherKing(King, Philosopher): + def __init__(self, realm, school): + King.__init__(self, realm) + Philosopher.__init__(self, school) + + def routine(self): + self.think() + self.rule() + self.think() + + +marcus_aurelius = PhilosopherKing("Roman Empire", "Stoic") +marcus_aurelius.routine() \ No newline at end of file diff --git a/lesson18/exercise07.py b/lesson18/exercise07.py new file mode 100644 index 0000000..9422485 --- /dev/null +++ b/lesson18/exercise07.py @@ -0,0 +1,60 @@ +from random import randrange, seed +from datetime import datetime + + +class Person: + def __init__(self, full_name, salary): + self.full_name = full_name + self.salary = salary + self.served_cnt = 0 + + def report(self): + print(self.full_name + " served " + str(self.served_cnt) + " customers.") + +class Waiter(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def serve(self, customers, barista): + self.served_cnt += customers + print("Waiter " + self.full_name + " served " + str(customers) + " customers") + barista.prepare(customers) + + +class Barista(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def prepare(self, customers): + print("Barista " + self.full_name + " served " + str(customers) + " customers") + self.served_cnt += customers + + +class Owner(Waiter, Barista): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + + +def main(): + seed(datetime.now()) + + o = Owner("owner", 100000) + w1 = Waiter("waiter-1", 200000) + w2 = Waiter("waiter-1", 200000) + b = Barista("barista", 300000) + + waiters = [o, w1, w2] + baristas = [o, b] + + for _ in range(10): + waiters[randrange(3)].serve(randrange(1,5+1), baristas[randrange(2)]) + + print("") + o.report() + w1.report() + w2.report() + b.report() + +main() + diff --git a/lesson18/exercise08.py b/lesson18/exercise08.py new file mode 100644 index 0000000..4f5e10f --- /dev/null +++ b/lesson18/exercise08.py @@ -0,0 +1,39 @@ +from abc import ABC, abstractmethod + +class Animal(ABC): + @abstractmethod + def make_sound(self): + pass + + +class Cat(Animal): + def make_sound(self): + print("Meow") + + +class HimalayanCat(Cat): + def make_sound(self): + super().make_sound() + print("Miouw Miouw") + + +class Dog(Animal): + def make_sound(self): + print("Woof woof") + + +class Doberman(Dog): + pass + + +class KingDoberman(Doberman): + def make_sound(self): + super().make_sound() + print("WOOAAAAAAAFFF") + + +Cat().make_sound() +HimalayanCat().make_sound() +Dog().make_sound() +Doberman().make_sound() +KingDoberman().make_sound() \ No newline at end of file diff --git a/lesson18/exercise09.py b/lesson18/exercise09.py new file mode 100644 index 0000000..acd341d --- /dev/null +++ b/lesson18/exercise09.py @@ -0,0 +1,60 @@ +from random import randrange, seed +from datetime import datetime +from abc import ABC, abstractmethod + +class Person(ABC): + def __init__(self, full_name, salary): + self.full_name = full_name + self.salary = salary + self.served_cnt = 0 + + def report(self): + print(self.full_name + " served " + str(self.served_cnt) + " customers.") + +class Waiter(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def serve(self, customers, barista): + self.served_cnt += customers + print("Waiter " + self.full_name + " served " + str(customers) + " customers") + barista.prepare(customers) + + +class Barista(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def prepare(self, customers): + print("Barista " + self.full_name + " served " + str(customers) + " customers") + self.served_cnt += customers + + +class Owner(Waiter, Barista): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + + +def main(): + seed(datetime.now()) + + o = Owner("owner", 100000) + w1 = Waiter("waiter-1", 200000) + w2 = Waiter("waiter-1", 200000) + b = Barista("barista", 300000) + + waiters = [o, w1, w2] + baristas = [o, b] + + for _ in range(10): + waiters[randrange(3)].serve(randrange(1,5+1), baristas[randrange(2)]) + + print("") + o.report() + w1.report() + w2.report() + b.report() + +main() + diff --git a/lesson18/exercise10.py b/lesson18/exercise10.py new file mode 100644 index 0000000..3fb6d5e --- /dev/null +++ b/lesson18/exercise10.py @@ -0,0 +1,43 @@ +from abc import ABC, abstractmethod +from math import pi + + +class GeometricObjectInterface(ABC): + @abstractmethod + def area(self): + pass + + @abstractmethod + def perimeter(self): + pass + + +class Cycle(GeometricObjectInterface): + def __init__(self, radius): + self.radius = radius + + def area(self): + return pi * self.radius ** 2 + + def perimeter(self): + return 2 * pi * self.radius + + +class Resizable(ABC): + @abstractmethod + def resize(self, param): + pass + + +class CycleResizable(Cycle, Resizable): + def __init__(self, radius): + Cycle.__init__(self, radius) + + def resize(self, param): + self.radius = self.radius * param + + +c = CycleResizable(1) +print(c.area(), c.perimeter()) +c.resize(2) +print(c.area(), c.perimeter()) diff --git a/lesson18/exercise11.py b/lesson18/exercise11.py new file mode 100644 index 0000000..0f27026 --- /dev/null +++ b/lesson18/exercise11.py @@ -0,0 +1,74 @@ +from linked_list import LinkedList +from random import randrange + +class OrderedList(LinkedList): + def __init__(self): + super().__init__() + + def insert(self, data): + if self.empty(): + self.insert_start(data) + elif data < self.head.data: + self.insert_start(data) + else: + prev = self.head + cur = self.head.next + while cur is not None: + if data < cur.data: + self.insert_after(prev,data) + return + else: + prev = cur + cur = cur.next + else: + self.insert_after(prev, data) + + def delete(self, data): + if self.empty(): + return None + elif self.head.data == data: + return self.delete_start() + else: + prev = self.head + cur = self.head.next + while cur is not None: + if data == cur.data: + return self.delete_after(prev) + else: + prev = cur + cur = cur.next + else: + return None + + +l = LinkedList() +for i in range(4,-1,-1): + l.insert_start(i) +print(l) + +l.insert_after(l.head.next.next, 5) +print(l) + +print(l.delete_start()) +print(l) + +print(l.delete_after(l.head.next)) +print(l) + +print("-" * 20) + +ol = OrderedList() + +for i in range(50): + val = randrange(10) + if i%2 == 0: + ol.insert(val) + print(f"inserted {val}.") + else: + ret = ol.delete(val) + if ret is None: + print(f"Deleting... {val} not found!") + else: + print(f"Deleted {val}") + print(ol) + diff --git a/lesson18/inheritance.py b/lesson18/inheritance.py new file mode 100644 index 0000000..f40d791 --- /dev/null +++ b/lesson18/inheritance.py @@ -0,0 +1,25 @@ +class Cow: + def __init__(self, weight, hunger): + self.weight = weight + self.hunger = hunger + + def express(self): + if self.hunger > 5: + print("Moooooowwwwwwwwww") + else: + print("Mowww") + + +class TexasLonghorn(Cow): + def __init__(self, weight, hunger, horn_length): + super().__init__(weight, hunger) + self.horn_length = horn_length + + +molly = Cow(500, 10) +molly.express() + +bob = TexasLonghorn(400,20,0.50) +bob.express() +print(f"Bob's horns are {bob.horn_length} meters long") +print(f"Bob's weight={bob.weight}, hunger={bob.hunger}, horn_length={bob.horn_length}") \ No newline at end of file diff --git a/lesson18/interface.py b/lesson18/interface.py new file mode 100644 index 0000000..43398e8 --- /dev/null +++ b/lesson18/interface.py @@ -0,0 +1,16 @@ +# interface.py +from abc import ABC, abstractmethod + + +class MyInterface(ABC): + @abstractmethod + def interface_method1(self): + pass + + @abstractmethod + def interface_method2(self): + pass + + +class MyRealClass(MyInterface): + ... diff --git a/lesson18/lesson18.exercise12/arena.py b/lesson18/lesson18.exercise12/arena.py new file mode 100644 index 0000000..0201c49 --- /dev/null +++ b/lesson18/lesson18.exercise12/arena.py @@ -0,0 +1,85 @@ +from character import Character +from random import randrange + +class Arena: + def __init__(self, team_A, team_B): + self.team_A = team_A + self.team_B = team_B + + def __str__(self): + st = "\n" + "-" * 15 + st += "\nTEAM A" + for character in self.team_A: + st += "\n" + str(character) + st += "\n" + ("-" * 15) + for character in self.team_B: + st += "\n" + str(character) + st += "\n" + ("-" * 15) + return st + + def __repr__(self): + st = f"Arena([" + st += ", ".join([repr(character) for character in self.team_A]) + st += "],[" + st += ", ".join([repr(character) for character in self.team_B]) + st += "])" + return st + + + def play(self): + time = -1 + while True: + time += 1 + print("=" * 20) + print("Time = " + str(time)) + print("=" * 20) + print(self) + + # create list of characters to play + chars_to_play = [] + for character in self.team_A: + if character.delay == 0: + chars_to_play.append(('A', character)) + for character in self.team_B: + if character.delay == 0: + chars_to_play.append(('B', character)) + + # active characters attack + + for character in chars_to_play: + attacking = character[1] + if character[0] == 'A': + defending = self.team_B[randrange(len(self.team_B))] + else: + defending = self.team_A[randrange(len(self.team_A))] + + damage = attacking.attack() + defending.health -= damage + print(f"{attacking.character_name} dealt {damage} to {defending.character_name}") + + # check for dead characters + + for pos in range(len(self.team_A)-1,-1,-1): + if self.team_A[pos].is_dead(): + print(f"{self.team_A[pos].character_name} is dead!") + self.team_A.pop(pos) + for pos in range(len(self.team_B)-1,-1,-1): + if self.team_B[pos].is_dead(): + print(f"{self.team_B[pos].character_name} is dead!") + self.team_B.pop(pos) + + # check if game ended + if len(self.team_A) == 0: + print("Team B won!") + break + elif len(self.team_B) == 0: + print("Team A won!") + break + + # end round! + for character in self.team_A: + character.end_round() + for character in self.team_B: + character.end_round() + + input("Press Enter to Continue") \ No newline at end of file diff --git a/lesson18/lesson18.exercise12/character.py b/lesson18/lesson18.exercise12/character.py new file mode 100644 index 0000000..bbb1131 --- /dev/null +++ b/lesson18/lesson18.exercise12/character.py @@ -0,0 +1,39 @@ +from equipment import Equipment +from random import randrange + + +class Character: + def __init__(self, character_name, equipment, attack_speed=2, delay=0): + self.character_name = character_name + self.equipment = equipment + self.max_health = 100 * self.equipment.cape + self.health = 100 * self.equipment.cape + self.attack_range = (3, 11) + self.attack_speed = attack_speed + self.delay = delay + self.max_delay = 5 + + def attack(self): + self.delay = self.max_delay - self.attack_speed + return round(randrange(self.attack_range[0], self.attack_range[1]) * self.equipment.sword) + + def is_dead(self): + return self.health <= 0 + + def end_round(self): + self.health = self.health+1 if self.health+1<=self.max_health else self.max_health + self.delay -= 1 + + def __str__(self): + return f"{self.character_name} H:{round(self.health)} D:{self.delay}" + + def __repr__(self): + return f"Character({self.character_name},{self.attack_speed}, {self.delay}, {round(self.max_health)}, {round(self.health)})" + + def __iadd__(self, other): + self.health += other + return self + + def __isub__(self, other): + self.health -= other + return self \ No newline at end of file diff --git a/lesson18/lesson18.exercise12/equipment.py b/lesson18/lesson18.exercise12/equipment.py new file mode 100644 index 0000000..4f85f40 --- /dev/null +++ b/lesson18/lesson18.exercise12/equipment.py @@ -0,0 +1,5 @@ +class Equipment: + def __init__(self, sword, cape): + self.sword = sword + self.cape = cape + diff --git a/lesson18/lesson18.exercise12/mage.py b/lesson18/lesson18.exercise12/mage.py new file mode 100644 index 0000000..2f75ee7 --- /dev/null +++ b/lesson18/lesson18.exercise12/mage.py @@ -0,0 +1,25 @@ +from character import Character +from random import randrange + + +class Mage(Character): + def __init__(self, character_name, equipment, attack_speed=2, delay=0): + super().__init__(character_name, equipment, attack_speed, delay) + self.attack_range = (8, 17) + self.mana = 100 + self.max_mana = 100 + + def end_round(self): + super().end_round() + self.mana = self.mana + 1 if self.mana + 1 <= self.mana else self.max_mana + + def lightning_spell(self): + self.mana -= 55 + return randrange(30, 50) + + def attack(self): + self.delay = self.max_delay - self.attack_speed + if self.mana >= 55: + return self.lightning_spell() + else: + return round(randrange(self.attack_range[0], self.attack_range[1]) * self.equipment.sword) diff --git a/lesson18/lesson18.exercise12/main.py b/lesson18/lesson18.exercise12/main.py new file mode 100644 index 0000000..226096a --- /dev/null +++ b/lesson18/lesson18.exercise12/main.py @@ -0,0 +1,21 @@ +from character import Character +from tank import Tank +from mage import Mage +from arena import Arena +from equipment import Equipment +from random import randrange, seed, uniform +from datetime import datetime + + +def main(): + seed(datetime.now()) + + orcs = [Character("Orc-" + str(i+1),Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 2,randrange(4)) for i in range(5)] + orcs += [Tank("Orc Tank",Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 2,randrange(4))] + night_elves = [Character("Night-Elf-" + str(i + 1),Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 3, randrange(3)) for i in range(3)] + night_elves += [Mage("Night Elf Mage",Equipment(uniform(1.1, 1.5), uniform(1.1,1.3)), 2, randrange(4))] + a = Arena(orcs, night_elves) + a.play() + + +main() \ No newline at end of file diff --git a/lesson18/lesson18.exercise12/tank.py b/lesson18/lesson18.exercise12/tank.py new file mode 100644 index 0000000..6b3e49b --- /dev/null +++ b/lesson18/lesson18.exercise12/tank.py @@ -0,0 +1,8 @@ +from character import Character + +class Tank(Character): + def __init__(self, character_name, equipment, attack_speed=2, delay=0): + super().__init__(character_name, equipment, attack_speed, delay) + self.attack_range = (20, 30) + self.max_health = self.max_health * 2 + self.health = self.max_health diff --git a/lesson18/linked_list.py b/lesson18/linked_list.py new file mode 100644 index 0000000..764fd5a --- /dev/null +++ b/lesson18/linked_list.py @@ -0,0 +1,48 @@ +class Node: + def __init__(self, data, next=None): + self.data = data + self.next = next + + +class LinkedList: + def __init__(self): + self.head = None + + def empty(self): + return self.head is None + + def insert_start(self, data): + n = Node(data) + n.next = self.head + self.head = n + + def insert_after(self, prev, data): + n = Node(data) + n.next = prev.next + prev.next = n + + def delete_start(self): + if self.empty(): + return None + else: + c = self.head + self.head = self.head.next + return c.data + + def delete_after(self, prev): + if prev.next is None: + return None + else: + c = prev.next + prev.next = c.next + return c.data + + def __str__(self): + p = self.head + st = "" + while p is not None: + st += str(p.data) + "-->" + p = p.next + st += "." + return st + diff --git a/lesson18/method.overriding.py b/lesson18/method.overriding.py new file mode 100644 index 0000000..446ca28 --- /dev/null +++ b/lesson18/method.overriding.py @@ -0,0 +1,31 @@ +# method.overriding.py +class Cow: + def __init__(self, weight, hunger): + self.weight = weight + self.hunger = hunger + + def express(self): + if self.hunger > 5: + print("Moooooowwwwwwwwww") + else: + print("Mowww") + + +class TexasLonghorn(Cow): + def __init__(self, weight, hunger, horn_length): + super().__init__(weight, hunger) + self.horn_length = horn_length + + def express(self): + if self.hunger > 5: + print("MEEoooEEEwwwwwwwww") + else: + print("MEoEwww") + +molly = Cow(500, 10) +molly.express() + +bob = TexasLonghorn(400,20,0.50) +bob.express() +print(f"Bob's horns are {bob.horn_length} meters long") +print(f"Bob's weight={bob.weight}, hunger={bob.hunger}, horn_length={bob.horn_length}") \ No newline at end of file diff --git a/lesson18/mixin.py b/lesson18/mixin.py new file mode 100644 index 0000000..9a5c172 --- /dev/null +++ b/lesson18/mixin.py @@ -0,0 +1,23 @@ +# mixin.py +class ComparableMixin: + """This class has methods which use `<=` and `==`, + but this class does NOT implement those methods.""" + def __ne__(self, other): + return not (self == other) + def __lt__(self, other): + return self <= other and (self != other) + def __gt__(self, other): + return not self <= other + def __ge__(self, other): + return self == other or self > other + +class Integer(ComparableMixin): + def __init__(self, i): + self.i = i + def __le__(self, other): + return self.i <= other.i + def __eq__(self, other): + return self.i == other.i + +print(Integer(3)<=Integer(4)) +print(Integer(3)= 100.") + else: + st = user_input + if st == "": + raise ValueError("No digits entered!") + elif not st.isdigit(): + raise ValueError("Wrong Input. Only digits please!") + x = int(st) + if x < 100: + raise ValueTooSmallError("Value must be >= 100.") + elif x > 200: + raise ValueTooLargeError("Value must be <= 200.") + elif x % 5 != 0: + raise NotMultipleOfFiveError(x) + + except (ValueTooSmallError, ValueTooLargeError, NotMultipleOfFiveError) as e: + print(e) + except ValueError as v: + print(v) + except Exception as e: + print(e) + else: + return x + + +print(get_integer_con()) \ No newline at end of file diff --git a/lesson19/exercise04.py b/lesson19/exercise04.py new file mode 100644 index 0000000..2fa84d2 --- /dev/null +++ b/lesson19/exercise04.py @@ -0,0 +1,20 @@ +from tree import Tree, BinarySearchTree + +t = Tree() +t.insert_root("A") +t.insert_left(t.root, "B") +t.insert_right(t.root, "C") +t.insert_left(t.root.left, "D") +t.insert_right(t.root.left, "E") +t.insert_right(t.root.right, "F") +print(t) + +t2 = BinarySearchTree() +t2.insert(2) +t2.insert(5) +t2.insert(8) +t2.insert(11) +t2.insert(1) +t2.insert(7) +print(t2) +print(t2.inorder()) \ No newline at end of file diff --git a/lesson19/lesson19.exercise05/exercise05.py b/lesson19/lesson19.exercise05/exercise05.py new file mode 100644 index 0000000..1043acb --- /dev/null +++ b/lesson19/lesson19.exercise05/exercise05.py @@ -0,0 +1,211 @@ +from teachers import Teachers +from pupils import Pupils +from lessons import Lessons + + +def main(): + + pupils = Pupils() + teachers = Teachers() + lessons = Lessons() + + while True: + print("\n===============") + print(" MENU ") + + print("1 - Manage Pupils") + print("2 - Manage Teachers") + print("3 - Manage Lessons") + print("4 - Exit") + choice = int(input("Pick one: ")) + + if choice == 1: + print("\n===============") + print(" PUPILS MENU ") + + print("1 - Create Pupil") + print("2 - Print Pupil(s)") + print("3 - Update Pupil") + print("4 - Delete Pupil") + pupils_choice = int(input("Pick one: ")) + + if pupils_choice == 1: + print("NEW PUPIL") + print("===========") + pupil = pupils.create_pupil() + if pupil is None: + continue + else: + print("NEW PUPIL") + print(pupil) + + elif pupils_choice == 2: + print("\n===============") + print(" SUB-MENU (PRINT) ") + print("1 - Print Pupil") + print("2 - Print all pupils (details)") + print("3 - Print all pupils (just the names)") + print_choice = input("Give your choice: ") + if print_choice.strip().isdigit(): + print_choice = int(print_choice) + else: + print("Wrong input!") + continue + + if print_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Pupil does not exist (with this id)") + else: + print(" PUPIL ") + print(pupil) + + elif print_choice == 2: + print(pupils) + elif print_choice == 3: + pupils.print_pupils_names() + else: + print("Wrong input! ") + continue + + elif pupils_choice == 3: + print("\n===============") + print(" SUB-MENU (UPDATE) ") + print("1 - Update Pupil (search by id)") + print("2 - Update Pupil (search by surname)") + update_choice = input("Give your choice: ") + if update_choice.strip().isdigit(): + update_choice = int(update_choice) + else: + print("Wrong input!") + continue + + if update_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif update_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: update + pupils.pupil_update(pupil) + + elif pupils_choice == 4: + print("\n===============") + print(" SUB-MENU (DELETE) ") + print("1 - Delete Pupil (search by id)") + print("2 - Delete Pupil (search by surname)") + delete_choice = input("Give your choice: ") + if delete_choice.strip().isdigit(): + delete_choice = int(delete_choice) + else: + print("Wrong input!") + continue + + if delete_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif delete_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: delete + pupils.delete_pupil_by_id(pupil.pupil_id) + + elif choice == 2: + print("\n===============") + print(" TEACHERS MENU ") + + print("1 - Create Teacher") + print("2 - Print Teacher(s)") + print("3 - Update Teacher") + print("4 - Delete Teacher") + teacher_choice = int(input("Pick one: ")) + + if teacher_choice == 1: + first_name = input("Give name: ") + surname = input("Give surname: ") + teachers.create_teacher(first_name, surname) + elif teacher_choice == 2: + teacher_id = int(input("Give id: ")) + teacher = teachers.read_teacher(teacher_id) + if teacher is None: + print("No such teacher exists!") + else: + print(teacher) + elif teacher_choice == 3: + teacher_id = int(input("Give id: ")) + teachers.update_teacher(teacher_id) + elif teacher_choice == 4: + teacher_id = int(input("Give id: ")) + teachers.delete_teacher(teacher_id) + + elif choice == 3: + print("\n===============") + print(" LESSONS MENU ") + + print("1 - Create Lesson") + print("2 - Print Lesson") + print("3 - Update Lesson") + print("4 - Delete Lesson") + lesson_choice = int(input("Pick one: ")) + + if lesson_choice == 1: + lesson_name = input("Give lesson name: ") + lessons.create_lesson(lesson_name) + elif lesson_choice == 2: + lesson_id = int(input("Give id: ")) + lesson = lessons.read_lesson(lesson_id) + if lesson is None: + print("No such lesson exists!") + else: + lesson.print_lesson_details(teachers, pupils) + elif lesson_choice == 3: + lesson_id = int(input("Give id: ")) + lessons.update_lesson(lesson_id, teachers, pupils) + elif lesson_choice == 4: + lesson_id = int(input("Give id: ")) + lessons.delete_lesson(lesson_id) + + + + elif choice == 4: + print("Bye bye!") + pupils.save_pupils_data() + teachers.save_teachers_data() + lessons.save_lessons_data() + break + + +main() \ No newline at end of file diff --git a/lesson19/lesson19.exercise05/lesson.py b/lesson19/lesson19.exercise05/lesson.py new file mode 100644 index 0000000..b422372 --- /dev/null +++ b/lesson19/lesson19.exercise05/lesson.py @@ -0,0 +1,38 @@ +from teachers import Teachers +from pupils import Pupils + + +class Lesson: + def __init__(self, lesson_name="", lesson_id=-1): + self.lesson_name = lesson_name + self.teacher_ids = [] + self.pupil_ids = [] + self.lesson_id = lesson_id + + def from_dict(self, lesson_dict): + self.lesson_name = lesson_dict["lesson_name"] + self.teacher_ids = lesson_dict["teacher_ids"] + self.pupil_ids = lesson_dict["pupil_ids"] + self.lesson_id = lesson_dict["lesson_id"] + + def to_dict(self): + lesson_dict = {"lesson_name": self.lesson_name, + "teacher_ids": self.teacher_ids, + "pupil_ids": self.pupil_ids, + "lesson_id": self.lesson_id + } + + return lesson_dict + + def print_lesson_details(self, teachers, pupils): + print(f"LESSON: {self.lesson_name}") + print("=========") + print("TEACHERS: ") + for teacher_id in self.teacher_ids: + teacher = teachers.read_teacher(teacher_id) + print(f"{teacher.first_name} {teacher.surname}") + print("STUDENTS: ") + for pupil_id in self.pupil_ids: + pupil = pupils.search_pupil_by_id(pupil_id) + print(f"{pupil.first_name} {pupil.last_name}") + diff --git a/lesson19/lesson19.exercise05/lessons.json b/lesson19/lesson19.exercise05/lessons.json new file mode 100644 index 0000000..92073a6 --- /dev/null +++ b/lesson19/lesson19.exercise05/lessons.json @@ -0,0 +1 @@ +[{"lesson_name": "Algorithms", "teacher_ids": [1001], "pupil_ids": [1001, 1002], "lesson_id": 1001}] \ No newline at end of file diff --git a/lesson19/lesson19.exercise05/lessons.py b/lesson19/lesson19.exercise05/lessons.py new file mode 100644 index 0000000..c9dfb6b --- /dev/null +++ b/lesson19/lesson19.exercise05/lessons.py @@ -0,0 +1,101 @@ +import json +from lesson import Lesson + +class Lessons: + def __init__(self): + try: + with open("lessons.json") as f: + lessons_list = json.load(f) + + self.lessons = [] + for lesson_dict in lessons_list: + l = Lesson() + l.from_dict(lesson_dict) + self.lessons += [l] + except FileNotFoundError: + self.lessons = [] + + def save_lessons_data(self): + list_to_write = [] + for lesson in self.lessons: + list_to_write += [lesson.to_dict()] + + with open("lessons.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.lessons: + return 1001 + else: + ids = [] + for l in self.lessons: + ids.append(l.lesson_id) + return max(ids) + 1 + + def create_lesson(self, lesson_name): + for lesson in self.lessons: + if lesson.lesson_name == lesson_name: + print("Error. Lesson already exists! ") + return None + + l = Lesson(lesson_name, self.next_id()) + self.lessons.append(l) + return l + + def read_lesson(self, lesson_id): + for lesson in self.lessons: + if lesson_id == lesson.lesson_id: + return lesson + else: + return None + + def update_lesson(self, lesson_id, teachers, pupils): + for lesson in self.lessons: + if lesson_id == lesson.lesson_id: + lesson.print_lesson_details(teachers, pupils) + choice = int(input("Update 1-name, 2-teachers, 3-pupils: ")) + if choice == 1: + lesson.lesson_name = input("Give new name: ") + elif choice == 2: + upd_teacher_choice = int(input("Updating lesson teachers: 1-add, 2-remove: ")) + if upd_teacher_choice == 1: + print("Teachers(not in lesson): ") + for teacher in teachers.teachers: + if teacher.teacher_id not in lesson.teacher_ids: + print(f"{teacher.teacher_id}-{teacher.first_name} {teacher.surname}") + upd_teacher_id = int(input("Pick the (id) to add: ")) + lesson.teacher_ids.append(upd_teacher_id) + elif upd_teacher_choice == 2: + print("Lesson Teachers: ") + for teacher_id in lesson.teacher_ids: + teacher = teachers.read_teacher(teacher_id) + print(f"{teacher.teacher_id}-{teacher.first_name} {teacher.surname}") + upd_teacher_id = int(input("Pick the (id) to delete: ")) + lesson.teacher_ids.remove(upd_teacher_id) + elif choice == 3: + upd_pupil_choice = int(input("Updating lesson pupils: 1-add, 2-remove: ")) + if upd_pupil_choice == 1: + print("Pupils(not in lesson): ") + for pupil in pupils.pupils: + if pupil.pupil_id not in lesson.pupil_ids: + print(f"{pupil.pupil_id}-{pupil.first_name} {pupil.last_name}") + upd_pupil_id = int(input("Pick the (id) to add: ")) + lesson.pupil_ids.append(upd_pupil_id) + elif upd_pupil_choice == 2: + print("Lesson Pupils: ") + for pupil_id in lesson.pupil_ids: + pupil = pupils.search_pupil_by_id(pupil_id) + print(f"{pupil.pupil_id}-{pupil.first_name} {pupil.last_name}") + upd_pupil_id = int(input("Pick the (id) to delete: ")) + lesson.pupil_ids.remove(upd_pupil_id) + break + + def delete_lesson(self, lesson_id): + for i in range(len(self.lessons)): + if lesson_id == self.lessons[i].lesson_id: + self.lessons.pop(i) + return + else: + print("No lesson with this id!") + + diff --git a/lesson19/lesson19.exercise05/pupil.py b/lesson19/lesson19.exercise05/pupil.py new file mode 100644 index 0000000..ecde02f --- /dev/null +++ b/lesson19/lesson19.exercise05/pupil.py @@ -0,0 +1,42 @@ +class Pupil: + def __init__(self, first_name="", last_name="", fathers_name="", + age=-1, class_name="", id_number=None, pupil_id=-1): + self.first_name = first_name + self.last_name = last_name + self.fathers_name = fathers_name + self.age = age + self.class_name = class_name + self.id_number = id_number + self.pupil_id = pupil_id + + def from_dict(self, pupil_dict): + self.first_name = pupil_dict["first_name"] + self.last_name = pupil_dict["last_name"] + self.fathers_name = pupil_dict["fathers_name"] + self.age = pupil_dict["age"] + self.class_name = pupil_dict["class_name"] + if "id_number" in pupil_dict: + self.id_number = pupil_dict["id_number"] + self.pupil_id = pupil_dict["pupil_id"] + + def to_dict(self): + pupil_dict = {"first_name": self.first_name, + "last_name": self.last_name, + "fathers_name": self.fathers_name, + "age": self.age, + "class_name": self.class_name, + "pupil_id": self.pupil_id} + if self.id_number is not None: + pupil_dict["id_number"] = self.id_number + return pupil_dict + + def __str__(self): + + st = f"\nName : {self.first_name}" + st += f"\nLast Name : {self.last_name}" + st += f"\nFather's Name : {self.fathers_name}" + st += f"\nAge : {self.age}" + st += f"\nClass : {self.class_name}" + if self.id_number is not None: + st += f"\nID card number: {self.id_number}" + return st diff --git a/lesson19/lesson19.exercise05/pupils.json b/lesson19/lesson19.exercise05/pupils.json new file mode 100644 index 0000000..d8ffad4 --- /dev/null +++ b/lesson19/lesson19.exercise05/pupils.json @@ -0,0 +1 @@ +[{"first_name": "John", "last_name": "Cm", "fathers_name": "Wick", "age": 44, "class_name": 1, "pupil_id": 1001, "id_number": "12131234"}, {"first_name": "Bob", "last_name": "Hope", "fathers_name": "Charles", "age": 12, "class_name": 2, "pupil_id": 1002}, {"first_name": "1", "last_name": "1", "fathers_name": "1", "age": 1, "class_name": 1, "pupil_id": 1003}] \ No newline at end of file diff --git a/lesson19/lesson19.exercise05/pupils.py b/lesson19/lesson19.exercise05/pupils.py new file mode 100644 index 0000000..150aa39 --- /dev/null +++ b/lesson19/lesson19.exercise05/pupils.py @@ -0,0 +1,121 @@ +from pupil import Pupil +import json + + +class Pupils: + def __init__(self): + try: + with open("pupils.json") as f: + pupils_list = json.load(f) + + self.pupils = [] + for pupil_dict in pupils_list: + p = Pupil() + p.from_dict(pupil_dict) + self.pupils += [p] + except FileNotFoundError: + self.pupils = [] + + def __str__(self): + st = "" + for pupil in self.pupils: + st += "\n" + "=" * 15 + st += str(pupil) + return st + + def save_pupils_data(self): + list_to_write = [] + for pupil in self.pupils: + list_to_write += [pupil.to_dict()] + + with open("pupils.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.pupils: + return 1001 + else: + ids = [] + for p in self.pupils: + ids.append(p.pupil_id) + return max(ids) + 1 + + def create_pupil(self): + first_name = input("Give name: ") + last_name = input("Give surname: ") + fathers_name = input("Give father's name: ") + + for p in self.pupils: + if first_name == p.first_name and last_name == p.last_name and fathers_name == p.fathers_name: + print("This pupil already exists.") + ch = input("Do you want to continue? (y-yes, n-no): ") + if ch == "n": + return None + + age = int(input("Give age: ")) + class_name = int(input("Give class: ")) + id_card = input("Does he/she has an id card: (y-true, n-false): ") + if id_card == "y": + id_number = input("Give id card number: ") + else: + id_number = None + + pupil = Pupil(first_name,last_name,fathers_name,age,class_name,id_number,self.next_id()) + + self.pupils.append(pupil) + return pupil + + def search_pupil_by_id(self, pupil_id): + for pupil in self.pupils: + if pupil_id == pupil.pupil_id: + return pupil + return None + + def search_pupil_by_surname(self, last_name): + match_pupils = [] + for pupil in self.pupils: + if last_name == pupil.last_name: + match_pupils.append(pupil) + return match_pupils + + def pupil_update(self, pupil): + print(pupil) + print("=" * 15) + print("1-name") + print("2-surname") + print("3-father's name") + print("4-age") + print("5-class") + print("6-id number") + print("=" * 15) + update_choice = int(input("Pick something to update: ")) + if update_choice == 1: + pupil.first_name = input("Give new name: ") + elif update_choice == 2: + pupil.last_name = input("Give new surname: ") + elif update_choice == 3: + pupil.fathers_name = input("Give new father's name: ") + elif update_choice == 4: + pupil.age = input("Give new age: ") + elif update_choice == 5: + pupil.class_name = input("Give new class: ") + elif update_choice == 6: + pupil.id_number = input("Give new id number: ") + + print("=" * 15) + print(pupil) + print("Pupil updated! ") + + def delete_pupil_by_id(self, pupil_id): + for i in range(len(self.pupils)): + if pupil_id == self.pupils[i].pupil_id: + self.pupils.pop(i) + print("Pupil deleted!") + return + else: + print("No pupil with this id!") + + def print_pupils_names(self): + for pupil in self.pupils: + print(f"{pupil.first_name} {pupil.fathers_name[0]}. {pupil.last_name}") + diff --git a/lesson19/lesson19.exercise05/teacher.py b/lesson19/lesson19.exercise05/teacher.py new file mode 100644 index 0000000..bfdfb5e --- /dev/null +++ b/lesson19/lesson19.exercise05/teacher.py @@ -0,0 +1,22 @@ +class Teacher: + def __init__(self, first_name="", surname="", teacher_id=-1): + self.first_name = first_name + self.surname = surname + self.teacher_id = teacher_id + + def from_dict(self, teacher_dict): + self.first_name = teacher_dict["first_name"] + self.surname = teacher_dict["surname"] + self.teacher_id = teacher_dict["teacher_id"] + + def to_dict(self): + teacher_dict = {"first_name": self.first_name, + "surname": self.surname, + "teacher_id":self.teacher_id} + return teacher_dict + + def __str__(self): + st = f"Name : {self.first_name}" + st += f"\nSurname: {self.surname}" + st += f"\nid : {self.teacher_id}" + return st diff --git a/lesson19/lesson19.exercise05/teachers.json b/lesson19/lesson19.exercise05/teachers.json new file mode 100644 index 0000000..fd7e825 --- /dev/null +++ b/lesson19/lesson19.exercise05/teachers.json @@ -0,0 +1 @@ +[{"first_name": "Severus", "surname": "Snape", "teacher_id": 1001}, {"first_name": "Charles", "surname": "Xavier", "teacher_id": 1002}, {"first_name": "Sergio", "surname": "Marquina", "teacher_id": 1003}] \ No newline at end of file diff --git a/lesson19/lesson19.exercise05/teachers.py b/lesson19/lesson19.exercise05/teachers.py new file mode 100644 index 0000000..0fb4cca --- /dev/null +++ b/lesson19/lesson19.exercise05/teachers.py @@ -0,0 +1,72 @@ +import json +from teacher import Teacher + + +class Teachers: + def __init__(self): + try: + with open("teachers.json") as f: + teachers_list = json.load(f) + + self.teachers = [] + for teacher_dict in teachers_list: + t = Teacher() + t.from_dict(teacher_dict) + self.teachers += [t] + except FileNotFoundError: + self.teachers = [] + + def save_teachers_data(self): + list_to_write = [] + for teacher in self.teachers: + list_to_write += [teacher.to_dict()] + + with open("teachers.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.teachers: + return 1001 + else: + ids = [] + for t in self.teachers: + ids.append(t.teacher_id) + return max(ids) + 1 + + def create_teacher(self,first_name, surname): + for teacher in self.teachers: + if teacher.first_name == first_name and teacher.surname == surname: + print("Error. Teacher already exists! ") + return None + + t = Teacher(first_name, surname, self.next_id()) + self.teachers.append(t) + return t + + def read_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + return teacher + else: + return None + + def update_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + print(teacher) + choice = int(input("Update 1-name, 2-surname: ")) + if choice == 1: + teacher.first_name = input("Give new name: ") + elif choice == 2: + teacher.surname = input("Give new surname: ") + return + + def delete_teacher(self, teacher_id): + for i in range(len(self.teachers)): + if teacher_id == self.teachers[i].teacher_id: + self.teachers.pop(i) + return + else: + print("No teacher with this id!") + + diff --git a/lesson19/python19.exceptions.pdf b/lesson19/python19.exceptions.pdf new file mode 100644 index 0000000..0f462ce Binary files /dev/null and b/lesson19/python19.exceptions.pdf differ diff --git a/lesson19/raise.py b/lesson19/raise.py new file mode 100644 index 0000000..d93a815 --- /dev/null +++ b/lesson19/raise.py @@ -0,0 +1,12 @@ +# raise.py +while True: + try: + x = int(input("Give nonnegative integer: ")) + if x < 0: + raise ValueError("NonNegative Value entered") + except ValueError as v: + print(v) + else: + print(x) + break + diff --git a/lesson19/tree.py b/lesson19/tree.py new file mode 100644 index 0000000..f1f4625 --- /dev/null +++ b/lesson19/tree.py @@ -0,0 +1,86 @@ +class Node: + def __init__(self, data, left=None, right=None): + self.data = data + self.left = left + self.right = right + + +class Tree: + def __init__(self): + self.root = None + + def insert_root(self, data): + n = Node(data) + self.root = n + + def insert_left(self, node, data): + n = Node(data) + node.left = n + + def insert_right(self, node, data): + n = Node(data) + node.right = n + + def __str__(self): + st = "" + + def rec_str(n): + nonlocal st + + if n is None: + st += "_" + else: + st += str(n.data) + st += "(" + rec_str(n.left) + st += "," + rec_str(n.right) + st += ")" + + rec_str(self.root) + return st + + +class BinarySearchTree(Tree): + def __init__(self): + super().__init__() + + def insert(self, data): + if self.root is None: + self.insert_root(data) + print(str(data) + " inserted!") + + node = self.root + while True: + if data == node.data: + print(str(data) + " already in tree. ") + break + elif data < node.data: + if node.left is None: + node.left = Node(data) + print(str(data) + " inserted!") + break + else: + node = node.left + else: # data > node.data + if node.right is None: + node.right = Node(data) + print(str(data) + " inserted!") + break + else: + node = node.right + + def inorder(self): + ret_list = [] + + def rec_inorder(node): + nonlocal ret_list + if node is not None: + rec_inorder(node.left) + ret_list += [node.data] + rec_inorder(node.right) + + + + rec_inorder(self.root) + return ret_list \ No newline at end of file diff --git a/lesson19/try.except.py b/lesson19/try.except.py new file mode 100644 index 0000000..4b7078b --- /dev/null +++ b/lesson19/try.except.py @@ -0,0 +1,6 @@ +try: + nom = int(input("Give the nominator: ")) + denom = int(input("Give the denominator: ")) + res = nom/denom +except ZeroDivisionError: + print("Error: Division by zero") \ No newline at end of file diff --git a/lesson19/user.exception.py b/lesson19/user.exception.py new file mode 100644 index 0000000..384ea50 --- /dev/null +++ b/lesson19/user.exception.py @@ -0,0 +1,14 @@ +class MyException(Exception): + def __init__(self, val, message): + self.val = val + self.message = message + + def __str__(self): + return f"{self.message}: {str(self.val)} is not valid" + +try: + val = int(input("Give an integer: ")) + if val < 0: + raise MyException(val, "Invalid Value") +except MyException as e: + print(e) diff --git a/lesson20/args.py b/lesson20/args.py new file mode 100644 index 0000000..dfd4593 --- /dev/null +++ b/lesson20/args.py @@ -0,0 +1,5 @@ +def my_sum(*numbers): + s = 0 + for number in numbers: + s += int(number) + return s diff --git a/lesson20/assert.py b/lesson20/assert.py new file mode 100644 index 0000000..765e1fd --- /dev/null +++ b/lesson20/assert.py @@ -0,0 +1,10 @@ +def my_sum(sth): + s = 0 + for item in sth: + s += item + return s + + +assert my_sum((1,2,3)) == 6 +assert my_sum([1,2,3]) == 6 +assert my_sum({1,2,3}) == 6 \ No newline at end of file diff --git a/lesson20/assert2.py b/lesson20/assert2.py new file mode 100644 index 0000000..c5216eb --- /dev/null +++ b/lesson20/assert2.py @@ -0,0 +1,9 @@ +def my_avg(sth): + assert len(sth)!=0, "iterable is empty!" + s = 0 + for item in sth: + s += item + return s/len(sth) + +print(my_avg(())) + diff --git a/lesson20/comment.ret.value.py b/lesson20/comment.ret.value.py new file mode 100644 index 0000000..d69eb98 --- /dev/null +++ b/lesson20/comment.ret.value.py @@ -0,0 +1,4 @@ +def full_name(first_name, last_name) -> str: + return f"{first_name} {last_name}" + +print(full_name("John", "Wick")) \ No newline at end of file diff --git a/lesson20/documentation.py b/lesson20/documentation.py new file mode 100644 index 0000000..6a85091 --- /dev/null +++ b/lesson20/documentation.py @@ -0,0 +1,66 @@ +# source: https://realpython.com/documenting-python-code/ + +class Animal: + """ + A class used to represent an Animal + + ... + + Attributes + ---------- + says_str : str + a formatted string to print out what the animal says + name : str + the name of the animal + sound : str + the sound that the animal makes + num_legs : int + the number of legs the animal has (default 4) + + Methods + ------- + says(sound=None) + Prints the animals name and what sound it makes + """ + + says_str = "A {name} says {sound}" + + def __init__(self, name, sound, num_legs=4): + """ + Parameters + ---------- + name : str + The name of the animal + sound : str + The sound the animal makes + num_legs : int, optional + The number of legs the animal (default is 4) + """ + + self.name = name + self.sound = sound + self.num_legs = num_legs + + def says(self, sound=None): + """Prints what the animals name is and what sound it makes. + + If the argument `sound` isn't passed in, the default Animal + sound is used. + + Parameters + ---------- + sound : str, optional + The sound the animal makes (default is None) + + Raises + ------ + NotImplementedError + If no sound is set for the animal or passed in as a + parameter. + """ + + if self.sound is None and sound is None: + raise NotImplementedError("Silent Animals are not supported!") + + out_sound = self.sound if sound is None else sound + print(self.says_str.format(name=self.name, sound=out_sound)) \ No newline at end of file diff --git a/lesson20/exercise01.py b/lesson20/exercise01.py new file mode 100644 index 0000000..daab0fe --- /dev/null +++ b/lesson20/exercise01.py @@ -0,0 +1,18 @@ +import unittest +from waiter import Waiter, Barista + + +class WaiterTestCase(unittest.TestCase): + def setUp(self): + self.baristaObj = Barista("Bob", 10000) + + def test_init(self): + w = Waiter("Tom", 5000) + self.assertEqual(w.full_name, "Tom") + self.assertEqual(w.salary, 5000) + self.assertEqual(w.served_cnt, 0) + + def test_serve(self): + w = Waiter("Tom", 5000) + w.serve(50, self.baristaObj) + self.assertEqual(w.served_cnt, 50) diff --git a/lesson20/exercise02.py b/lesson20/exercise02.py new file mode 100644 index 0000000..c67a0c1 --- /dev/null +++ b/lesson20/exercise02.py @@ -0,0 +1,44 @@ +from graph import Graph +from queue import Queue + + +def breadth_first_search(graph, start, finish): + q = Queue() + discovered = [start] + q.enqueue(start) + parent = {} + while len(q) > 0: + v = q.dequeue() + if v == finish: + break + for neighbor in graph.neighbors(v): + if neighbor.descr not in discovered: + discovered += [neighbor.descr] + parent[neighbor.descr] = v + q.enqueue(neighbor.descr) + + path = [finish] + while path[0] != start: + path = [parent[path[0]]] + path + + print(path) + + +def main(): + facebook_users = Graph() + for user in ["Bob", "Anne", "Elisa", "Diana", "Carl"]: + facebook_users.add_vertex(user) + + facebook_users.add_edge("Carl", "Bob") + facebook_users.add_edge("Carl", "Elisa") + facebook_users.add_edge("Carl", "Diana") + facebook_users.add_edge("Diana", "Bob") + facebook_users.add_edge("Diana", "Anne") + facebook_users.add_edge("Elisa", "Anne") + facebook_users.add_edge("Anne", "Bob") + print(facebook_users) + print("\n") + breadth_first_search(facebook_users, "Carl", "Anne") + + +main() \ No newline at end of file diff --git a/lesson20/graph.py b/lesson20/graph.py new file mode 100644 index 0000000..1d4a715 --- /dev/null +++ b/lesson20/graph.py @@ -0,0 +1,40 @@ +class Node: + def __init__(self, descr="", neighbors=None): + self.descr = descr + if neighbors is None: + self.neighbors = [] + else: + self.neighbors = neighbors + + +class Graph: + def __init__(self): + self.nodes = [] + + def add_vertex(self, descr="", neighbors=None): + if neighbors is None: + neighbors = [] + self.nodes += [Node(descr, neighbors)] + + def __index_of(self, descr): + for i in range(len(self.nodes)): + if descr == self.nodes[i].descr: + return i + + def add_edge(self, descr1, descr2): + index1 = self.__index_of(descr1) + index2 = self.__index_of(descr2) + self.nodes[index1].neighbors += [self.nodes[index2]] + self.nodes[index2].neighbors += [self.nodes[index1]] + + def neighbors(self, descr): + return self.nodes[self.__index_of(descr)].neighbors + + def __str__(self): + st = "" + for node in self.nodes: + st += f"\n{node.descr}: " + for neighbor in node.neighbors: + st += f" {neighbor.descr}" + + return st \ No newline at end of file diff --git a/lesson20/lesson20.exercise02/exercise03.py b/lesson20/lesson20.exercise02/exercise03.py new file mode 100644 index 0000000..02ad65c --- /dev/null +++ b/lesson20/lesson20.exercise02/exercise03.py @@ -0,0 +1,211 @@ +from teachers import Teachers +from pupils import Pupils +from lessons import Lessons + + +def main(): + + pupils = Pupils() + teachers = Teachers() + lessons = Lessons() + + while True: + print("\n===============") + print(" MENU ") + + print("1 - Manage Pupils") + print("2 - Manage Teachers") + print("3 - Manage Lessons") + print("4 - Exit") + choice = int(input("Pick one: ")) + + if choice == 1: + print("\n===============") + print(" PUPILS MENU ") + + print("1 - Create Pupil") + print("2 - Print Pupil(s)") + print("3 - Update Pupil") + print("4 - Delete Pupil") + pupils_choice = int(input("Pick one: ")) + + if pupils_choice == 1: + print("NEW PUPIL") + print("===========") + pupil = pupils.create_pupil() + if pupil is None: + continue + else: + print("NEW PUPIL") + print(pupil) + + elif pupils_choice == 2: + print("\n===============") + print(" SUB-MENU (PRINT) ") + print("1 - Print Pupil") + print("2 - Print all pupils (details)") + print("3 - Print all pupils (just the names)") + print_choice = input("Give your choice: ") + if print_choice.strip().isdigit(): + print_choice = int(print_choice) + else: + print("Wrong input!") + continue + + if print_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Pupil does not exist (with this id)") + else: + print(" PUPIL ") + print(pupil) + + elif print_choice == 2: + print(pupils) + elif print_choice == 3: + pupils.print_pupils_names() + else: + print("Wrong input! ") + continue + + elif pupils_choice == 3: + print("\n===============") + print(" SUB-MENU (UPDATE) ") + print("1 - Update Pupil (search by id)") + print("2 - Update Pupil (search by surname)") + update_choice = input("Give your choice: ") + if update_choice.strip().isdigit(): + update_choice = int(update_choice) + else: + print("Wrong input!") + continue + + if update_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif update_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: update + pupils.pupil_update(pupil) + + elif pupils_choice == 4: + print("\n===============") + print(" SUB-MENU (DELETE) ") + print("1 - Delete Pupil (search by id)") + print("2 - Delete Pupil (search by surname)") + delete_choice = input("Give your choice: ") + if delete_choice.strip().isdigit(): + delete_choice = int(delete_choice) + else: + print("Wrong input!") + continue + + if delete_choice == 1: + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + if pupil is None: + print("Error! There is no pupil with this id!") + continue + elif delete_choice == 2: + surname = input("Give surname: ") + matching_pupils = pupils.search_pupil_by_surname(surname) + if not matching_pupils: + print("No matching pupils with this surname!") + continue + elif len(matching_pupils) == 1: + pupil = matching_pupils[0] + else: + for p in matching_pupils: + print(p) + print(f"id = {p['id']}") + print("-" * 15) + pupil_id = int(input("Give id: ")) + pupil = pupils.search_pupil_by_id(pupil_id) + + # pupil: delete + pupils.delete_pupil_by_id(pupil.pupil_id, lessons) + + elif choice == 2: + print("\n===============") + print(" TEACHERS MENU ") + + print("1 - Create Teacher") + print("2 - Print Teacher(s)") + print("3 - Update Teacher") + print("4 - Delete Teacher") + teacher_choice = int(input("Pick one: ")) + + if teacher_choice == 1: + first_name = input("Give name: ") + surname = input("Give surname: ") + teachers.create_teacher(first_name, surname) + elif teacher_choice == 2: + teacher_id = int(input("Give id: ")) + teacher = teachers.read_teacher(teacher_id) + if teacher is None: + print("No such teacher exists!") + else: + print(teacher) + elif teacher_choice == 3: + teacher_id = int(input("Give id: ")) + teachers.update_teacher(teacher_id) + elif teacher_choice == 4: + teacher_id = int(input("Give id: ")) + teachers.delete_teacher(teacher_id, lessons) + + elif choice == 3: + print("\n===============") + print(" LESSONS MENU ") + + print("1 - Create Lesson") + print("2 - Print Lesson") + print("3 - Update Lesson") + print("4 - Delete Lesson") + lesson_choice = int(input("Pick one: ")) + + if lesson_choice == 1: + lesson_name = input("Give lesson name: ") + lessons.create_lesson(lesson_name) + elif lesson_choice == 2: + lesson_id = int(input("Give id: ")) + lesson = lessons.read_lesson(lesson_id) + if lesson is None: + print("No such lesson exists!") + else: + lesson.print_lesson_details(teachers, pupils) + elif lesson_choice == 3: + lesson_id = int(input("Give id: ")) + lessons.update_lesson(lesson_id, teachers, pupils) + elif lesson_choice == 4: + lesson_id = int(input("Give id: ")) + lessons.delete_lesson(lesson_id) + + + + elif choice == 4: + print("Bye bye!") + pupils.save_pupils_data() + teachers.save_teachers_data() + lessons.save_lessons_data() + break + + +main() \ No newline at end of file diff --git a/lesson20/lesson20.exercise02/lesson.py b/lesson20/lesson20.exercise02/lesson.py new file mode 100644 index 0000000..b422372 --- /dev/null +++ b/lesson20/lesson20.exercise02/lesson.py @@ -0,0 +1,38 @@ +from teachers import Teachers +from pupils import Pupils + + +class Lesson: + def __init__(self, lesson_name="", lesson_id=-1): + self.lesson_name = lesson_name + self.teacher_ids = [] + self.pupil_ids = [] + self.lesson_id = lesson_id + + def from_dict(self, lesson_dict): + self.lesson_name = lesson_dict["lesson_name"] + self.teacher_ids = lesson_dict["teacher_ids"] + self.pupil_ids = lesson_dict["pupil_ids"] + self.lesson_id = lesson_dict["lesson_id"] + + def to_dict(self): + lesson_dict = {"lesson_name": self.lesson_name, + "teacher_ids": self.teacher_ids, + "pupil_ids": self.pupil_ids, + "lesson_id": self.lesson_id + } + + return lesson_dict + + def print_lesson_details(self, teachers, pupils): + print(f"LESSON: {self.lesson_name}") + print("=========") + print("TEACHERS: ") + for teacher_id in self.teacher_ids: + teacher = teachers.read_teacher(teacher_id) + print(f"{teacher.first_name} {teacher.surname}") + print("STUDENTS: ") + for pupil_id in self.pupil_ids: + pupil = pupils.search_pupil_by_id(pupil_id) + print(f"{pupil.first_name} {pupil.last_name}") + diff --git a/lesson20/lesson20.exercise02/lessons.json b/lesson20/lesson20.exercise02/lessons.json new file mode 100644 index 0000000..15db2bb --- /dev/null +++ b/lesson20/lesson20.exercise02/lessons.json @@ -0,0 +1 @@ +[{"lesson_name": "Algorithms", "teacher_ids": [1001], "pupil_ids": [1001, 1002], "lesson_id": 1001}, {"lesson_name": "AS", "teacher_ids": [], "pupil_ids": [], "lesson_id": 1002}] \ No newline at end of file diff --git a/lesson20/lesson20.exercise02/lessons.py b/lesson20/lesson20.exercise02/lessons.py new file mode 100644 index 0000000..c9dfb6b --- /dev/null +++ b/lesson20/lesson20.exercise02/lessons.py @@ -0,0 +1,101 @@ +import json +from lesson import Lesson + +class Lessons: + def __init__(self): + try: + with open("lessons.json") as f: + lessons_list = json.load(f) + + self.lessons = [] + for lesson_dict in lessons_list: + l = Lesson() + l.from_dict(lesson_dict) + self.lessons += [l] + except FileNotFoundError: + self.lessons = [] + + def save_lessons_data(self): + list_to_write = [] + for lesson in self.lessons: + list_to_write += [lesson.to_dict()] + + with open("lessons.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.lessons: + return 1001 + else: + ids = [] + for l in self.lessons: + ids.append(l.lesson_id) + return max(ids) + 1 + + def create_lesson(self, lesson_name): + for lesson in self.lessons: + if lesson.lesson_name == lesson_name: + print("Error. Lesson already exists! ") + return None + + l = Lesson(lesson_name, self.next_id()) + self.lessons.append(l) + return l + + def read_lesson(self, lesson_id): + for lesson in self.lessons: + if lesson_id == lesson.lesson_id: + return lesson + else: + return None + + def update_lesson(self, lesson_id, teachers, pupils): + for lesson in self.lessons: + if lesson_id == lesson.lesson_id: + lesson.print_lesson_details(teachers, pupils) + choice = int(input("Update 1-name, 2-teachers, 3-pupils: ")) + if choice == 1: + lesson.lesson_name = input("Give new name: ") + elif choice == 2: + upd_teacher_choice = int(input("Updating lesson teachers: 1-add, 2-remove: ")) + if upd_teacher_choice == 1: + print("Teachers(not in lesson): ") + for teacher in teachers.teachers: + if teacher.teacher_id not in lesson.teacher_ids: + print(f"{teacher.teacher_id}-{teacher.first_name} {teacher.surname}") + upd_teacher_id = int(input("Pick the (id) to add: ")) + lesson.teacher_ids.append(upd_teacher_id) + elif upd_teacher_choice == 2: + print("Lesson Teachers: ") + for teacher_id in lesson.teacher_ids: + teacher = teachers.read_teacher(teacher_id) + print(f"{teacher.teacher_id}-{teacher.first_name} {teacher.surname}") + upd_teacher_id = int(input("Pick the (id) to delete: ")) + lesson.teacher_ids.remove(upd_teacher_id) + elif choice == 3: + upd_pupil_choice = int(input("Updating lesson pupils: 1-add, 2-remove: ")) + if upd_pupil_choice == 1: + print("Pupils(not in lesson): ") + for pupil in pupils.pupils: + if pupil.pupil_id not in lesson.pupil_ids: + print(f"{pupil.pupil_id}-{pupil.first_name} {pupil.last_name}") + upd_pupil_id = int(input("Pick the (id) to add: ")) + lesson.pupil_ids.append(upd_pupil_id) + elif upd_pupil_choice == 2: + print("Lesson Pupils: ") + for pupil_id in lesson.pupil_ids: + pupil = pupils.search_pupil_by_id(pupil_id) + print(f"{pupil.pupil_id}-{pupil.first_name} {pupil.last_name}") + upd_pupil_id = int(input("Pick the (id) to delete: ")) + lesson.pupil_ids.remove(upd_pupil_id) + break + + def delete_lesson(self, lesson_id): + for i in range(len(self.lessons)): + if lesson_id == self.lessons[i].lesson_id: + self.lessons.pop(i) + return + else: + print("No lesson with this id!") + + diff --git a/lesson20/lesson20.exercise02/pupil.py b/lesson20/lesson20.exercise02/pupil.py new file mode 100644 index 0000000..ecde02f --- /dev/null +++ b/lesson20/lesson20.exercise02/pupil.py @@ -0,0 +1,42 @@ +class Pupil: + def __init__(self, first_name="", last_name="", fathers_name="", + age=-1, class_name="", id_number=None, pupil_id=-1): + self.first_name = first_name + self.last_name = last_name + self.fathers_name = fathers_name + self.age = age + self.class_name = class_name + self.id_number = id_number + self.pupil_id = pupil_id + + def from_dict(self, pupil_dict): + self.first_name = pupil_dict["first_name"] + self.last_name = pupil_dict["last_name"] + self.fathers_name = pupil_dict["fathers_name"] + self.age = pupil_dict["age"] + self.class_name = pupil_dict["class_name"] + if "id_number" in pupil_dict: + self.id_number = pupil_dict["id_number"] + self.pupil_id = pupil_dict["pupil_id"] + + def to_dict(self): + pupil_dict = {"first_name": self.first_name, + "last_name": self.last_name, + "fathers_name": self.fathers_name, + "age": self.age, + "class_name": self.class_name, + "pupil_id": self.pupil_id} + if self.id_number is not None: + pupil_dict["id_number"] = self.id_number + return pupil_dict + + def __str__(self): + + st = f"\nName : {self.first_name}" + st += f"\nLast Name : {self.last_name}" + st += f"\nFather's Name : {self.fathers_name}" + st += f"\nAge : {self.age}" + st += f"\nClass : {self.class_name}" + if self.id_number is not None: + st += f"\nID card number: {self.id_number}" + return st diff --git a/lesson20/lesson20.exercise02/pupils.json b/lesson20/lesson20.exercise02/pupils.json new file mode 100644 index 0000000..d8ffad4 --- /dev/null +++ b/lesson20/lesson20.exercise02/pupils.json @@ -0,0 +1 @@ +[{"first_name": "John", "last_name": "Cm", "fathers_name": "Wick", "age": 44, "class_name": 1, "pupil_id": 1001, "id_number": "12131234"}, {"first_name": "Bob", "last_name": "Hope", "fathers_name": "Charles", "age": 12, "class_name": 2, "pupil_id": 1002}, {"first_name": "1", "last_name": "1", "fathers_name": "1", "age": 1, "class_name": 1, "pupil_id": 1003}] \ No newline at end of file diff --git a/lesson20/lesson20.exercise02/pupils.py b/lesson20/lesson20.exercise02/pupils.py new file mode 100644 index 0000000..07ed429 --- /dev/null +++ b/lesson20/lesson20.exercise02/pupils.py @@ -0,0 +1,124 @@ +from pupil import Pupil +import json + + +class Pupils: + def __init__(self): + try: + with open("pupils.json") as f: + pupils_list = json.load(f) + + self.pupils = [] + for pupil_dict in pupils_list: + p = Pupil() + p.from_dict(pupil_dict) + self.pupils += [p] + except FileNotFoundError: + self.pupils = [] + + def __str__(self): + st = "" + for pupil in self.pupils: + st += "\n" + "=" * 15 + st += str(pupil) + return st + + def save_pupils_data(self): + list_to_write = [] + for pupil in self.pupils: + list_to_write += [pupil.to_dict()] + + with open("pupils.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.pupils: + return 1001 + else: + ids = [] + for p in self.pupils: + ids.append(p.pupil_id) + return max(ids) + 1 + + def create_pupil(self): + first_name = input("Give name: ") + last_name = input("Give surname: ") + fathers_name = input("Give father's name: ") + + for p in self.pupils: + if first_name == p.first_name and last_name == p.last_name and fathers_name == p.fathers_name: + print("This pupil already exists.") + ch = input("Do you want to continue? (y-yes, n-no): ") + if ch == "n": + return None + + age = int(input("Give age: ")) + class_name = int(input("Give class: ")) + id_card = input("Does he/she has an id card: (y-true, n-false): ") + if id_card == "y": + id_number = input("Give id card number: ") + else: + id_number = None + + pupil = Pupil(first_name,last_name,fathers_name,age,class_name,id_number,self.next_id()) + + self.pupils.append(pupil) + return pupil + + def search_pupil_by_id(self, pupil_id): + for pupil in self.pupils: + if pupil_id == pupil.pupil_id: + return pupil + return None + + def search_pupil_by_surname(self, last_name): + match_pupils = [] + for pupil in self.pupils: + if last_name == pupil.last_name: + match_pupils.append(pupil) + return match_pupils + + def pupil_update(self, pupil): + print(pupil) + print("=" * 15) + print("1-name") + print("2-surname") + print("3-father's name") + print("4-age") + print("5-class") + print("6-id number") + print("=" * 15) + update_choice = int(input("Pick something to update: ")) + if update_choice == 1: + pupil.first_name = input("Give new name: ") + elif update_choice == 2: + pupil.last_name = input("Give new surname: ") + elif update_choice == 3: + pupil.fathers_name = input("Give new father's name: ") + elif update_choice == 4: + pupil.age = input("Give new age: ") + elif update_choice == 5: + pupil.class_name = input("Give new class: ") + elif update_choice == 6: + pupil.id_number = input("Give new id number: ") + + print("=" * 15) + print(pupil) + print("Pupil updated! ") + + def delete_pupil_by_id(self, pupil_id, lessons): + for i in range(len(self.pupils)): + if pupil_id == self.pupils[i].pupil_id: + self.pupils.pop(i) + print("Pupil deleted!") + for lesson in lessons.lessons: + if pupil_id in lesson.pupil_ids: + lesson.pupil_ids.remove(pupil_id) + return + else: + print("No teacher with this id!") + + def print_pupils_names(self): + for pupil in self.pupils: + print(f"{pupil.first_name} {pupil.fathers_name[0]}. {pupil.last_name}") + diff --git a/lesson20/lesson20.exercise02/teacher.py b/lesson20/lesson20.exercise02/teacher.py new file mode 100644 index 0000000..bfdfb5e --- /dev/null +++ b/lesson20/lesson20.exercise02/teacher.py @@ -0,0 +1,22 @@ +class Teacher: + def __init__(self, first_name="", surname="", teacher_id=-1): + self.first_name = first_name + self.surname = surname + self.teacher_id = teacher_id + + def from_dict(self, teacher_dict): + self.first_name = teacher_dict["first_name"] + self.surname = teacher_dict["surname"] + self.teacher_id = teacher_dict["teacher_id"] + + def to_dict(self): + teacher_dict = {"first_name": self.first_name, + "surname": self.surname, + "teacher_id":self.teacher_id} + return teacher_dict + + def __str__(self): + st = f"Name : {self.first_name}" + st += f"\nSurname: {self.surname}" + st += f"\nid : {self.teacher_id}" + return st diff --git a/lesson20/lesson20.exercise02/teachers.json b/lesson20/lesson20.exercise02/teachers.json new file mode 100644 index 0000000..0d14dd5 --- /dev/null +++ b/lesson20/lesson20.exercise02/teachers.json @@ -0,0 +1 @@ +[{"first_name": "Severus", "surname": "Snape", "teacher_id": 1001}, {"first_name": "Charles", "surname": "Xavier", "teacher_id": 1002}, {"first_name": "Sergio", "surname": "Marquina", "teacher_id": 1003}, {"first_name": "AA", "surname": "AA", "teacher_id": 1004}] \ No newline at end of file diff --git a/lesson20/lesson20.exercise02/teachers.py b/lesson20/lesson20.exercise02/teachers.py new file mode 100644 index 0000000..b60db81 --- /dev/null +++ b/lesson20/lesson20.exercise02/teachers.py @@ -0,0 +1,75 @@ +import json +from teacher import Teacher + + +class Teachers: + def __init__(self): + try: + with open("teachers.json") as f: + teachers_list = json.load(f) + + self.teachers = [] + for teacher_dict in teachers_list: + t = Teacher() + t.from_dict(teacher_dict) + self.teachers += [t] + except FileNotFoundError: + self.teachers = [] + + def save_teachers_data(self): + list_to_write = [] + for teacher in self.teachers: + list_to_write += [teacher.to_dict()] + + with open("teachers.json", "w") as f: + json.dump(list_to_write, f) + + def next_id(self): + if not self.teachers: + return 1001 + else: + ids = [] + for t in self.teachers: + ids.append(t.teacher_id) + return max(ids) + 1 + + def create_teacher(self,first_name, surname): + for teacher in self.teachers: + if teacher.first_name == first_name and teacher.surname == surname: + print("Error. Teacher already exists! ") + return None + + t = Teacher(first_name, surname, self.next_id()) + self.teachers.append(t) + return t + + def read_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + return teacher + else: + return None + + def update_teacher(self, teacher_id): + for teacher in self.teachers: + if teacher_id == teacher.teacher_id: + print(teacher) + choice = int(input("Update 1-name, 2-surname: ")) + if choice == 1: + teacher.first_name = input("Give new name: ") + elif choice == 2: + teacher.surname = input("Give new surname: ") + return + + def delete_teacher(self, teacher_id, lessons): + for i in range(len(self.teachers)): + if teacher_id == self.teachers[i].teacher_id: + self.teachers.pop(i) + + for lesson in lessons.lessons: + if teacher_id in lesson.teacher_ids: + lesson.teacher_ids.remove(teacher_id) + else: + print("No teacher with this id!") + + diff --git a/lesson20/python20.testing.pdf b/lesson20/python20.testing.pdf new file mode 100644 index 0000000..729e7aa Binary files /dev/null and b/lesson20/python20.testing.pdf differ diff --git a/lesson20/queue.py b/lesson20/queue.py new file mode 100644 index 0000000..079b6c3 --- /dev/null +++ b/lesson20/queue.py @@ -0,0 +1,31 @@ +class Queue: + def __init__(self): + self.array = [] + + def enqueue(self, elem): + self.array.append(elem) + + def dequeue(self): + if not self.array: + return None + else: + return self.array.pop(0) + + def __str__(self): + return ", ".join(self.array) + + def __add__(self, other): + new_q = Queue() + new_q.array = self.array[:] + new_q.enqueue(other) + return new_q + + def __iadd__(self, other): + self.enqueue(other) + return self + + def __neg__(self): + return self.dequeue() + + def __len__(self): + return len(self.array) \ No newline at end of file diff --git a/lesson20/teacher.py b/lesson20/teacher.py new file mode 100644 index 0000000..bfdfb5e --- /dev/null +++ b/lesson20/teacher.py @@ -0,0 +1,22 @@ +class Teacher: + def __init__(self, first_name="", surname="", teacher_id=-1): + self.first_name = first_name + self.surname = surname + self.teacher_id = teacher_id + + def from_dict(self, teacher_dict): + self.first_name = teacher_dict["first_name"] + self.surname = teacher_dict["surname"] + self.teacher_id = teacher_dict["teacher_id"] + + def to_dict(self): + teacher_dict = {"first_name": self.first_name, + "surname": self.surname, + "teacher_id":self.teacher_id} + return teacher_dict + + def __str__(self): + st = f"Name : {self.first_name}" + st += f"\nSurname: {self.surname}" + st += f"\nid : {self.teacher_id}" + return st diff --git a/lesson20/temp.py b/lesson20/temp.py new file mode 100644 index 0000000..7a35da5 --- /dev/null +++ b/lesson20/temp.py @@ -0,0 +1,84 @@ +from queue import Queue + + +class Node: + def __init__(self, descr="", neighbors=None): + self.descr = descr + if neighbors is None: + self.neighbors = [] + else: + self.neighbors = neighbors + + +class Graph: + def __init__(self): + self.nodes=[] + + def add_vertex(self, descr="", neighbors=None): + if neighbors is None: + neighbors = [] + self.nodes.append(Node(descr, neighbors)) + + def index_of(self, descr): + for i in range(len(self.nodes)): + if descr == self.nodes[i].descr: + return i + return -1 + + def add_edge(self, descr1, descr2): + index1 = self.index_of(descr1) + index2 = self.index_of(descr2) + self.nodes[index1].neighbors.append(self.nodes[index2]) + self.nodes[index2].neighbors.append(self.nodes[index1]) + + def neighbors(self, descr): + return self.nodes[self.index_of(descr)].neighbors + + def __str__(self): + st = "" + for node in self.nodes: + st += f"\n{node.descr}: " + for neighbor in node.neighbors: + st += f"{neighbor.descr} " + return st + + +def breadth_first_search(graph, start, finish): + q = Queue() + discovered = [start] + q.enqueue(start) + parent = {} + while len(q)>0: + v = q.dequeue() + if v == finish: + break + for neighbor in graph.neighbors(v): + if neighbor.descr not in discovered: + discovered += [neighbor.descr] + parent[neighbor.descr] = v + q.enqueue(neighbor.descr) + + path = [finish] + while path[0] != start: + path = [parent[path[0]]] + path + + print(path) + + +def main(): + facebook_users = Graph() + for user in ["Bob", "Anne", "Elisa", "Diana", "Carl"]: + facebook_users.add_vertex(user) + + facebook_users.add_edge("Carl", "Diana") + facebook_users.add_edge("Carl", "Elisa") + facebook_users.add_edge("Carl", "Bob") + facebook_users.add_edge("Diana", "Bob") + facebook_users.add_edge("Diana", "Anne") + facebook_users.add_edge("Elisa", "Anne") + facebook_users.add_edge("Anne", "Bob") + print(facebook_users) + breadth_first_search(facebook_users, "Anne", "Diana") + + +main() diff --git a/lesson20/test_args.py b/lesson20/test_args.py new file mode 100644 index 0000000..f31779a --- /dev/null +++ b/lesson20/test_args.py @@ -0,0 +1,10 @@ +import unittest +from args import my_sum # import function to be tested + + +class MySumTestCase(unittest.TestCase): + def test_1(self): + self.assertEqual(my_sum(1, 2, 3), 6) + + def test_2(self): + self.assertEqual(my_sum(), 0) diff --git a/lesson20/test_teacher.py b/lesson20/test_teacher.py new file mode 100644 index 0000000..23f3b3b --- /dev/null +++ b/lesson20/test_teacher.py @@ -0,0 +1,31 @@ +import unittest +from teacher import Teacher + + +class TeacherTestCase(unittest.TestCase): + def setUp(self) -> None: + self.bush = Teacher("George", "Bush") + self.clinton = Teacher("Bill", "Clinton", 1001) + + def test_from_dict(self): + dict_arg = { + "first_name": "George", + "surname": "Bush", + "teacher_id": -1 + } + t = Teacher() + t.from_dict(dict_arg) + self.assertEqual(self.bush.first_name, t.first_name) + self.assertEqual(self.bush.surname, t.surname) + self.assertEqual(self.bush.teacher_id, t.teacher_id) + + def test_to_dict(self): + dict_arg = { + "first_name": "George", + "surname": "Bush", + "teacher_id": -1 + } + + self.assertEqual(self.bush.to_dict()["first_name"], dict_arg["first_name"]) + self.assertEqual(self.bush.to_dict()["surname"], dict_arg["surname"]) + self.assertEqual(self.bush.to_dict()["teacher_id"], dict_arg["teacher_id"]) diff --git a/lesson20/waiter.py b/lesson20/waiter.py new file mode 100644 index 0000000..9422485 --- /dev/null +++ b/lesson20/waiter.py @@ -0,0 +1,60 @@ +from random import randrange, seed +from datetime import datetime + + +class Person: + def __init__(self, full_name, salary): + self.full_name = full_name + self.salary = salary + self.served_cnt = 0 + + def report(self): + print(self.full_name + " served " + str(self.served_cnt) + " customers.") + +class Waiter(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def serve(self, customers, barista): + self.served_cnt += customers + print("Waiter " + self.full_name + " served " + str(customers) + " customers") + barista.prepare(customers) + + +class Barista(Person): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + def prepare(self, customers): + print("Barista " + self.full_name + " served " + str(customers) + " customers") + self.served_cnt += customers + + +class Owner(Waiter, Barista): + def __init__(self, full_name, salary): + Person.__init__(self, full_name, salary) + + + +def main(): + seed(datetime.now()) + + o = Owner("owner", 100000) + w1 = Waiter("waiter-1", 200000) + w2 = Waiter("waiter-1", 200000) + b = Barista("barista", 300000) + + waiters = [o, w1, w2] + baristas = [o, b] + + for _ in range(10): + waiters[randrange(3)].serve(randrange(1,5+1), baristas[randrange(2)]) + + print("") + o.report() + w1.report() + w2.report() + b.report() + +main() +