├── .idea └── .gitignore ├── 1. Lists as Stacks and Queues ├── Lists as Stacks and Queues - Exercise │ ├── 10_cups_and_bottles.py │ ├── 1_reverse_numbers.py │ ├── 2_stacked_queries.py │ ├── 3_fast_food.py │ ├── 4_fashion_boutique.py │ ├── 5_truck_tour.py │ ├── 6_balanced_parentheses.py │ ├── 7_robotics.py │ ├── 8_crossroads.py │ └── 9_key_revolver.py └── Lists as Stacks and Queues - Lab │ ├── 1_reverse_strings.py │ ├── 2_matching_parentheses.py │ ├── 3_supermarket.py │ ├── 4_water_dispenser.py │ ├── 5_hot_potato.py │ └── __init__.py ├── 10. Exam ├── 1. Offroad Challenge.py ├── 2. Fishing Competition.py └── 3. Team Lineup.py ├── 2. Tuples and Sets ├── Tuples and Sets - Exercise │ ├── 1_unique_usernames.py │ ├── 2_sets_of_elements.py │ ├── 3_periodic_table.py │ ├── 4_count_symbols.py │ ├── 5_longest_Intersection.py │ └── 6_battle_of_names.py └── Tuples and Sets - Lab │ ├── 1_count_same_values.py │ ├── 2_students_grades.py │ ├── 3_record_unique_names.py │ ├── 4_parking_lot.py │ ├── 5_softuni_party.py │ └── 6_summation_pairs.py ├── 3. Stacks, Queues, Tuples and Sets └── Stacks, Queues, Tuples and Sets - Exercise │ ├── 1_numbers.py │ ├── 2_expression_evaluator.py │ ├── 3_milkshakes.py │ ├── 4_honey.py │ ├── 5_santas_present_factory.py │ └── 6_paint_colors.py ├── 4. Multidimensional Lists ├── Multidimensional Lists - Exercise 1 │ ├── 10_radioactive_mutate_vampire_bunnies.py │ ├── 1_diagonals.py │ ├── 2_diagonal_difference.py │ ├── 3_2x2_squares_in_matrix.py │ ├── 4_maximal_sum.py │ ├── 5_matrix_of_palindromes.py │ ├── 6_matrix_shuffling.py │ ├── 7_snake_moves.py │ ├── 8_bombs.py │ └── 9_miner.py ├── Multidimensional Lists - Exercise 2 │ ├── 1_flatten_lists.py │ ├── 2_matrix_modification.py │ ├── 3_knight_game.py │ ├── 4_easter_bunny.py │ ├── 5_alice_in_wonderland.py │ ├── 6_range_day.py │ └── 7_present_delivery.py └── Multidimensional Lists - Lab │ ├── 1_sum_matrix_elements.py │ ├── 2_even_Matrix.py │ ├── 3_flattening_matrix.py │ ├── 4_sum_matrix_columns.py │ ├── 5_primary_diagonal.py │ ├── 6_symbol_in_matrix.py │ └── 7_square_with_maximum_sum.py ├── 5. Functions Advanced ├── Functions Advanced - Exercise │ ├── 10_fill_the_box.py │ ├── 11_math_operations.py │ ├── 1_negative_vs_positive.py │ ├── 2_keyword_arguments_length.py │ ├── 3_even_or_odd.py │ ├── 4_numbers_filter.py │ ├── 5_concatenate.py │ ├── 6_function_executor.py │ ├── 7_grocery.py │ ├── 8_age_assignment.py │ └── 9_recursion_palindrome.py └── Functions Advanced - Lab │ ├── 1_multiplication_function.py │ ├── 2_person_info.py │ ├── 3_cheese_showcase.py │ ├── 4_rectangle.py │ ├── 5_operate.py │ └── 6_recursive_power.py ├── 6. Error Handling ├── Error-Handling - Exercise │ ├── 01_numbers_dictionary.py │ ├── 02_email_validator.py │ └── Error-Handling - Exercise.rar └── Error-Handling - Lab │ ├── 01_so_many_exceptions.py │ ├── 02_value_can_not_be_negative.py │ └── 03_repeat_text.py ├── 7. File Handling ├── File-Handling - Exercise │ ├── 01_even_lines.py │ ├── 02_line_numbers.py │ ├── 03_file_manipulator.py │ ├── 04_directory_traversal.py │ ├── File-Handling - Exercise.rar │ └── text.txt └── File-Handling - Lab │ ├── 01_file_opener.py │ ├── 02_file_reader.py │ ├── 03_file_writer.py │ ├── 04_file_delete.py │ ├── 05_word_count.py │ ├── my_first_file.txt │ ├── numbers.txt │ ├── text.txt │ └── words.txt └── README.md /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/10_cups_and_bottles.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | cups_capacity = deque(int(x) for x in input().split()) 4 | filled_bottles = [int(x) for x in input().split()] 5 | 6 | wasted_litters_of_water = 0 7 | 8 | while cups_capacity and filled_bottles: 9 | bottle = filled_bottles.pop() 10 | cups_capacity[0] -= bottle 11 | if cups_capacity[0] <= 0: 12 | wasted_litters_of_water += abs(cups_capacity[0]) 13 | del cups_capacity[0] 14 | 15 | if cups_capacity: 16 | print(f"Cups: {' '.join(str(x) for x in cups_capacity)}") 17 | else: 18 | print(f"Bottles: {' '.join(str(x) for x in filled_bottles)}") 19 | 20 | print(f"Wasted litters of water: {wasted_litters_of_water}") 21 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/1_reverse_numbers.py: -------------------------------------------------------------------------------- 1 | numbers = input().split() 2 | for num in range(len(numbers)): 3 | print(f"{numbers.pop()}", end=" ") 4 | 5 | 6 | # while numbers: 7 | # print(f"{numbers.pop()}", end=" ") 8 | 9 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/2_stacked_queries.py: -------------------------------------------------------------------------------- 1 | number_of_commands = int(input()) 2 | 3 | stack_queries = [] 4 | 5 | 6 | def check_stack_size(): 7 | if len(stack_queries) != 0: 8 | return True 9 | 10 | 11 | for _ in range(number_of_commands): 12 | command = input() 13 | if command.startswith("1"): 14 | __, number = command.split() 15 | stack_queries.append(int(number)) 16 | elif check_stack_size(): 17 | if command.startswith("2"): 18 | stack_queries.pop() 19 | elif command.startswith("3"): 20 | print(max(stack_queries)) 21 | elif command.startswith("4"): 22 | print(min(stack_queries)) 23 | 24 | print(", ".join(str(stack_queries.pop()) for n in range(len(stack_queries)))) 25 | 26 | 27 | # while stack_queries: 28 | # print_element = stack_queries.pop() 29 | # if stack_queries: 30 | # print(print_element, end=", ") 31 | # else: 32 | # print(print_element) 33 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/3_fast_food.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | quantity_of_the_food = int(input()) 4 | orders = deque(int(x) for x in input().split()) 5 | 6 | 7 | print(max(orders)) 8 | while orders: 9 | order_number = orders.popleft() 10 | if quantity_of_the_food - order_number >= 0: 11 | quantity_of_the_food -= order_number 12 | else: 13 | print(f"Orders left: {order_number}", *orders) 14 | break 15 | else: 16 | print("Orders complete") 17 | 18 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/4_fashion_boutique.py: -------------------------------------------------------------------------------- 1 | clothes_in_box = [int(x) for x in input().split()] 2 | rack_capacity = int(input()) 3 | current_rack = rack_capacity 4 | used_racks = 1 5 | while clothes_in_box: 6 | cloth_size = clothes_in_box.pop() 7 | if cloth_size <= current_rack: 8 | current_rack -= cloth_size 9 | else: 10 | used_racks += 1 11 | current_rack = rack_capacity 12 | current_rack -= cloth_size 13 | 14 | print(used_racks) 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/5_truck_tour.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | petrol_pumps = int(input()) 4 | 5 | pumps = deque() 6 | for _ in range(petrol_pumps): 7 | pump_info = [int(x) for x in input().split()] 8 | pumps.append(pump_info) 9 | 10 | 11 | for attempt in range(petrol_pumps): 12 | tank = 0 13 | full_circle = True 14 | for fuel, distance in pumps: 15 | tank += fuel 16 | if distance > tank: 17 | full_circle = False 18 | break 19 | else: 20 | tank -= distance 21 | if full_circle: 22 | print(attempt) 23 | break 24 | else: 25 | pumps.append(pumps.popleft()) 26 | 27 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/6_balanced_parentheses.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | parentheses = deque(input()) 4 | open_per = deque() 5 | balanced = True 6 | while parentheses: 7 | check_par = parentheses.popleft() 8 | if check_par in "{[(": 9 | open_per.append(check_par) 10 | elif not open_per: 11 | balanced = False 12 | break 13 | else: 14 | if f"{open_per.pop() + check_par}" not in "{}()[]": 15 | balanced = False 16 | break 17 | 18 | if balanced and not open_per: 19 | print("YES") 20 | else: 21 | print("NO") -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/7_robotics.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from collections import deque 3 | 4 | 5 | class Factory: 6 | robots = [] 7 | staring_time = None 8 | products_on_line = deque() 9 | 10 | def __init__(self, name: str, process_time: int): 11 | self.name = name 12 | self.process_time = process_time 13 | self.busy_until = self.staring_time 14 | 15 | def getting_item(self): 16 | self.busy_until = self.staring_time + datetime.timedelta(0, self.process_time) 17 | 18 | @staticmethod 19 | def adding_time(): 20 | Factory.staring_time += datetime.timedelta(0, 1) 21 | 22 | 23 | robot_data_list = input().split(";") 24 | hours, minutes, seconds = [int(x) for x in input().split(":")] 25 | Factory.staring_time = datetime.datetime(100, 1, 1, hours, minutes, seconds) 26 | product = input() 27 | 28 | while product != "End": 29 | Factory.products_on_line.append(product) 30 | product = input() 31 | 32 | for robot_data in robot_data_list: 33 | name, process = [int(x) if x.isdigit() else x for x in robot_data.split("-")] 34 | Factory.robots.append(Factory(name, process)) 35 | 36 | while Factory.products_on_line: 37 | Factory.adding_time() 38 | item = Factory.products_on_line.popleft() 39 | 40 | for robot in Factory.robots: 41 | if Factory.staring_time >= robot.busy_until: 42 | robot.getting_item() 43 | print(f'{robot.name} - {item} [{Factory.staring_time.time()}]') 44 | break 45 | else: 46 | Factory.products_on_line.append(item) 47 | 48 | 49 | 50 | 51 | 52 | 53 | # import datetime 54 | # from collections import deque 55 | # 56 | # robot_data_list = input().split(";") 57 | # starting_time = input() 58 | # command_product = input() 59 | # hours, minutes, seconds = [int(x) for x in starting_time.split(":")] 60 | # starting_time = datetime.datetime(100, 1, 1, hours, minutes, seconds) 61 | # 62 | # 63 | # def adding_processing_time_to_robots(time_, star_time="No"): 64 | # global starting_time 65 | # if star_time != "No": 66 | # return starting_time + datetime.timedelta(0, time_) 67 | # starting_time += datetime.timedelta(0, time_) 68 | # return starting_time 69 | # 70 | # 71 | # product_line_robots = {} 72 | # for robot_info in robot_data_list: 73 | # name, busy_until = robot_info.split("-") 74 | # product_line_robots[name] = product_line_robots.get(name, {}) 75 | # product_line_robots[name]["process time"] = int(busy_until) 76 | # product_line_robots[name]["busy until"] = starting_time 77 | # 78 | # products_in_line = deque() 79 | # 80 | # while command_product != "End": 81 | # products_in_line.append(command_product) 82 | # command_product = input() 83 | # 84 | # while products_in_line: 85 | # adding_processing_time_to_robots(1) 86 | # item_to_process = products_in_line.popleft() 87 | # for robot in product_line_robots: 88 | # if starting_time >= product_line_robots[robot]["busy until"]: 89 | # product_line_robots[robot]["busy until"] = adding_processing_time_to_robots( 90 | # product_line_robots[robot]["process time"], "Yes") 91 | # print(f'{robot} - {item_to_process} [{starting_time.time()}]') 92 | # break 93 | # else: 94 | # products_in_line.append(item_to_process) 95 | # 96 | # 97 | # 98 | # 99 | # 100 | # 101 | 102 | 103 | # 104 | # from collections import deque 105 | # 106 | # 107 | # def convert_str_to_seconds(str_time): 108 | # hours, minutes, seconds = [int(x) for x in str_time.split(':')] 109 | # return hours * 60 * 60 + minutes * 60 + seconds 110 | # 111 | # 112 | # def convert_seconds_to_str_time(seconds): 113 | # hours = seconds // (60 * 60) 114 | # seconds %= (60 * 60) 115 | # minutes = seconds // 60 116 | # seconds %= 60 117 | # return f'{hours:02d}:{minutes:02d}:{seconds:02d}' 118 | # 119 | # 120 | # robots_data = input().split(';') 121 | # process_time_by_robot = {} 122 | # busy_until_by_robot = {} 123 | # 124 | # for robot_data in robots_data: 125 | # name, process_time = robot_data.split('-') 126 | # process_time_by_robot[name] = int(process_time) 127 | # busy_until_by_robot[name] = -1 128 | # 129 | # time = convert_str_to_seconds(input()) 130 | # items = deque() 131 | # line = input() 132 | # 133 | # while line != "End": 134 | # items.append(line) 135 | # line = input() 136 | # 137 | # while items: 138 | # time = (time + 1) % 24 * 60 * 60 139 | # item = items.popleft() 140 | # 141 | # for name, busy_until in busy_until_by_robot.items(): 142 | # if time >= busy_until: 143 | # busy_until_by_robot[name] = time + process_time_by_robot[name] 144 | # print(f'{name} - {item} [{convert_seconds_to_str_time(time)}]') 145 | # break 146 | # else: 147 | # items.append(item) 148 | # 149 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/8_crossroads.py: -------------------------------------------------------------------------------- 1 | from _collections import deque 2 | 3 | duration_green = int(input()) 4 | window = int(input()) 5 | line = input() 6 | cars = deque() 7 | cars_counter = 0 8 | crashed = False 9 | 10 | while line != "END": 11 | if line == "green": 12 | if cars: 13 | current_car = cars.popleft() 14 | left_seconds = duration_green - len(current_car) 15 | 16 | while left_seconds > 0: 17 | cars_counter += 1 18 | if not cars: 19 | break 20 | current_car = cars.popleft() 21 | left_seconds -= len(current_car) 22 | 23 | if left_seconds == 0: 24 | cars_counter += 1 25 | if window >= abs(left_seconds): 26 | if left_seconds < 0: 27 | cars_counter += 1 28 | else: 29 | index = window + left_seconds 30 | print(f"A crash happened!\n{current_car} was hit at {current_car[index]}.") 31 | crashed = True 32 | break 33 | else: 34 | cars.append(line) 35 | line = input() 36 | 37 | if not crashed: 38 | print(f"Everyone is safe.\n{cars_counter} total cars passed the crossroads.") 39 | 40 | 41 | 42 | 43 | 44 | 45 | # 46 | # 47 | # from collections import deque 48 | # 49 | # green_lift_duration = int(input()) 50 | # free_window_in_sec = int(input()) 51 | # car_or_command = input() 52 | # 53 | # car_q = deque() 54 | # passed_cars = 0 55 | # 56 | # while car_or_command != "END": 57 | # if car_or_command != "green": 58 | # car_q.append(car_or_command) 59 | # else: 60 | # if car_q: 61 | # green_lift_start = green_lift_duration 62 | # free_window_on_gree = free_window_in_sec 63 | # for _ in range(len(car_q)): 64 | # car_enter = False 65 | # car = car_q.popleft() 66 | # coming_tru_car = len(car) 67 | # if green_lift_start != 0: 68 | # green_lift_start -= coming_tru_car 69 | # car_enter = True 70 | # if green_lift_start < 0: 71 | # coming_tru_car = abs(green_lift_start) 72 | # green_lift_start = 0 73 | # else: 74 | # passed_cars += 1 75 | # continue 76 | # if coming_tru_car and car_enter: 77 | # coming_tru_car -= free_window_on_gree 78 | # if coming_tru_car > 0: 79 | # print(f"A crash happened!\n{car} was hit at {list(car)[-coming_tru_car]}.") 80 | # exit() 81 | # passed_cars += 1 82 | # break 83 | # 84 | # car_or_command = input() 85 | # 86 | # print(f"Everyone is safe.\n{passed_cars} total cars passed the crossroads.") 87 | # 88 | # 89 | # 90 | # 91 | # 92 | # 93 | # 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Exercise/9_key_revolver.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | bullet_price = int(input()) 4 | size_of_the_gun_barrel = int(input()) 5 | bullets = [int(x) for x in input().split()] 6 | locks = deque(int(x) for x in input().split()) 7 | intelligence = int(input()) 8 | 9 | barrel_count, shoot_count = 0, 0 10 | 11 | while bullets and locks: 12 | barrel_count += 1 13 | shoot_count += 1 14 | bullet = bullets.pop() 15 | if bullet <= locks[0]: 16 | locks.popleft() 17 | print("Bang!") 18 | else: 19 | print("Ping!") 20 | if barrel_count == size_of_the_gun_barrel and bullets: 21 | print("Reloading!") 22 | barrel_count = 0 23 | 24 | if locks: 25 | print(f"Couldn't get through. Locks left: {len(locks)}") 26 | else: 27 | earned_money = abs((shoot_count * bullet_price) - intelligence) 28 | print(f"{len(bullets)} bullets left. Earned ${earned_money}") -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/1_reverse_strings.py: -------------------------------------------------------------------------------- 1 | stack_list = list(input()) 2 | while stack_list: 3 | print(stack_list.pop(), end= "") 4 | 5 | 6 | # from collections import deque 7 | # stack = deque(input()) 8 | # stack.reverse() 9 | # print(*stack, sep="") 10 | 11 | 12 | 13 | 14 | # print(input()[::-1]) 15 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/2_matching_parentheses.py: -------------------------------------------------------------------------------- 1 | string_expression = input() 2 | 3 | per_stack = [] 4 | 5 | for index, char in enumerate(string_expression): 6 | if char == "(": 7 | per_stack.append(index) 8 | elif char == ")": 9 | start_index = per_stack.pop() 10 | print(string_expression[start_index:1+index]) 11 | 12 | 13 | # for index in range(len(string_expression)): 14 | # if string_expression[index] == "(": 15 | # per_stack.append(index) 16 | # elif string_expression[index] == ")": 17 | # start_index = per_stack.pop() 18 | # print(string_expression[start_index:1 + index]) -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/3_supermarket.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | name = input() 4 | 5 | supermarket_line = deque() 6 | 7 | 8 | def customers_to_paid(): 9 | for person in range(len(supermarket_line)): 10 | print(f"{supermarket_line.popleft()} ") 11 | 12 | # while supermarket_line: 13 | # print(f"{supermarket_line.popleft()} ") 14 | 15 | 16 | while name != "End": 17 | if name == "Paid": 18 | customers_to_paid() 19 | else: 20 | supermarket_line.append(name) 21 | name = input() 22 | 23 | 24 | print(f"{len(supermarket_line)} people remaining.") 25 | 26 | 27 | 28 | # data_input = input() 29 | # people_in_q = [] 30 | # while data_input != "End": 31 | # if data_input == "Paid": 32 | # [print(x) for x in people_in_q] 33 | # people_in_q.clear() 34 | # data_input = input() 35 | # continue 36 | # people_in_q.append(data_input) 37 | # data_input = input() 38 | # 39 | # print(f"{len(people_in_q)} people remaining.") -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/4_water_dispenser.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class WaterDispenser: 5 | quantity = 0 6 | water_line = deque() 7 | 8 | def add_person_to_q(self, name: str): 9 | self.water_line.append(name) 10 | 11 | def refill(self, litters: int): 12 | self.quantity += litters 13 | 14 | def get_water(self, litters: int): 15 | if litters <= self.quantity: 16 | self.quantity -= litters 17 | return f"{self.water_line.popleft()} got water" 18 | return f"{self.water_line.popleft()} must wait" 19 | 20 | 21 | dispenser = WaterDispenser() 22 | 23 | dispenser.quantity = int(input()) 24 | person = input() 25 | 26 | while person != "Start": 27 | dispenser.add_person_to_q(person) 28 | person = input() 29 | 30 | command = input() 31 | while command != "End": 32 | if command.isdigit(): 33 | print(dispenser.get_water(int(command))) 34 | else: 35 | _, litters_to_refill = command.split() 36 | dispenser.refill(int(litters_to_refill)) 37 | command = input() 38 | 39 | print(f"{dispenser.quantity} liters left") 40 | 41 | 42 | 43 | 44 | 45 | 46 | # from collections import deque 47 | # 48 | # dispenser_quantity = int(input()) 49 | # person = input() 50 | # 51 | # water_line = deque() 52 | # 53 | # 54 | # def refill(liters): 55 | # global dispenser_quantity 56 | # dispenser_quantity += liters 57 | # 58 | # 59 | # def get_water(liters): 60 | # global dispenser_quantity 61 | # if liters <= dispenser_quantity: 62 | # dispenser_quantity -= liters 63 | # print(f"{water_line.popleft()} got water") 64 | # else: 65 | # print(f"{water_line.popleft()} must wait") 66 | # 67 | # 68 | # while person != "Start": 69 | # water_line.append(person) 70 | # person = input() 71 | # 72 | # command = input() 73 | # while command != "End": 74 | # if command.isdigit(): 75 | # get_water(int(command)) 76 | # else: 77 | # _, litters_to_refill = command.split() 78 | # refill(int(litters_to_refill)) 79 | # command = input() 80 | # 81 | # print(f"{dispenser_quantity} liters left") 82 | 83 | 84 | 85 | 86 | # quantity = int(input()) 87 | # 88 | # people_in_q = [] 89 | # people_litters_drink = [] 90 | # data_input = input() 91 | # while data_input != "Start": 92 | # people_in_q.append(data_input) 93 | # data_input = input() 94 | # 95 | # data_input = input() 96 | # while data_input != "End": 97 | # if "refill" in data_input: 98 | # quantity += int(data_input.split()[-1]) 99 | # data_input = input() 100 | # continue 101 | # people_litters_drink.append(int(data_input)) 102 | # data_input = input() 103 | # 104 | # for name, liters in zip(people_in_q.copy(), people_litters_drink.copy()): 105 | # if quantity - liters >= 0: 106 | # quantity -= liters 107 | # print(f"{name} got water") 108 | # people_in_q.pop(0) 109 | # else: 110 | # print(f"{name} must wait") 111 | # 112 | # print(f"{quantity} liters left") 113 | -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/5_hot_potato.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | kids = deque(input().split()) 4 | number_of_skips = int(input()) 5 | 6 | while len(kids) > 1: 7 | kids.rotate(-number_of_skips) 8 | print(f"Removed {kids.pop()}") 9 | 10 | print(f"Last is {kids.popleft()}") 11 | 12 | 13 | 14 | 15 | # from collections import deque 16 | # kids = deque(input().split()) 17 | # tosses = int(input()) 18 | # 19 | # while len(kids) > 1: 20 | # for num in range(1, tosses + 1): 21 | # if num % tosses == 0: 22 | # print(f"Removed {kids.popleft()}") 23 | # break 24 | # kids.append(kids.popleft()) 25 | # 26 | # print(f"Last is {kids.pop()}") -------------------------------------------------------------------------------- /1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ip681/python-advanced/d4fd461144d6eb149cc26f53728e27658bdc3109/1. Lists as Stacks and Queues/Lists as Stacks and Queues - Lab/__init__.py -------------------------------------------------------------------------------- /10. Exam/1. Offroad Challenge.py: -------------------------------------------------------------------------------- 1 | # initial_fuel = list(map(int, input().split())) 2 | # consumption_index = list(map(int, input().split())) 3 | # needed_fuel = list(map(int, input().split())) 4 | # 5 | # reached_altitudes = [] 6 | # 7 | # #t 8 | # for i in range(len(needed_fuel)): 9 | # available_fuel = initial_fuel[-1] - consumption_index[0] 10 | # 11 | # if available_fuel >= needed_fuel[i]: 12 | # print(f"John has reached: Altitude {i+1}") 13 | # reached_altitudes.append(i+1) 14 | # initial_fuel.pop() 15 | # consumption_index.pop(0) 16 | # else: 17 | # print(f"John did not reach: Altitude {i+1}") 18 | # break 19 | # 20 | # if not needed_fuel: 21 | # print("John has reached all the altitudes and managed to reach the top!") 22 | # else: 23 | # if reached_altitudes: 24 | # print("John failed to reach the top.") 25 | # print("Reached altitudes:", end=' ') 26 | # print(*[f"Altitude {alt}" for alt in reached_altitudes], sep=', ') 27 | # else: 28 | # print("John failed to reach the top.") 29 | # print("John didn't reach any altitude.") 30 | 31 | from collections import deque 32 | 33 | initial_fuel = [int(x) for x in input().split()] 34 | additional_consumption_index = deque(int(x) for x in input().split()) 35 | amount_of_fuel_needed = deque(int(x) for x in input().split()) 36 | 37 | reached_altitudes = [] 38 | 39 | while initial_fuel and additional_consumption_index: 40 | current_fuel = initial_fuel.pop() 41 | current_index = additional_consumption_index.popleft() 42 | current_fuel_needed = amount_of_fuel_needed.popleft() 43 | current_result = current_fuel - current_index 44 | 45 | altitude_number = len(reached_altitudes) + 1 46 | 47 | if current_result >= current_fuel_needed: 48 | reached_altitudes.append(altitude_number) 49 | print(f"John has reached: Altitude {altitude_number}") 50 | else: 51 | print(f"John did not reach: Altitude {altitude_number}") 52 | break 53 | 54 | if len(reached_altitudes) == 4: 55 | print("John has reached all the altitudes and managed to reach the top!") 56 | else: 57 | print(f"John failed to reach the top.") 58 | if reached_altitudes: 59 | altitudes_str = ", ".join([f"Altitude {alt}" for alt in reached_altitudes]) 60 | print(f"Reached altitudes: {altitudes_str}") 61 | else: 62 | print("John didn't reach any altitude.") 63 | -------------------------------------------------------------------------------- /10. Exam/2. Fishing Competition.py: -------------------------------------------------------------------------------- 1 | def is_valid_position(row, col, matrix_size): 2 | return 0 <= row < matrix_size and 0 <= col < matrix_size 3 | 4 | 5 | def move_ship(row, col, direction): 6 | if direction == "up": 7 | return row - 1, col 8 | elif direction == "down": 9 | return row + 1, col 10 | elif direction == "left": 11 | return row, col - 1 12 | elif direction == "right": 13 | return row, col + 1 14 | 15 | #num 16 | n = int(input()) 17 | fishing_area = [] 18 | ship_row, ship_col = 0, 0 19 | fish_caught = 0 20 | 21 | for row in range(n): 22 | line = input() 23 | fishing_area.append(list(line)) 24 | if 'S' in line: 25 | ship_row, ship_col = row, line.index('S') 26 | 27 | commands = [] 28 | while True: 29 | command = input() 30 | if command == "collect the nets": 31 | break 32 | commands.append(command) 33 | 34 | for command in commands: 35 | fishing_area[ship_row][ship_col] = '-' 36 | new_row, new_col = move_ship(ship_row, ship_col, command) 37 | 38 | if not is_valid_position(new_row, new_col, n): 39 | if command == "up": 40 | new_row = n - 1 41 | elif command == "down": 42 | new_row = 0 43 | elif command == "left": 44 | new_col = n - 1 45 | elif command == "right": 46 | new_col = 0 47 | 48 | ship_row, ship_col = new_row, new_col 49 | 50 | element = fishing_area[new_row][new_col] 51 | if isinstance(element, list): 52 | element = ''.join(element) 53 | 54 | if str(element).isdigit(): 55 | fish_caught += int(element) 56 | fishing_area[new_row][new_col] = '-' 57 | 58 | if fishing_area[new_row][new_col] == 'W': 59 | print( 60 | f"You fell into a whirlpool! The ship sank and you lost the fish you caught. Last coordinates of the ship: [{new_row},{new_col}]") 61 | exit() 62 | 63 | ship_row, ship_col = new_row, new_col 64 | fishing_area[ship_row][ship_col] = 'S' 65 | 66 | if fish_caught >= 20: 67 | print("Success! You managed to reach the quota!") 68 | else: 69 | print(f"You didn't catch enough fish and didn't reach the quota! You need {20 - fish_caught} tons of fish more.") 70 | 71 | if fish_caught>0: 72 | print(f"Amount of fish caught: {fish_caught} tons.") 73 | 74 | # print(f"Amount of fish caught: {fish_caught} tons.") 75 | for row in fishing_area: 76 | print(''.join(row)) 77 | 78 | 79 | # def is_inside(matrix_size, r, c): 80 | # return 0 <= r < matrix_size and 0 <= c < matrix_size 81 | # 82 | # 83 | # def move_ship(matrix, row, col, command): 84 | # matrix[row][col] = '-' 85 | # if command == "up": 86 | # row -= 1 87 | # elif command == "down": 88 | # row += 1 89 | # elif command == "left": 90 | # col -= 1 91 | # elif command == "right": 92 | # col += 1 93 | # 94 | # if not is_inside(len(matrix), row, col): 95 | # if row == -1: 96 | # row = len(matrix) - 1 97 | # elif row == len(matrix): 98 | # row = 0 99 | # if col == -1: 100 | # col = len(matrix) - 1 101 | # elif col == len(matrix): 102 | # col = 0 103 | # 104 | # return row, col 105 | # 106 | # 107 | # n = int(input()) 108 | # matrix = [list(input()) for _ in range(n)] 109 | # 110 | # ship_row, ship_col = None, None 111 | # for r in range(n): 112 | # for c in range(n): 113 | # if matrix[r][c] == 'S': 114 | # ship_row, ship_col = r, c 115 | # break 116 | # 117 | # fish_caught = 0 118 | # while True: 119 | # command = input() 120 | # if command == "collect the nets": 121 | # break 122 | # 123 | # ship_row, ship_col = move_ship(matrix, ship_row, ship_col, command) 124 | # 125 | # if matrix[ship_row][ship_col] == 'W': 126 | # print( 127 | # f"You fell into a whirlpool! The ship sank and you lost the fish you caught. Last coordinates of the ship: [{ship_row},{ship_col}]") 128 | # exit() 129 | # 130 | # if matrix[ship_row][ship_col].isdigit(): 131 | # fish_caught += int(matrix[ship_row][ship_col]) 132 | # matrix[ship_row][ship_col] = '-' 133 | # 134 | # matrix[ship_row][ship_col] = 'S' 135 | # 136 | # if fish_caught < 20: 137 | # print(f"You didn't catch enough fish and didn't reach the quota! You need {20 - fish_caught} tons of fish more.") 138 | # elif fish_caught >= 20: 139 | # print("Success! You managed to reach the quota!") 140 | # 141 | # if fish_caught > 0: 142 | # print(f"Amount of fish caught: {fish_caught} tons.") 143 | # 144 | # for row in matrix: 145 | # print(''.join(row)) -------------------------------------------------------------------------------- /10. Exam/3. Team Lineup.py: -------------------------------------------------------------------------------- 1 | def team_lineup(*args): 2 | country_data = {} 3 | for pl, ctr in args: 4 | if ctr in country_data: 5 | country_data[ctr].append(pl) 6 | else: 7 | country_data[ctr] = [pl] 8 | 9 | sorted_ctr = dict(sorted(country_data.items(), key=lambda kvp: (-len(kvp[1]), kvp[0]))) 10 | 11 | rt = [] 12 | for ctr, country_players in sorted_ctr.items(): 13 | rt.append(f"{ctr}:") 14 | 15 | for pl in country_players: 16 | rt.append(f" -{pl}") 17 | 18 | return "\n".join(rt) -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/1_unique_usernames.py: -------------------------------------------------------------------------------- 1 | number_of_user_names = int(input()) 2 | names = set() 3 | for name in range(number_of_user_names): 4 | names.add(input()) 5 | 6 | print("\n".join(names)) 7 | 8 | 9 | # 10 | # 11 | # 12 | # 13 | # 14 | # 15 | # 16 | # 17 | # 18 | # 19 | # number_of_user_names = int(input()) 20 | # names = [input() for _ in range(number_of_user_names)] 21 | # print("\n".join(set(names))) -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/2_sets_of_elements.py: -------------------------------------------------------------------------------- 1 | first_set_sep, second_set_sep = [int(num) for num in input().split()] 2 | 3 | first_set = set() 4 | second_set = set() 5 | 6 | for num in range(first_set_sep): 7 | first_set.add(input()) 8 | 9 | for num in range(second_set_sep): 10 | second_set.add(input()) 11 | 12 | print("\n".join(first_set.intersection(second_set))) 13 | 14 | 15 | 16 | 17 | 18 | 19 | # 20 | # 21 | # first_set_sep, second_set_sep = [int(num) for num in input().split()] 22 | # 23 | # all_numbers = [input() for _ in range(first_set_sep+second_set_sep)] 24 | # print("\n".join(list(set(all_numbers[:first_set_sep]) & set(all_numbers[first_set_sep:])))) 25 | -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/3_periodic_table.py: -------------------------------------------------------------------------------- 1 | elements_count = int(input()) 2 | 3 | elements = set() 4 | for _ in range(elements_count): 5 | how_many_elements = input().split() 6 | for element in how_many_elements: 7 | elements.add(element) 8 | 9 | print("\n".join(elements)) 10 | 11 | 12 | # 13 | # 14 | # 15 | # 16 | # 17 | # 18 | # 19 | # 20 | # elements_count = int(input()) 21 | # 22 | # elements = [] 23 | # for _ in range(elements_count): 24 | # for element in input().split(): 25 | # elements.append(element) 26 | # 27 | # print("\n".join(set(elements))) -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/4_count_symbols.py: -------------------------------------------------------------------------------- 1 | main_string = input() 2 | 3 | result_ = {} 4 | for symbol in main_string: 5 | result_[symbol] = f": {main_string.count(symbol)} time/s" 6 | 7 | for sym, rep in sorted(result_.items()): 8 | print(f"{sym}{rep}") -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/5_longest_Intersection.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | lines = int(input()) 4 | max_intersection = -sys.maxsize 5 | combined_intersection = set() 6 | set_a = set() 7 | set_b = set() 8 | 9 | for i in range(lines): 10 | data = input().split("-") 11 | range_1 = [int(i) for i in data[0].split(",")] 12 | range_2 = [int(i) for i in data[1].split(",")] 13 | for i in range(range_1[0], range_1[1] + 1): 14 | set_a.add(i) 15 | for i in range(range_2[0], range_2[1] + 1): 16 | set_b.add(i) 17 | sets_intersection = set_a.intersection(set_b) 18 | if len(sets_intersection) > max_intersection: 19 | max_intersection = len(sets_intersection) 20 | combined_intersection = sets_intersection 21 | set_a.clear() 22 | set_b.clear() 23 | 24 | 25 | print(f"Longest intersection is [", end="") 26 | print(*combined_intersection, sep=", ", end="") 27 | print(f"] with length {max_intersection}") 28 | 29 | 30 | # 31 | # lines_of_input = int(input()) 32 | # 33 | # biggest_range = 0 34 | # result_ = [] 35 | # for _ in range(lines_of_input): 36 | # first_intersection, second_intersection = input().split("-") 37 | # first_intersection = [int(num) for num in first_intersection.split(",") if num.isdigit()] 38 | # second_intersection = [int(num) for num in second_intersection.split(",") if num.isdigit()] 39 | # if first_intersection[1] > second_intersection[1]: 40 | # first_num = first_intersection[0] 41 | # if first_intersection[0] < second_intersection[0]: 42 | # first_num = second_intersection[0] 43 | # result_.append([first_num, second_intersection[-1]]) 44 | # else: 45 | # first_num = first_intersection[0] 46 | # if first_intersection[0] < second_intersection[0]: 47 | # first_num = second_intersection[0] 48 | # result_.append([first_num, first_intersection[-1]]) 49 | # 50 | # result_ = sorted(result_, key=lambda x: abs(x[0] - x[1]), reverse=True) 51 | # longest_result = [x for x in range(result_[0][0], result_[0][1]+1)] 52 | # print(f"Longest intersection is {longest_result} with length {len(longest_result)}") 53 | # 54 | -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Exercise/6_battle_of_names.py: -------------------------------------------------------------------------------- 1 | number_of_names = int(input()) 2 | 3 | odd_numbers = set() 4 | even_numbers = set() 5 | 6 | for row in range(1, number_of_names + 1): 7 | name = input() 8 | current_name_score = 0 9 | for ltr in name: 10 | current_name_score += ord(ltr) 11 | number_to_add = int(current_name_score/row) 12 | if number_to_add % 2 != 0: 13 | odd_numbers.add(number_to_add) 14 | else: 15 | even_numbers.add(number_to_add) 16 | 17 | if sum(odd_numbers) < sum(even_numbers): 18 | print(*even_numbers.symmetric_difference(odd_numbers), sep=", ") 19 | elif sum(odd_numbers) > sum(even_numbers): 20 | print(*odd_numbers.difference(even_numbers), sep=", ") 21 | else: 22 | print(*odd_numbers.union(even_numbers), sep=", ") -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/1_count_same_values.py: -------------------------------------------------------------------------------- 1 | numbers_to_count = input().split() 2 | 3 | result = {float(num): numbers_to_count.count(num) for num in numbers_to_count} 4 | for number, counter in result.items(): 5 | print(f"{number:.1f} - {counter} times") 6 | 7 | 8 | -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/2_students_grades.py: -------------------------------------------------------------------------------- 1 | number_of_students = int(input()) 2 | 3 | result = {} 4 | for student in range(number_of_students): 5 | student_name, student_grade = input().split() 6 | result[student_name] = result.get(student_name, list()) 7 | result[student_name].append(f"{float(student_grade):.2f}") 8 | 9 | for name, grades in result.items(): 10 | print(f"{name} -> {' '.join(grades)} (avg: {(sum(float(num) for num in grades)/len(grades)):.2f})") 11 | 12 | 13 | -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/3_record_unique_names.py: -------------------------------------------------------------------------------- 1 | number_of_names = int(input()) 2 | 3 | names = set() 4 | 5 | for _ in range(number_of_names): 6 | names.add(input()) 7 | 8 | print("\n".join(names)) 9 | 10 | 11 | 12 | # 13 | # number_of_names = int(input()) 14 | # 15 | # names = [input() for _ in range(number_of_names)] 16 | # print("\n".join(set(names))) -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/4_parking_lot.py: -------------------------------------------------------------------------------- 1 | car_numbers = int(input()) 2 | 3 | parking_lot = set() 4 | for car in range(car_numbers): 5 | direction, car_plate_number = input().split(", ") 6 | 7 | if "IN" == direction: 8 | parking_lot.add(car_plate_number) 9 | 10 | elif "OUT" == direction and car_plate_number in parking_lot: 11 | parking_lot.remove(car_plate_number) 12 | 13 | 14 | if parking_lot: 15 | print('\n'.join(parking_lot)) 16 | else: 17 | print("Parking Lot is Empty") 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | # car_numbers = int(input()) 27 | # 28 | # parking_lot = {} 29 | # for car in range(car_numbers): 30 | # direction, car_plate_number = input().split(", ") 31 | # if "IN" == direction: 32 | # parking_lot[car_plate_number] = direction 33 | # continue 34 | # del parking_lot[car_plate_number] 35 | # 36 | # if parking_lot.keys(): 37 | # print('\n'.join(parking_lot.keys())) 38 | # else: 39 | # print("Parking Lot is Empty") -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/5_softuni_party.py: -------------------------------------------------------------------------------- 1 | number_of_guests = int(input()) 2 | 3 | reservation = {input() for _ in range(number_of_guests)} 4 | guests_who_came = input() 5 | 6 | while guests_who_came != "END": 7 | reservation.remove(guests_who_came) 8 | guests_who_came = input() 9 | 10 | print(len(reservation)) 11 | print("\n".join(sorted(reservation))) 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | # 25 | # 26 | # 27 | # number_of_guests = int(input()) 28 | # 29 | # reservation = [input() for _ in range(number_of_guests)] 30 | # guests_who_came = input() 31 | # while guests_who_came != "END": 32 | # if guests_who_came in reservation: 33 | # reservation.remove(guests_who_came) 34 | # guests_who_came = input() 35 | # 36 | # print(len(reservation)) 37 | # vip, regular = [], [] 38 | # [vip.append(res) if res[0].isdigit() else regular.append(res) for res in reservation] 39 | # if vip: 40 | # print('\n'.join(sorted(vip))) 41 | # if regular: 42 | # print('\n'.join(sorted(regular))) -------------------------------------------------------------------------------- /2. Tuples and Sets/Tuples and Sets - Lab/6_summation_pairs.py: -------------------------------------------------------------------------------- 1 | pairs_of_numbers = [int(num) for num in input().split()] 2 | 3 | target_number = int(input()) 4 | result_print = set() 5 | total_iterations = 0 6 | for pos, number_one in enumerate(pairs_of_numbers, 1): 7 | for number_two in pairs_of_numbers[pos:]: 8 | total_iterations += 1 9 | if number_one + number_two == target_number: 10 | result_print.add((number_one, number_two)) 11 | print(f"{number_one} + {number_two} = {target_number}") 12 | 13 | print(f"Iterations done: {total_iterations}") 14 | if result_print: 15 | print(*result_print, sep="\n") 16 | 17 | 18 | 19 | 20 | 21 | # 22 | # 23 | # 24 | # 25 | # 26 | # pairs_of_numbers = [int(num) for num in input().split()] 27 | # 28 | # target_number = int(input()) 29 | # result_print = [] 30 | # total_iterations = 0 31 | # for pos, number_one in enumerate(pairs_of_numbers, 1): 32 | # for number_two in pairs_of_numbers[pos:]: 33 | # total_iterations += 1 34 | # if number_one + number_two == target_number: 35 | # print(f"{number_one} + {number_two} = {target_number}") 36 | # result_print.append(f"({number_one}, {number_two})") 37 | # 38 | # print(f"Iterations done: {total_iterations}") 39 | # if result_print: 40 | # print('\n'.join(set(result_print))) -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/1_numbers.py: -------------------------------------------------------------------------------- 1 | set_one = set(int(x) for x in input().split()) 2 | set_two = set(int(x) for x in input().split()) 3 | 4 | number_of_commands = int(input()) 5 | 6 | for _ in range(number_of_commands): 7 | command = input() 8 | 9 | if "Check Subset" not in command: 10 | numbers = [int(x) for x in command.split() if x.isdigit()] 11 | 12 | if "First" in command: 13 | if "Add" in command: 14 | for num in numbers: 15 | set_one.add(num) 16 | 17 | elif "Remove" in command: 18 | for num in numbers: 19 | set_one.discard(num) 20 | 21 | elif "Second" in command: 22 | if "Add" in command: 23 | for num in numbers: 24 | set_two.add(num) 25 | 26 | elif "Remove" in command: 27 | for num in numbers: 28 | set_two.discard(num) 29 | 30 | else: 31 | print(set_one.issuperset(set_two)) 32 | 33 | print(*sorted(set_one), sep=", ") 34 | print(*sorted(set_two), sep=", ") 35 | -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/2_expression_evaluator.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | string_expression = input().split() 4 | 5 | numbers = deque() 6 | operators = { 7 | "+": lambda f, s: f + s, 8 | "-": lambda f, s: f - s, 9 | "*": lambda f, s: f * s, 10 | "/": lambda f, s: f // s 11 | } 12 | 13 | 14 | for element in string_expression: 15 | if element in "+-*/": 16 | while len(numbers) > 1: 17 | numbers.appendleft(operators[element](numbers.popleft(), numbers.popleft())) 18 | else: 19 | numbers.append(int(element)) 20 | 21 | print(numbers.popleft()) 22 | 23 | 24 | 25 | # 26 | # from collections import deque 27 | # 28 | # string_expression = input().split() 29 | # 30 | # numbers = deque() 31 | # 32 | # for element in string_expression: 33 | # if element in "+-*/": 34 | # while len(numbers) > 1: 35 | # num_one = numbers.popleft() 36 | # num_two = numbers.popleft() 37 | # 38 | # result = 0 39 | # 40 | # if element == "+": 41 | # result = num_one + num_two 42 | # elif element == "-": 43 | # result = num_one - num_two 44 | # elif element == "*": 45 | # result = num_one * num_two 46 | # else: 47 | # result = num_one // num_two 48 | # 49 | # numbers.appendleft(result) 50 | # 51 | # else: 52 | # numbers.append(int(element)) 53 | # 54 | # print(numbers.popleft()) 55 | # 56 | # 57 | # 58 | # 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | # from collections import deque 67 | # 68 | # string_expression = deque(input().split()) 69 | # 70 | # result = 0 71 | # numbers_so_far = "" 72 | # el = 0 73 | # while len(string_expression) != 1: 74 | # check_element = string_expression[el] 75 | # if check_element == "-": 76 | # result = int(string_expression.popleft()) 77 | # while True: 78 | # check_element = string_expression[0] 79 | # if check_element != "-": 80 | # take_element = string_expression.popleft() 81 | # result -= int(take_element) 82 | # else: 83 | # string_expression[0] = result 84 | # el = 0 85 | # break 86 | # elif check_element == "*": 87 | # result = int(string_expression.popleft()) 88 | # while True: 89 | # check_element = string_expression[0] 90 | # if check_element != "*": 91 | # take_element = string_expression.popleft() 92 | # result *= int(take_element) 93 | # else: 94 | # string_expression[0] = result 95 | # el = 0 96 | # break 97 | # elif check_element == "/": 98 | # result = int(string_expression.popleft()) 99 | # while True: 100 | # check_element = string_expression[0] 101 | # if check_element != "/": 102 | # take_element = string_expression.popleft() 103 | # result = int(result / int(take_element)) 104 | # else: 105 | # string_expression[0] = result 106 | # el = 0 107 | # break 108 | # if check_element == "+": 109 | # result = int(string_expression.popleft()) 110 | # while True: 111 | # check_element = string_expression[0] 112 | # if check_element != "+": 113 | # take_element = string_expression.popleft() 114 | # result += int(take_element) 115 | # else: 116 | # string_expression[0] = result 117 | # el = 0 118 | # break 119 | # else: 120 | # el += 1 121 | # 122 | # 123 | # print(*string_expression) 124 | 125 | -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/3_milkshakes.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | chocolate = [int(x) for x in input().split(",")] 5 | cups_of_milk = deque(int(x) for x in input().split(",")) 6 | 7 | successfully_made_milkshakes = 0 8 | 9 | while chocolate and cups_of_milk and successfully_made_milkshakes != 5: 10 | current_chocolate = chocolate.pop() 11 | current_cup = cups_of_milk.popleft() 12 | 13 | if current_chocolate <= 0 and current_cup <= 0: 14 | continue 15 | elif current_chocolate <= 0: 16 | cups_of_milk.appendleft(current_cup) 17 | continue 18 | elif current_cup <= 0: 19 | chocolate.append(current_chocolate) 20 | continue 21 | if current_chocolate == current_cup: 22 | successfully_made_milkshakes += 1 23 | else: 24 | cups_of_milk.append(current_cup) 25 | chocolate.append(current_chocolate - 5) 26 | 27 | if successfully_made_milkshakes == 5: 28 | print(f"Great! You made all the chocolate milkshakes needed!") 29 | else: 30 | print(f"Not enough milkshakes.") 31 | 32 | if chocolate: 33 | print(f"Chocolate: {', '.join(str(x) for x in chocolate)}") 34 | else: 35 | print("Chocolate: empty") 36 | 37 | if cups_of_milk: 38 | print(f"Milk: {', '.join(str(x) for x in cups_of_milk)}") 39 | else: 40 | print("Milk: empty") 41 | 42 | 43 | 44 | # 45 | # from collections import deque 46 | # 47 | # 48 | # chocolate = [int(x) for x in input().split(",")] 49 | # cups_of_milk = deque(int(x) for x in input().split(",")) 50 | # 51 | # successfully_made_milkshakes = 0 52 | # 53 | # while chocolate and cups_of_milk: 54 | # current_chocolate = chocolate[-1] 55 | # current_cup = cups_of_milk[0] 56 | # if current_chocolate <= 0: 57 | # del chocolate[-1] 58 | # continue 59 | # if current_cup <= 0: 60 | # del cups_of_milk[0] 61 | # elif current_chocolate != current_cup: 62 | # cups_of_milk.append(cups_of_milk.popleft()) 63 | # chocolate[-1] -= 5 64 | # else: 65 | # successfully_made_milkshakes += 1 66 | # del cups_of_milk[0] 67 | # del chocolate[-1] 68 | # 69 | # if successfully_made_milkshakes == 5: 70 | # break 71 | # 72 | # if successfully_made_milkshakes == 5: 73 | # print(f"Great! You made all the chocolate milkshakes needed!") 74 | # else: 75 | # print(f"Not enough milkshakes.") 76 | # 77 | # if chocolate: 78 | # print(f"Chocolate: {', '.join(str(x) for x in chocolate)}") 79 | # else: 80 | # print("Chocolate: empty") 81 | # 82 | # if cups_of_milk: 83 | # print(f"Milk: {', '.join(str(x) for x in cups_of_milk)}") 84 | # else: 85 | # print("Milk: empty") 86 | # 87 | -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/4_honey.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | bees = deque(int(x) for x in input().split()) 4 | nectars = [int(x) for x in input().split()] 5 | operations = deque(input().split()) 6 | 7 | honey_made = 0 8 | operators = { 9 | "+": lambda f, s: f + s, 10 | "-": lambda f, s: f - s, 11 | "*": lambda f, s: f * s, 12 | "/": lambda f, s: f / s 13 | } 14 | 15 | while bees and nectars: 16 | bee = bees.popleft() 17 | nectar = nectars.pop() 18 | 19 | if nectar < bee: 20 | bees.appendleft(bee) 21 | continue 22 | operation = operations.popleft() 23 | if nectar > 0: 24 | honey_made += abs(operators[operation](bee, nectar)) 25 | 26 | print(f"Total honey made: {honey_made}") 27 | 28 | if bees: 29 | print(f"Bees left: {', '.join(str(x) for x in bees)}") 30 | 31 | if nectars: 32 | print(f"Nectar left: {', '.join(str(x) for x in nectars)}") -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/5_santas_present_factory.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | boxes_with_materials = [int(x) for x in input().split()] 4 | magic_values = deque(int(x) for x in input().split()) 5 | 6 | presents = { 7 | "Bicycle": [0, 400], 8 | "Doll": [0, 150], 9 | "Teddy bear": [0, 300], 10 | "Wooden train": [0, 250] 11 | } 12 | 13 | while boxes_with_materials and magic_values: 14 | material = boxes_with_materials.pop() 15 | magic = magic_values.popleft() 16 | 17 | if material == 0 and magic == 0: 18 | continue 19 | if material == 0: 20 | magic_values.appendleft(magic) 21 | continue 22 | if magic == 0: 23 | boxes_with_materials.append(material) 24 | continue 25 | 26 | product_of_operation = material * magic 27 | if product_of_operation < 0: 28 | result = material + magic 29 | boxes_with_materials.append(result) 30 | 31 | else: 32 | found_present = False 33 | for gift, data in presents.items(): 34 | _, magic_level = data 35 | if magic_level == product_of_operation: 36 | presents[gift][0] += 1 37 | found_present = True 38 | break 39 | if product_of_operation > 0 and not found_present: 40 | boxes_with_materials.append(material + 15) 41 | 42 | if (presents["Bicycle"][0] >= 1 and presents["Teddy bear"][0] >= 1) or \ 43 | (presents["Doll"][0] >= 1 and presents["Wooden train"][0] >= 1): 44 | print(f"The presents are crafted! Merry Christmas!") 45 | else: 46 | print(f"No presents this Christmas!") 47 | 48 | if boxes_with_materials: 49 | print(f"Materials left: {', '.join(str(x) for x in boxes_with_materials[::-1])}") 50 | #print(f"Materials left: {', '.join([str(boxes_with_materials.pop()) for _ in range(len(boxes_with_materials))])}") 51 | #print(f"Materials left: {', '.join(str(x) for x in reversed(boxes_with_materials)}") 52 | 53 | if magic_values: 54 | print(f"Magic left: {', '.join(str(x) for x in magic_values)}") 55 | 56 | for gift, data in presents.items(): 57 | amount, _ = data 58 | if amount >= 1: 59 | print(f"{gift}: {amount}") 60 | -------------------------------------------------------------------------------- /3. Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/6_paint_colors.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | substring = deque(input().split()) 4 | 5 | colors = { 6 | "all colors": ("red", "yellow", "blue", "orange", "purple", "green"), 7 | "required colors": { 8 | "orange": ("red", "yellow"), 9 | "purple": ("red", "blue"), 10 | "green": ("yellow", "blue") 11 | } 12 | } 13 | 14 | result = [] 15 | 16 | while substring: 17 | last_part = "" 18 | if len(substring) > 1: 19 | last_part = substring.pop() 20 | first_part = substring.popleft() 21 | for color in (first_part + last_part, last_part + first_part): 22 | if color in colors["all colors"]: 23 | result.append(color) 24 | break 25 | else: 26 | for item in (first_part[:-1], last_part[:-1]): 27 | if item: 28 | substring.insert(len(substring) // 2, item) 29 | 30 | for color, req_colors in colors["required colors"].items(): 31 | if any(x not in result and color in result for x in req_colors): 32 | result.remove(color) 33 | 34 | print(result) 35 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/10_radioactive_mutate_vampire_bunnies.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split()] 2 | matrix = [[x for x in input()] for _ in range(rows)] 3 | commands = input() 4 | 5 | winner, movement = False, { 6 | "U": [-1, 0], "D": [1, 0], "L": [0, -1], "R": [0, 1] 7 | } 8 | 9 | 10 | def find_player_position(): 11 | for row in range(rows): 12 | if "P" in matrix[row]: 13 | return row, matrix[row].index("P") 14 | 15 | 16 | def player_alive(row, col): 17 | if matrix[row][col] == "B": 18 | show_result("dead") 19 | 20 | 21 | def check_valid_index(row, col, player=False): 22 | global winner 23 | if 0 <= row < rows and 0 <= col < cols: 24 | return True 25 | if player: 26 | winner = True 27 | 28 | 29 | def bunnies_position(): 30 | position = [] 31 | for row in range(rows): 32 | for col in range(cols): 33 | if matrix[row][col] == "B": 34 | position.append(row) 35 | position.append(col) 36 | return position 37 | 38 | 39 | def bunnies_moves(bunnies_pos): 40 | for i in range(0, len(bunnies_pos), 2): 41 | row, col = bunnies_pos[i], bunnies_pos[i + 1] 42 | for bunnie_move in movement: 43 | new_row, new_col = row + movement[bunnie_move][0], col + movement[bunnie_move][1] 44 | if check_valid_index(new_row, new_col): 45 | matrix[new_row][new_col] = "B" 46 | 47 | 48 | def show_result(status="won"): 49 | [print(*matrix[row], sep="") for row in range(rows)] 50 | print(f"{status}: {player_row} {player_col}") 51 | exit() 52 | 53 | 54 | player_row, player_col = find_player_position() 55 | matrix[player_row][player_col] = "." 56 | for command in commands: 57 | player_movement_row, player_movement_col = player_row + movement[command][0], player_col + movement[command][1] 58 | if check_valid_index(player_movement_row, player_movement_col, True): 59 | player_row, player_col = player_movement_row, player_movement_col 60 | bunnies_moves(bunnies_position()) 61 | if winner: 62 | show_result() 63 | if check_valid_index(player_movement_row, player_movement_col): 64 | player_alive(player_movement_row, player_movement_col) 65 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/1_diagonals.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | 3 | nested_list = [[int(x) for x in input().split(", ")] for _ in range(rows)] 4 | 5 | 6 | def diagonal_sums(matrix, rows): 7 | diagonals = { 8 | "primary sum": [], 9 | "secondary sum": [] 10 | } 11 | 12 | for i in range(rows): 13 | diagonals["primary sum"].append(matrix[i][i]) 14 | diagonals["secondary sum"].append(matrix[i][rows - i - 1]) 15 | 16 | print( 17 | f"Primary diagonal: {', '.join(str(x) for x in diagonals['primary sum'])}. Sum: {sum(diagonals['primary sum'])}") 18 | print( 19 | f"Secondary diagonal: {', '.join(map(str, diagonals['secondary sum']))}. Sum: {sum(diagonals['secondary sum'])}") 20 | 21 | 22 | diagonal_sums(nested_list, rows) 23 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/2_diagonal_difference.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | 3 | nested_list = [[int(x) for x in input().split()] for _ in range(rows)] 4 | 5 | 6 | def diagonal_sums(matrix, rows): 7 | diagonals = { 8 | "primary sum": [], 9 | "secondary sum": [] 10 | } 11 | 12 | for i in range(rows): 13 | diagonals["primary sum"].append(matrix[i][i]) 14 | diagonals["secondary sum"].append(matrix[i][rows - i - 1]) 15 | 16 | print(abs(sum(diagonals["primary sum"]) - sum(diagonals["secondary sum"]))) 17 | 18 | 19 | diagonal_sums(nested_list, rows) 20 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/3_2x2_squares_in_matrix.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split()] 2 | square_matrix = [input().split() for _ in range(rows)] 3 | all_square_matrices = 0 4 | 5 | 6 | def check_valid_index(row, col): 7 | if 0 <= row + 2 <= rows and 0 <= col + 2 <= cols: 8 | return True 9 | 10 | 11 | def find_identical_chars(row, col, all_square_matrices): 12 | if check_valid_index(row, col): 13 | if all([True if x == square_matrix[row][col:col + 2][0] else False for x in 14 | square_matrix[row][col:col + 2] + square_matrix[row + 1][col:col + 2]]): 15 | all_square_matrices += 1 16 | return all_square_matrices 17 | 18 | 19 | for row in range(rows): 20 | for col in range(cols): 21 | all_square_matrices = find_identical_chars(row, col, all_square_matrices) 22 | 23 | print(all_square_matrices) 24 | 25 | 26 | 27 | # rows, cols = [int(x) for x in input().split()] 28 | # 29 | # square_matrix = [input().split() for _ in range(rows)] 30 | # all_square_matrices = [] 31 | # 32 | # 33 | # def check_valid_index(row, col): 34 | # if 0 <= row + 2 <= rows and 0 <= col + 2 <= cols: 35 | # return True 36 | # 37 | # 38 | # def find_identical_chars(row, col): 39 | # if check_valid_index(row, col): 40 | # count_identical = 0 41 | # symbol = square_matrix[row][col] 42 | # for row_check in range(row, row + 2): 43 | # count_identical += square_matrix[row_check][col:col + 2].count(symbol) 44 | # if count_identical == 4: 45 | # all_square_matrices.append(1) 46 | # 47 | # 48 | # for row in range(rows): 49 | # for col in range(cols): 50 | # find_identical_chars(row, col) 51 | # 52 | # print(sum(all_square_matrices)) -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/4_maximal_sum.py: -------------------------------------------------------------------------------- 1 | rows, colons = [int(x) for x in input().split()] 2 | 3 | matrix_list = [[int(x) for x in input().split()] for row in range(rows)] 4 | max_sum = {"max number": -181, 5 | "row": 0, 6 | "col": 0} 7 | 8 | 9 | def check_valid_index(row, col): 10 | if 0 <= row + 3 <= rows and 0 <= col + 3 <= colons: 11 | return True 12 | 13 | 14 | def sum_rectangle(row, col): 15 | if check_valid_index(row, col): 16 | sum_total = 0 17 | for row_check in range(row, row + 3): 18 | sum_total += sum(matrix_list[row_check][col: col + 3]) 19 | if max_sum["max number"] < sum_total: 20 | max_sum["max number"] = sum_total 21 | max_sum["row"] = row 22 | max_sum["col"] = col 23 | 24 | 25 | for row in range(rows): 26 | for col in range(colons): 27 | sum_rectangle(row, col) 28 | 29 | print(f"Sum = {max_sum['max number']}") 30 | for row in range(max_sum["row"], max_sum["row"] + 3): 31 | print(" ".join([str(x) for x in matrix_list[row][max_sum["col"]: max_sum["col"] + 3]])) 32 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/5_matrix_of_palindromes.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split()] 2 | 3 | for row in range(97, 97 + rows): 4 | for col in range(97, 97 + cols): 5 | print(f"{chr(row)}{chr((row + col) - 97)}{chr(row)}", end=" ") 6 | print() 7 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/6_matrix_shuffling.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split()] 2 | 3 | matrix = [input().split() for _ in range(rows)] 4 | 5 | 6 | def check_valid_index(row1, col1, row2, col2): 7 | if 0 <= row1 < rows and 0 <= col1 < cols \ 8 | and 0 <= row2 < rows and 0 <= col2 < cols: 9 | return True 10 | print("Invalid input!") 11 | 12 | 13 | def swap_command(row1, col1, row2, col2): 14 | if check_valid_index(row1, col1, row2, col2): 15 | matrix[row1][col1], matrix[row2][col2] = matrix[row2][col2], matrix[row1][col1] 16 | for row in range(len(matrix)): 17 | print(" ".join(map(str, matrix[row]))) 18 | 19 | 20 | command = input() 21 | while command != "END": 22 | command_type, *info = [int(x) if x.isdigit() else x for x in command.split()] 23 | if "swap" == command_type and len(info) == 4: 24 | row1, col1, row2, col2 = info 25 | swap_command(row1, col1, row2, col2) 26 | else: 27 | print("Invalid input!") 28 | command = input() 29 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/7_snake_moves.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | rows, cols = [int(x) for x in input().split()] 4 | snake = input() 5 | 6 | index_snake = 0 7 | 8 | for row in range(rows): 9 | result = deque() 10 | for col in range(cols): 11 | if index_snake == len(snake): 12 | index_snake = 0 13 | if row % 2 == 0: 14 | result.append(snake[index_snake]) 15 | else: 16 | result.appendleft(snake[index_snake]) 17 | index_snake += 1 18 | print("".join(result)) 19 | 20 | 21 | 22 | 23 | 24 | 25 | # rows, cols = [int(x) for x in input().split()] 26 | # snake = input() 27 | # 28 | # index_snake = 0 29 | # 30 | # for row in range(rows): 31 | # line = "" 32 | # for col in range(cols): 33 | # if index_snake == len(snake): 34 | # index_snake = 0 35 | # if row % 2 == 0: 36 | # line += snake[index_snake] 37 | # else: 38 | # line = snake[index_snake] + line 39 | # index_snake += 1 40 | # print(line) 41 | # 42 | 43 | 44 | 45 | # rows, cols = [int(x) for x in input().split()] 46 | # snake = input() 47 | # 48 | # index_snake = 0 49 | # 50 | # for row in range(rows): 51 | # result = [] 52 | # for col in range(cols): 53 | # if index_snake == len(snake): 54 | # index_snake = 0 55 | # if row % 2 == 0: 56 | # result.append(snake[index_snake]) 57 | # else: 58 | # result.insert(0, snake[index_snake]) 59 | # index_snake += 1 60 | # print(*result, sep="") -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/8_bombs.py: -------------------------------------------------------------------------------- 1 | matrix = [[int(x) for x in input().split()] for _ in range(int(input()))] 2 | 3 | for row, col in [[int(n) for n in x.split(",")] for x in input().split(" ")]: 4 | if matrix[row][col] <= 0: continue 5 | bomb_damage, matrix[row][col] = matrix[row][col], 0 6 | for row_pos, col_pos in ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (1, -1), (-1, 1), (1, 1)): 7 | if 0 <= row + row_pos < len(matrix) and 0 <= col + col_pos < len(matrix[0]): 8 | if matrix[row + row_pos][col + col_pos] > 0: matrix[row + row_pos][col + col_pos] -= bomb_damage 9 | 10 | alive_cells = [num for row in range(len(matrix)) for num in matrix[row] if num > 0] 11 | print(f"Alive cells: {len(alive_cells)}\nSum: {sum(alive_cells)}") 12 | [print(*matrix[row]) for row in range(len(matrix))] 13 | 14 | 15 | 16 | 17 | 18 | # rows = int(input()) 19 | # matrix = [[int(x) for x in input().split()] for _ in range(rows)] 20 | # bombs_coordinates = [int(x) for x in input().replace(" ", ",").split(",")] 21 | # cols, alive_cells, movement_explosion = len(matrix[0]), [], { 22 | # "up": [0, -1], "down": [0, 1], "left": [-1, 0], "right": [1, 0], 23 | # "top left diagonal": [-1, -1], "bottom left diagonal": [-1, 1], 24 | # "top right diagonal": [1, -1], "bottom right diagonal": [1, 1]} 25 | # 26 | # for i in range(0, len(bombs_coordinates), 2): 27 | # row, col = bombs_coordinates[i], bombs_coordinates[i + 1] 28 | # if matrix[row][col] > 0: 29 | # bomb_damage, matrix[row][col] = matrix[row][col], 0 30 | # for ind in movement_explosion: 31 | # row_movement, col_movement = row + movement_explosion[ind][0], col + movement_explosion[ind][1] 32 | # if 0 <= row_movement < rows and 0 <= col_movement < cols: 33 | # if matrix[row_movement][col_movement] > 0: 34 | # matrix[row_movement][col_movement] -= bomb_damage 35 | # 36 | # alive_cells = [num for row in range(len(matrix)) for num in matrix[row] if num > 0] 37 | # print(f"Alive cells: {len(alive_cells)}\nSum: {sum(alive_cells)}") 38 | # [print(*matrix[row], sep=" ") for row in range(len(matrix))] 39 | # 40 | # 41 | # 42 | # 43 | 44 | 45 | 46 | 47 | 48 | 49 | # 50 | # 51 | # rows = int(input()) 52 | # 53 | # matrix = [[int(x) for x in input().split()] for _ in range(rows)] 54 | # bombs_coordinates = [int(x) for x in input().replace(" ", ",").split(",")] 55 | # cols, alive_cells = len(matrix[0]), [] 56 | # 57 | # 58 | # def check_valid_index(row, col): 59 | # if 0 <= row < rows and 0 <= col < cols: 60 | # return True 61 | # 62 | # 63 | # def explode(row, col, bomb_damage): 64 | # if matrix[row][col] > 0: 65 | # matrix[row][col] -= bomb_damage 66 | # 67 | # 68 | # movement_explosion = { 69 | # "up": [0, -1], "down": [0, 1], "left": [-1, 0], "right": [1, 0], 70 | # "top left diagonal": [-1, -1], "bottom left diagonal": [-1, 1], 71 | # "top right diagonal": [1, -1], "bottom right diagonal": [1, 1]} 72 | # 73 | # 74 | # for i in range(0, len(bombs_coordinates), 2): 75 | # row, col = bombs_coordinates[i], bombs_coordinates[i + 1] 76 | # if matrix[row][col] > 0: 77 | # bomb_damage, matrix[row][col] = matrix[row][col], 0 78 | # for ind in movement_explosion: 79 | # row_movement, col_movement = movement_explosion[ind] 80 | # if check_valid_index(row + row_movement, col + col_movement): 81 | # explode(row + row_movement, col + col_movement, bomb_damage) 82 | # 83 | # for row in range(len(matrix)): 84 | # for num in matrix[row]: 85 | # if num > 0: 86 | # alive_cells.append(num) 87 | # 88 | # print(f"Alive cells: {len(alive_cells)}") 89 | # print(f"Sum: {sum(alive_cells)}") 90 | # for row in range(len(matrix)): 91 | # print(*matrix[row], sep=" ") 92 | # 93 | # 94 | # 95 | # 96 | 97 | 98 | 99 | 100 | 101 | 102 | # 103 | # rows = int(input()) 104 | # 105 | # matrix = [[int(x) for x in input().split()] for _ in range(rows)] 106 | # bombs_coordinates = [int(x) for x in input().replace(" ", ",").split(",")] 107 | # cols = len(matrix[0]) 108 | # bomb_row = bombs_coordinates[::2] 109 | # bomb_col = bombs_coordinates[1::2] 110 | # alive_cells = [] 111 | # 112 | # 113 | # def check_valid_index(row, col): 114 | # if 0 <= row < rows and 0 <= col < cols: 115 | # return True 116 | # 117 | # 118 | # def explode(row, col, bomb_damage): 119 | # if matrix[row][col] > 0: 120 | # matrix[row][col] -= bomb_damage 121 | # 122 | # 123 | # movement_explosion = [0, -1, 0, 1, -1, 0, 1, 0, -1, -1, -1, 1, 1, -1, 1, 1] 124 | # row_movement = movement_explosion[::2] 125 | # col_movement = movement_explosion[1::2] 126 | # for i in range(len(bomb_row)): 127 | # row, col = bomb_row[i], bomb_col[i] 128 | # if matrix[row][col] > 0: 129 | # bomb_damage, matrix[row][col] = matrix[row][col], 0 130 | # for ind in range(len(row_movement)): 131 | # if check_valid_index(row + row_movement[ind], col + col_movement[ind]): 132 | # explode(row + row_movement[ind], col + col_movement[ind], bomb_damage) 133 | # 134 | # for row in range(len(matrix)): 135 | # for num in matrix[row]: 136 | # if num > 0: 137 | # alive_cells.append(num) 138 | # 139 | # print(f"Alive cells: {len(alive_cells)}") 140 | # print(f"Sum: {sum(alive_cells)}") 141 | # for row in range(len(matrix)): 142 | # print(*matrix[row], sep=" ") 143 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 1/9_miner.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | MATRIX_SIZE = int(input()) 4 | commands = deque(input().split()) 5 | 6 | coal = 0 7 | collected_coal = 0 8 | start_row, start_col = 0, 0 9 | matrix = [] 10 | movement = { 11 | "up": (-1, 0), "down": (1, 0), 12 | "left": (0, -1), "right": (0, 1) 13 | } 14 | 15 | for row in range(MATRIX_SIZE): 16 | matrix.append(input().split()) 17 | coal += matrix[row].count("c") 18 | if "s" in matrix[row]: 19 | start_row, start_col = row, matrix[row].index("s") 20 | 21 | while commands: 22 | direction = commands.popleft() 23 | moving_row, moving_col = start_row + movement[direction][0], start_col + movement[direction][1] 24 | if not 0 <= moving_row < MATRIX_SIZE or not 0 <= moving_col < MATRIX_SIZE: 25 | continue 26 | 27 | symbol = matrix[moving_row][moving_col] 28 | 29 | if symbol == "e": 30 | print(f"Game over! {moving_row, moving_col}") 31 | break 32 | 33 | if symbol == "c": 34 | matrix[moving_row][moving_col] = "*" 35 | collected_coal += 1 36 | 37 | if collected_coal == coal: 38 | print(f"You collected all coal! {moving_row, moving_col}") 39 | break 40 | 41 | start_row, start_col = moving_row, moving_col 42 | else: 43 | print(f"{coal - collected_coal} pieces of coal left. {moving_row, moving_col}") 44 | 45 | 46 | 47 | 48 | # field_numbers = int(input()) 49 | # commands = input().split() 50 | # mine_field = [input().split() for _ in range(field_numbers)] 51 | # 52 | # command_movement = { 53 | # "up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1] 54 | # } 55 | # 56 | # 57 | # def find_starting_position(): 58 | # total_coal = 0 59 | # for row in range(field_numbers): 60 | # if "s" in mine_field[row]: 61 | # row_find, col_find = row, mine_field[row].index("s") 62 | # total_coal += mine_field[row].count("c") 63 | # return row_find, col_find, total_coal 64 | # 65 | # 66 | # row, col, total_coal = find_starting_position() 67 | # 68 | # 69 | # def check_valid_index(col, row): 70 | # if 0 <= row < field_numbers and 0 <= col < len(mine_field[row]): 71 | # return True 72 | # 73 | # 74 | # def end_route(col, row): 75 | # if mine_field[row][col] == "e": 76 | # print(f"Game over! ({row}, {col})") 77 | # exit() 78 | # 79 | # 80 | # def coal_position(col, row, coal): 81 | # if mine_field[row][col] == "c": 82 | # mine_field[row][col] = "*" 83 | # coal -= 1 84 | # return coal 85 | # 86 | # 87 | # def check_movement(col, row, coal): 88 | # end_route(col, row) 89 | # return col, row, coal_position(col, row, coal) 90 | # 91 | # 92 | # for command in commands: 93 | # row_check, col_check = row + command_movement[command][0], col + command_movement[command][1] 94 | # if check_valid_index(col_check, row_check): 95 | # col, row, total_coal = check_movement(col_check, row_check, total_coal) 96 | # if total_coal == 0: 97 | # print(f"You collected all coal! ({row}, {col})") 98 | # break 99 | # else: 100 | # print(f"{total_coal} pieces of coal left. ({row}, {col})") 101 | 102 | 103 | # field_numbers = int(input()) 104 | # commands = input().split() 105 | # mine_field = [input().split() for _ in range(field_numbers)] 106 | # 107 | # 108 | # def find_starting_position(): 109 | # total_coal = 0 110 | # for col in range(len(mine_field)): 111 | # if "s" in mine_field[col]: 112 | # colon = col 113 | # row = mine_field[col].index("s") 114 | # if "c" in mine_field[col]: 115 | # total_coal += mine_field[col].count("c") 116 | # return row, colon, total_coal 117 | # 118 | # 119 | # col, row, total_coal = find_starting_position() 120 | # 121 | # 122 | # def check_valid_index(col, row): 123 | # if 0 <= row < len(mine_field) and 0 <= col < len(mine_field[row]): 124 | # return True 125 | # 126 | # 127 | # def end_of_route(col, row): 128 | # if mine_field[row][col] == "e": 129 | # print(f"Game over! ({row}, {col})") 130 | # exit() 131 | # 132 | # 133 | # def coal_position(col, row, coal): 134 | # if mine_field[row][col] == "c": 135 | # mine_field[row][col] = "*" 136 | # coal -= 1 137 | # return coal 138 | # 139 | # 140 | # def up(col, row, total_coal): 141 | # if check_valid_index(row - 1, col): 142 | # row -= 1 143 | # end_of_route(col, row) 144 | # total_coal = coal_position(col, row, total_coal) 145 | # return col, row, total_coal 146 | # 147 | # 148 | # def down(col, row, total_coal): 149 | # if check_valid_index(row + 1, col): 150 | # row += 1 151 | # end_of_route(col, row) 152 | # total_coal = coal_position(col, row, total_coal) 153 | # return col, row, total_coal 154 | # 155 | # 156 | # def left(col, row, total_coal): 157 | # if check_valid_index(row, col - 1): 158 | # col -= 1 159 | # end_of_route(col, row) 160 | # total_coal = coal_position(col, row, total_coal) 161 | # return col, row, total_coal 162 | # 163 | # 164 | # def right(col, row, total_coal): 165 | # if check_valid_index(row, col + 1): 166 | # col += 1 167 | # end_of_route(col, row) 168 | # total_coal = coal_position(col, row, total_coal) 169 | # return col, row, total_coal 170 | # 171 | # 172 | # command_dic = { 173 | # "up": up, 174 | # "down": down, 175 | # "left": left, 176 | # "right": right 177 | # 178 | # } 179 | # for command in commands: 180 | # col, row, total_coal = command_dic[command](col, row, total_coal) 181 | # if total_coal == 0: 182 | # print(f"You collected all coal! ({row}, {col})") 183 | # break 184 | # else: 185 | # print(f"{total_coal} pieces of coal left. ({row}, {col})") 186 | # 187 | # 188 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/1_flatten_lists.py: -------------------------------------------------------------------------------- 1 | matrix = input().split("|")[::-1] 2 | 3 | for row in range(len(matrix)): 4 | for num in matrix[row].split(): 5 | print(num, end=" ") 6 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/2_matrix_modification.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | matrix = [[int(x) for x in input().split()] for _ in range(rows)] 3 | cols = len(matrix[0]) 4 | 5 | 6 | def check_valid_index(row, col): 7 | if 0 <= row < rows and 0 <= col < cols: 8 | return True 9 | print("Invalid coordinates") 10 | 11 | 12 | def add_to_matrix(row, col, value, operator): 13 | if check_valid_index(row, col): 14 | if "Add" in operator: 15 | matrix[row][col] += value 16 | else: 17 | matrix[row][col] -= value 18 | 19 | 20 | command = input() 21 | while command != "END": 22 | command_type, row, col, value = [int(x) if x[-1].isdigit() else x for x in command.split()] 23 | add_to_matrix(row, col, value, command_type) 24 | command = input() 25 | 26 | [print(*matrix[row]) for row in range(rows)] 27 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/3_knight_game.py: -------------------------------------------------------------------------------- 1 | rows = int(int(input())) 2 | 3 | pos_knights, matrix, total_knights = [], [], [0] 4 | for row in range(rows): 5 | matrix.append(list(input())) 6 | for col in range(len(matrix[0])): 7 | if matrix[row][col] == "K": 8 | pos_knights.append([row, col]) 9 | 10 | cols = len(matrix[0]) 11 | 12 | 13 | def check_valid_index(row, col): 14 | if 0 <= row < rows and 0 <= col < cols: 15 | return True 16 | 17 | 18 | movement = { 19 | "up left": [-2, -1], "up right": [-2, 1], "down left": [2, -1], "down right": [2, 1], 20 | "left up": [-1, -2], "left down": [1, -2], "right up": [-1, 2], "right down": [1, 2], 21 | } 22 | 23 | 24 | def check_knights(): 25 | result = {} 26 | for row, col in pos_knights: 27 | for m_row, m_col in movement.values(): 28 | knight_row, knight_col = row + m_row, col + m_col 29 | if check_valid_index(knight_row, knight_col) and matrix[knight_row][knight_col] == "K": 30 | result[f"{row} {col}"] = result.get(f"{row} {col}", 0) + 1 31 | if not result: 32 | return 33 | total_knights[0] += 1 34 | row, col = [int(x) for x in max(result, key=result.get).split()] 35 | matrix[row][col] = "0" 36 | pos_knights.remove([row, col]) 37 | check_knights() 38 | 39 | 40 | check_knights() 41 | print(total_knights[0]) 42 | 43 | 44 | 45 | 46 | # rows = int(int(input())) 47 | # matrix = [[x for x in input()] for _ in range(rows)] 48 | # cols = len(matrix[0]) 49 | # total_knights = [0] 50 | # 51 | # 52 | # def check_valid_index(row, col): 53 | # if 0 <= row < rows and 0 <= col < cols: 54 | # return True 55 | # 56 | # 57 | # movement = { 58 | # "up left": [-2, -1], "up right": [-2, 1], 59 | # "down left": [2, -1], "down right": [2, 1], 60 | # "left up": [-1, -2], "left down": [1, -2], 61 | # "right up": [-1, 2], "right down": [1, 2], 62 | # } 63 | # 64 | # 65 | # def find_all_knights(): 66 | # positions = [] 67 | # for row in range(rows): 68 | # for col in range(cols): 69 | # if matrix[row][col] == "K": 70 | # positions.append(row) 71 | # positions.append(col) 72 | # return positions 73 | # 74 | # 75 | # while True: 76 | # pos_knights = find_all_knights() 77 | # result = {} 78 | # for i in range(0, len(pos_knights), 2): 79 | # row, col = pos_knights[i], pos_knights[i + 1] 80 | # for m_row, m_col in movement.values(): 81 | # knight_row, knight_col = row + m_row, col + m_col 82 | # if check_valid_index(knight_row, knight_col): 83 | # if matrix[knight_row][knight_col] == "K": 84 | # result[f"{row} {col}"] = result.get(f"{row} {col}", 0) + 1 85 | # if sum(result.values()) == 0: 86 | # break 87 | # total_knights[0] += 1 88 | # row, col = max(result, key=result.get).split() 89 | # matrix[int(row)][int(col)] = "0" 90 | 91 | 92 | 93 | # def check_knights(pos_knights): 94 | # result = {} 95 | # for i in range(0, len(pos_knights), 2): 96 | # row, col = pos_knights[i], pos_knights[i + 1] 97 | # for m_row, m_col in movement.values(): 98 | # knight_row, knight_col = row + m_row, col + m_col 99 | # if check_valid_index(knight_row, knight_col): 100 | # if matrix[knight_row][knight_col] == "K": 101 | # result[f"{row} {col}"] = result.get(f"{row} {col}", 0) + 1 102 | # if sum(result.values()) == 0: 103 | # return 104 | # total_knights[0] += 1 105 | # row, col = max(result, key=result.get).split() 106 | # matrix[int(row)][int(col)] = "0" 107 | # check_knights(find_all_knights()) 108 | 109 | 110 | # print(total_knights[0]) -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/4_easter_bunny.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | matrix = [[int(x) if x[-1].isdigit() else x for x in input().split()] for _ in range(rows)] 3 | 4 | cols, result, directions = len(matrix[0]), {}, { 5 | "up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1] 6 | } 7 | 8 | 9 | def find_starting_position(): 10 | for row in range(rows): 11 | if "B" in matrix[row]: 12 | return row, matrix[row].index("B") 13 | 14 | 15 | def check_valid_index(row, col): 16 | if 0 <= row < rows and 0 <= col < cols and matrix[row][col] != "X": 17 | return True 18 | 19 | 20 | bunny_row, bunny_col = find_starting_position() 21 | 22 | 23 | def movement(): 24 | for direction, (row, col) in directions.items(): 25 | bunny_move_row, bunny_move_col = bunny_row + row, bunny_col + col 26 | for jump in range(cols): 27 | if check_valid_index(bunny_move_row, bunny_move_col): 28 | result[direction] = result.get(direction, 0) + matrix[bunny_move_row][bunny_move_col] 29 | bunny_move_row, bunny_move_col = row + bunny_move_row, col + bunny_move_col 30 | else: 31 | break 32 | 33 | 34 | movement() 35 | if sum(result.values()) != 0: 36 | max_direction = max(result, key=result.get) 37 | print(max_direction) 38 | for path in range(cols): 39 | print_row, print_col = bunny_row + directions[max_direction][0], bunny_col + directions[max_direction][1] 40 | if check_valid_index(print_row, print_col): 41 | print(f"[{print_row}, {print_col}]") 42 | bunny_row, bunny_col = print_row, print_col 43 | else: 44 | break 45 | print(result[max_direction]) 46 | 47 | 48 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/5_alice_in_wonderland.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | matrix = [[x for x in input().split()] for _ in range(rows)] 3 | cols = len(matrix[0]) 4 | 5 | score, movement = [0], {"up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1]} 6 | 7 | 8 | def check_movement(row, col): 9 | if 0 <= row < rows and 0 <= col < cols and matrix[row][col] != "R": 10 | return True 11 | print("Alice didn't make it to the tea party.") 12 | rabit_row, rabit_col = find_position("R", False) 13 | if rabit_row + rabit_col == row + col: 14 | matrix[row][col] = "*" 15 | show_result() 16 | exit() 17 | 18 | 19 | def find_position(symbol, alice=True): 20 | for row in range(rows): 21 | if symbol in matrix[row]: 22 | col = matrix[row].index(symbol) 23 | if alice: 24 | matrix[row][col] = "*" 25 | return row, col 26 | 27 | 28 | alice_row, alice_col = find_position("A") 29 | 30 | 31 | def alice_movement(row, col, movement_pos): 32 | move_row, move_col = row + movement[movement_pos][0], col + movement[movement_pos][1] 33 | if check_movement(move_row, move_col): 34 | if matrix[move_row][move_col][-1].isdigit(): 35 | score[0] += int(matrix[move_row][move_col]) 36 | matrix[move_row][move_col] = "*" 37 | return move_row, move_col 38 | 39 | 40 | def show_result(): 41 | [print(*matrix[row]) for row in range(rows)] 42 | 43 | 44 | while score[0] < 10: 45 | command = input() 46 | alice_row, alice_col = alice_movement(alice_row, alice_col, command) 47 | 48 | print("She did it! She went to the party.") 49 | show_result() 50 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/6_range_day.py: -------------------------------------------------------------------------------- 1 | SIZE_MATRIX = 5 2 | matrix = [[x for x in input().split()] for _ in range(SIZE_MATRIX)] 3 | dead_targets_pos, number_of_commands = [], int(input()) 4 | total_targets = [sum([matrix[row].count("x") for row in range(SIZE_MATRIX)])] 5 | directions = {"up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1]} 6 | 7 | 8 | def check_valid_index(row, col): 9 | if 0 <= row < SIZE_MATRIX and 0 <= col < SIZE_MATRIX: 10 | return True 11 | 12 | 13 | def find_position(): 14 | for row in range(SIZE_MATRIX): 15 | if "A" in matrix[row]: 16 | col = matrix[row].index("A") 17 | matrix[row][col] = "." 18 | return row, col 19 | 20 | 21 | player_row, player_col = find_position() 22 | 23 | 24 | def shoot(row, col, direction): 25 | for shoot in range(SIZE_MATRIX): 26 | shooting_row, shooting_col = row + directions[direction][0], col + directions[direction][1] 27 | if check_valid_index(shooting_row, shooting_col): 28 | if matrix[shooting_row][shooting_col] == "x": 29 | total_targets[0] -= 1 30 | dead_targets_pos.append([shooting_row, shooting_col]) 31 | matrix[shooting_row][shooting_col] = "." 32 | break 33 | row, col = shooting_row, shooting_col 34 | else: 35 | break 36 | 37 | 38 | def moving(row, col, direction, steps): 39 | total_step = [x * steps if x != 0 else 0 for x in directions[direction]] 40 | moving_row, moving_col = row + total_step[0], col + total_step[1] 41 | if check_valid_index(moving_row, moving_col) and matrix[moving_row][moving_col] == ".": 42 | matrix[row][col] = "." 43 | matrix[moving_row][moving_col] = "A" 44 | return moving_row, moving_col 45 | return row, col 46 | 47 | 48 | def show_result(): 49 | [print(x) for x in dead_targets_pos] 50 | 51 | 52 | for _ in range(number_of_commands): 53 | command = input().split() 54 | if "shoot" in command[0]: 55 | shoot(player_row, player_col, command[1]) 56 | elif "move" in command[0]: 57 | player_row, player_col = moving(player_row, player_col, command[1], int(command[-1])) 58 | if total_targets[0] == 0: 59 | print(f"Training completed! All {len(dead_targets_pos)} targets hit.") 60 | show_result() 61 | break 62 | else: 63 | print(f"Training not completed! {total_targets[0]} targets left.") 64 | show_result() 65 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Exercise 2/7_present_delivery.py: -------------------------------------------------------------------------------- 1 | presents = [int(input())] 2 | rows = int(input()) 3 | matrix = [[x for x in input().split()] for x in range(rows)] 4 | cols, total_nice_kids = len(matrix[0]), [[sum([matrix[row].count("V") for row in range(rows)])] * 2] 5 | directions = {"up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1]} 6 | 7 | 8 | def check_valid_index(row, col): 9 | if 0 <= row < rows and 0 <= col < cols: 10 | return True 11 | 12 | 13 | def find_position(): 14 | for row in range(rows): 15 | if "S" in matrix[row]: 16 | col = matrix[row].index("S") 17 | matrix[row][col] = "-" 18 | return row, col 19 | 20 | 21 | def check_where_he_steps(row, col, cookie=False): 22 | if matrix[row][col] == "V": 23 | total_nice_kids[0][0] -= 1 24 | presents[0] -= 1 25 | elif cookie and matrix[row][col] == "X": 26 | presents[0] -= 1 27 | elif matrix[row][col] == "C": 28 | cookie_time(row, col) 29 | matrix[row][col] = "-" 30 | 31 | 32 | def cookie_time(row, col): 33 | for added_row, added_col in directions.values(): 34 | moving_row, moving_col = row + added_row, col + added_col 35 | if check_valid_index(moving_row, moving_col): 36 | check_where_he_steps(moving_row, moving_col, True) 37 | 38 | 39 | def santa_move(row, col, direction): 40 | santa_moving_row, santa_moving_col = row + directions[direction][0], col + directions[direction][1] 41 | if check_valid_index(santa_moving_row, santa_moving_col): 42 | check_where_he_steps(santa_moving_row, santa_moving_col) 43 | return santa_moving_row, santa_moving_col 44 | 45 | 46 | def check_for_end(): 47 | if total_nice_kids[0][0] == 0: 48 | show_result(santa_row, santa_col) 49 | print(f"Good job, Santa! {total_nice_kids[0][1]} happy nice kid/s.") 50 | exit() 51 | if presents[0] == 0 and total_nice_kids[0][0] > 0: 52 | print("Santa ran out of presents!") 53 | show_result(santa_row, santa_col) 54 | print(f"No presents for {total_nice_kids[0][0]} nice kid/s.") 55 | exit() 56 | if presents[0] == 0: 57 | show_result(santa_row, santa_col) 58 | print(f"No presents for {total_nice_kids[0][0]} nice kid/s.") 59 | exit() 60 | 61 | 62 | def show_result(row, col): 63 | matrix[row][col] = "S" 64 | [print(*matrix[row]) for row in range(rows)] 65 | 66 | 67 | santa_row, santa_col = find_position() 68 | command = input() 69 | 70 | while command != "Christmas morning": 71 | santa_row, santa_col = santa_move(santa_row, santa_col, command) 72 | check_for_end() 73 | command = input() 74 | 75 | show_result(santa_row, santa_col) 76 | print(f"No presents for {total_nice_kids[0][0]} nice kid/s.") 77 | 78 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/1_sum_matrix_elements.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split(", ")] 2 | matrix = [[int(x) for x in input().split(", ")] for _ in range(rows)] 3 | print(sum(list(map(sum, zip(*matrix))))) 4 | # print(sum([sum(idx) for idx in zip(*matrix)])) 5 | print(matrix) -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/2_even_Matrix.py: -------------------------------------------------------------------------------- 1 | print([[int(x) for x in input().split(", ") if int(x) % 2 == 0] for _ in range(int(input()))]) 2 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/3_flattening_matrix.py: -------------------------------------------------------------------------------- 1 | print([int(x) for _ in range(int(input())) for x in input().split(", ")]) -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/4_sum_matrix_columns.py: -------------------------------------------------------------------------------- 1 | rows, cols = [int(x) for x in input().split(", ")] 2 | result = list(map(sum, zip(*[[int(x) for x in input().split()] for _ in range(rows)]))) 3 | [print(x) for x in result] 4 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/5_primary_diagonal.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | matrix = [[x for x in input().split()] for _ in range(rows)] 3 | [print(sum(int(matrix[i][i]) for i in range(rows)))] 4 | 5 | 6 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/6_symbol_in_matrix.py: -------------------------------------------------------------------------------- 1 | rows = int(input()) 2 | matrix = [input() for _ in range(rows)] 3 | symbol_to_find = input() 4 | 5 | 6 | def find_symbol(symbol): 7 | for row in range(rows): 8 | if symbol in matrix[row]: 9 | return row, matrix[row].find(symbol) 10 | return f"{symbol} does not occur in the matrix" 11 | 12 | 13 | print(find_symbol(symbol_to_find)) 14 | 15 | 16 | 17 | # for row in range(rows): 18 | # if symbol_to_find in matrix[row]: 19 | # print(f"({row}, {matrix[row].index(symbol_to_find)})") 20 | # break 21 | # else: 22 | # print(f"{symbol_to_find} does not occur in the matrix") 23 | -------------------------------------------------------------------------------- /4. Multidimensional Lists/Multidimensional Lists - Lab/7_square_with_maximum_sum.py: -------------------------------------------------------------------------------- 1 | rows, colons = [int(x) for x in input().split(", ")] 2 | 3 | matrix_list = [[int(x) for x in input().split(", ")] for row in range(rows)] 4 | max_sum = {"max number": -181, 5 | "row": 0, 6 | "col": 0} 7 | 8 | 9 | def check_valid_index(row, col): 10 | if 0 <= row + 2 <= rows and 0 <= col + 2 <= colons: 11 | return True 12 | 13 | 14 | def sum_square(row, col): 15 | if check_valid_index(row, col): 16 | sum_total = 0 17 | for row_check in range(row, row + 2): 18 | sum_total += sum(matrix_list[row_check][col: col + 2]) 19 | if max_sum["max number"] < sum_total: 20 | max_sum["max number"] = sum_total 21 | max_sum["row"] = row 22 | max_sum["col"] = col 23 | 24 | 25 | for row in range(rows): 26 | for col in range(colons): 27 | sum_square(row, col) 28 | 29 | for row in range(max_sum["row"], max_sum["row"] + 2): 30 | print(" ".join([str(x) for x in matrix_list[row][max_sum["col"]: max_sum["col"] + 2]])) 31 | print(max_sum['max number']) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/10_fill_the_box.py: -------------------------------------------------------------------------------- 1 | def fill_the_box(*args): 2 | height, length, width, *data = args 3 | size_of_the_box = height * length * width 4 | no_free_space = 0 5 | for symbol in data: 6 | if symbol == "Finish": 7 | break 8 | if size_of_the_box - symbol <= 0: 9 | symbol -= size_of_the_box 10 | size_of_the_box = 0 11 | if size_of_the_box > 0: 12 | size_of_the_box -= symbol 13 | else: 14 | no_free_space += symbol 15 | 16 | if size_of_the_box > 0: 17 | return f"There is free space in the box. You could put {size_of_the_box} more cubes." 18 | 19 | return f"No more free space! You have {no_free_space} more cubes." 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | print(fill_the_box(5, 5, 2, 40, 11, 7, 3, 1, 5, "Finish")) 28 | print(fill_the_box(10, 10, 10, 40, "Finish", 2, 15, 30)) 29 | print(fill_the_box(2, 8, 2, 2, 1, 7, 3, 1, 5, "Finish")) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/11_math_operations.py: -------------------------------------------------------------------------------- 1 | def math_operations(*args, **kwargs): 2 | result, pos = "", 1 3 | for num in args: 4 | if pos == 1: 5 | kwargs["a"] += num 6 | elif pos == 4: 7 | kwargs["m"] *= num 8 | elif pos == 2: 9 | kwargs["s"] -= num 10 | elif pos == 3: 11 | if num != 0: 12 | kwargs["d"] /= num 13 | pos += 1 14 | if pos > 4: 15 | pos = 1 16 | for key, value in sorted(kwargs.items(), key=lambda x: (-x[1], x[0])): 17 | result += f"{key}: {value:.1f}\n" 18 | 19 | return result 20 | 21 | 22 | # print(math_operations(2.1, 12.56, 0.0, -3.899, 6.0, -20.65, a=1, s=7, d=33, m=15)) 23 | print(math_operations(-1.0, 0.5, 1.6, 0.5, 6.1, -2.8, 80.0, a=0, s=(-2.3), d=0, m=0)) 24 | # print(math_operations(6.0, a=0, s=0, d=5, m=0)) 25 | 26 | 27 | # 3.1 + 6, 12.56 - 7 - , 0, -3.899*15 28 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/1_negative_vs_positive.py: -------------------------------------------------------------------------------- 1 | def negative_vs_positive(data): 2 | min_number = data.index(min([x for x in data if x > 0])) # O(n) + O(n) , ind 0(1) 3 | positive_numbers = sum(data[min_number:]) # O(k+n) 4 | negative_numbers = sum(data[:min_number]) # O(k+n) 5 | 6 | if positive_numbers > abs(negative_numbers): 7 | text = "The positives are stronger than the negatives" 8 | else: 9 | text = "The negatives are stronger than the positives" 10 | return f"{negative_numbers}\n{positive_numbers}\n{text}" 11 | 12 | 13 | input_numbers = sorted(int(x) for x in input().split()) # O(n log n) 14 | print(negative_vs_positive(input_numbers)) 15 | 16 | 17 | # def negative_vs_positive(data): 18 | # positive_numbers = 0 19 | # negative_numbers = 0 20 | # for num in data: 21 | # if num > 0: 22 | # positive_numbers += num 23 | # else: 24 | # negative_numbers -= num 25 | # 26 | # if positive_numbers > abs(negative_numbers): 27 | # text = "The positives are stronger than the negatives" 28 | # else: 29 | # text = "The negatives are stronger than the positives" 30 | # return f"-{negative_numbers}\n{positive_numbers}\n{text}" 31 | # 32 | # 33 | # input_numbers = [int(x) for x in input().split()] 34 | # print(negative_vs_positive(input_numbers)) 35 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/2_keyword_arguments_length.py: -------------------------------------------------------------------------------- 1 | dictionary = {'name': 'Peter', 'age': 25} 2 | 3 | 4 | def kwargs_length(**kwargs): 5 | return len(kwargs) 6 | 7 | 8 | print(kwargs_length(**dictionary)) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/3_even_or_odd.py: -------------------------------------------------------------------------------- 1 | def even_odd(*args): 2 | *numbers, command = args 3 | if command == "even": 4 | return [x for x in numbers if x % 2 == 0] 5 | return [x for x in numbers if x % 2 != 0] 6 | 7 | 8 | print(even_odd(1, 2, 3, 4, 5, 6, "even")) 9 | print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd")) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/4_numbers_filter.py: -------------------------------------------------------------------------------- 1 | def even_odd_filter(**kwargs): 2 | result = {} 3 | for type_numbers, numbers in kwargs.items(): 4 | if type_numbers == "even": 5 | result[type_numbers] = [x for x in numbers if x % 2 == 0] 6 | elif type_numbers == "odd": 7 | result[type_numbers] = [x for x in numbers if x % 2 != 0] 8 | return dict(sorted(result.items())) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/5_concatenate.py: -------------------------------------------------------------------------------- 1 | def concatenate(*args, **kwargs): 2 | main_string = ''.join(args) 3 | for key_to_check, string_to_change in kwargs.items(): 4 | if key_to_check in main_string: 5 | main_string = main_string.replace(key_to_check, string_to_change) 6 | return main_string 7 | 8 | 9 | print(concatenate("I", " ", "Love", " ", "Cythons", C="P", s="", java='Java')) 10 | print(concatenate("Soft", "UNI", "Is", "Grate", "!", UNI="Uni", Grate="Great")) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/6_function_executor.py: -------------------------------------------------------------------------------- 1 | def sum_numbers(num1, num2): 2 | return num1 + num2 3 | 4 | 5 | def multiply_numbers(num1, num2): 6 | return num1 * num2 7 | 8 | 9 | def make_upper(*strings): 10 | result = tuple(s.upper() for s in strings) 11 | return result 12 | 13 | 14 | def make_lower(*strings): 15 | result = tuple(s.lower() for s in strings) 16 | return result 17 | 18 | 19 | def func_executor(*args): 20 | result = "" 21 | for func_name, func_arg in args: 22 | result += f"{func_name.__name__} - {func_name(*func_arg)}\n" 23 | return result 24 | 25 | 26 | print(func_executor( 27 | (sum_numbers, (1, 2)), 28 | (multiply_numbers, (2, 4)) 29 | )) 30 | 31 | 32 | print(func_executor( 33 | (make_upper, ("Python", "softUni")), 34 | (make_lower, ("PyThOn",)), 35 | )) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/7_grocery.py: -------------------------------------------------------------------------------- 1 | def grocery_store(**kwargs): 2 | result = "" 3 | for product_name, quantity in sorted(kwargs.items(), key=lambda x: (-x[1], -len(x[0]), x[0])): 4 | result += f"{product_name}: {quantity}\n" 5 | return result 6 | 7 | ''' 8 | quantity in descending order. If there are two or more products with the same quantity, 9 | sort them by their name's length in descending order. 10 | If there are two or more products with the same name's length, 11 | sort them by their name in ascending order (alphabetically). 12 | In the end, return a string in the following format:''' 13 | 14 | print(grocery_store( 15 | bread=5, 16 | pasta=12, 17 | eggs=12, 18 | )) 19 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/8_age_assignment.py: -------------------------------------------------------------------------------- 1 | def age_assignment(*args, **kwargs): 2 | result = "" 3 | for name in args: 4 | for key in kwargs: 5 | if name[0] == key: 6 | # kwargs[name] = kwargs.pop(key) 7 | kwargs[name] = kwargs[key] 8 | del kwargs[key] 9 | break 10 | for name, age in sorted(kwargs.items(), key= lambda x: x[0]): 11 | result += f"{name} is {age} years old.\n" 12 | return result 13 | 14 | 15 | print(age_assignment("Peter", "George", G=26, P=19)) 16 | print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61)) 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | '''Create a function called age_assignment() that receives a different number of names and a different number of key-value pairs. 25 | The key will be a single letter (the first letter of each name) and the value - a number (age). 26 | Find its first letter in the key-value pairs for each name and assign the age to the person's name. 27 | Then, sort the names in ascending order (alphabetically) and return the information for each person on a new line in the format: 28 | "{name} is {age} years old." 29 | Submit only the function in the judge system.''' -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Exercise/9_recursion_palindrome.py: -------------------------------------------------------------------------------- 1 | def palindrome(word, idx): 2 | if idx == len(word) // 2: 3 | return f"{word} is a palindrome" 4 | if word[idx] == word[-idx-1]: 5 | print(word[-idx-1]) 6 | return palindrome(word, idx+1) 7 | else: 8 | return f"{word} is not a palindrome" 9 | 10 | 11 | print(palindrome("peter", 0)) 12 | print(palindrome("abcba", 0)) 13 | 14 | 15 | # def palindrome(word, idx): 16 | # if word == word[::-1]: 17 | # return f"{word} is a palindrome" 18 | # return f"{word} is not a palindrome" -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/1_multiplication_function.py: -------------------------------------------------------------------------------- 1 | def multiply(*args): 2 | result = 1 3 | for num in args: 4 | result *= num 5 | return result 6 | 7 | 8 | 9 | 10 | print(multiply(1, 4, 5)) 11 | print(multiply(4, 5, 6, 1, 3)) 12 | print(multiply(2, 0, 1000, 5000)) 13 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/2_person_info.py: -------------------------------------------------------------------------------- 1 | def get_info(**kwargs): 2 | return f"This is {kwargs.get('name')} from {kwargs.get('town')} and he is {kwargs.get('age')} years old" 3 | #eturn f"This is {kwargs['name']} from {kwargs['town']} and he is {kwargs['age']} years old" 4 | 5 | 6 | print(get_info(**{"name": "George", "town": "Sofia", "age": 20})) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/3_cheese_showcase.py: -------------------------------------------------------------------------------- 1 | def sorting_cheeses(**kwargs): 2 | result = "" 3 | for cheese, quantities in sorted(kwargs.items(), key=lambda x: (-len(x[1]), x[0])): 4 | result += f"{cheese}\n" + "\n".join(str(x) for x in sorted(quantities, reverse=True)) + "\n" 5 | # result += "\n" 6 | return result 7 | 8 | 9 | '''Camembert 10 | 500 11 | 430 12 | 105 13 | 100 14 | 100 15 | ''' 16 | print( 17 | sorting_cheeses( 18 | Parmesan=[102, 120, 135], 19 | Camembert=[100, 100, 105, 500, 430], 20 | Mozzarella=[50, 125], 21 | ) 22 | ) 23 | 24 | print( 25 | sorting_cheeses( 26 | Parmigiano=[165, 215], 27 | Feta=[150, 515], 28 | Brie=[150, 125] 29 | ) 30 | ) -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/4_rectangle.py: -------------------------------------------------------------------------------- 1 | # def rectangle(*args): 2 | # # if any([True for x in args if not isinstance(x, int)]): 3 | # 4 | # if not all([True if isinstance(x, int) else False for x in args]): 5 | # return "Enter valid values!" 6 | # 7 | # def area(): 8 | # return args[0] * args[1] 9 | # 10 | # def perimeter(): 11 | # return (args[0] + args[1]) * 2 12 | # 13 | # return f"Rectangle area: {area()}\nRectangle perimeter: {perimeter()}" 14 | # 15 | 16 | 17 | def rectangle(length, width): 18 | if not all([isinstance(x, int) for x in [length, width]]): 19 | return "Enter valid values!" 20 | 21 | def area(): 22 | return length * width 23 | 24 | def perimeter(): 25 | return (length + width) * 2 26 | 27 | return f"Rectangle area: {area()}\nRectangle perimeter: {perimeter()}" 28 | 29 | 30 | 31 | 32 | print(rectangle(2, 10)) 33 | print(rectangle('2', 10)) 34 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/5_operate.py: -------------------------------------------------------------------------------- 1 | def operate(operator, *args): 2 | result = args[0] 3 | if operator == "+": 4 | result = sum(args) 5 | elif operator == "-": 6 | for x in args[1:]: 7 | result -= x 8 | elif operator == "/": 9 | for x in args[1:]: 10 | result /= x 11 | elif operator == "*": 12 | for x in args[1:]: 13 | result *= x 14 | return result 15 | 16 | 17 | # from functools import reduce 18 | # 19 | # 20 | # def operate(operator, *args): 21 | # if operator == "+": 22 | # return reduce(lambda x, y: x + y, args) 23 | # elif operator == "-": 24 | # return reduce(lambda x, y: x - y, args) 25 | # elif operator == "*": 26 | # return reduce(lambda x, y: x * y, args) 27 | # elif operator == "/": 28 | # return reduce(lambda x, y: x / y, args) 29 | 30 | 31 | '''((((1+2)+3)+4)+5)''' 32 | # def operate(operator, *args): 33 | # return reduce(lambda x, y: eval(f"{x} {operator} {y}"), args) 34 | 35 | '''x = 1 36 | eval('x+1') 37 | 2''' 38 | print(operate("+", 1, 2, 3)) 39 | print(operate("*", 3, 4)) 40 | -------------------------------------------------------------------------------- /5. Functions Advanced/Functions Advanced - Lab/6_recursive_power.py: -------------------------------------------------------------------------------- 1 | def recursive_power(number, power): 2 | if power == 0: 3 | return 1 4 | return number * recursive_power(number, power - 1) 5 | 6 | 7 | print(recursive_power(2, 10)) 8 | print(recursive_power(10, 100)) -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Exercise/01_numbers_dictionary.py: -------------------------------------------------------------------------------- 1 | numbers_dictionary = {} 2 | 3 | while True: 4 | line = input() 5 | 6 | if line == "Search": 7 | break 8 | 9 | number_as_string = line 10 | 11 | try: 12 | number = int(input()) 13 | numbers_dictionary[number_as_string] = number 14 | except: 15 | print("The variable number must be an integer") 16 | 17 | while True: 18 | line = input() 19 | 20 | if line == "Remove": 21 | break 22 | 23 | searched = line 24 | 25 | if searched not in numbers_dictionary: 26 | print("Number does not exist in dictionary") 27 | else: 28 | print(numbers_dictionary[searched]) 29 | 30 | while True: 31 | line = input() 32 | 33 | if line == "End": 34 | break 35 | 36 | searched = line 37 | 38 | if searched not in numbers_dictionary: 39 | print("Number does not exist in dictionary") 40 | else: 41 | del numbers_dictionary[searched] 42 | 43 | print(numbers_dictionary) 44 | -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Exercise/02_email_validator.py: -------------------------------------------------------------------------------- 1 | class MustContainAtSymbolError(Exception): 2 | """Email does not have @ """ 3 | pass 4 | 5 | 6 | class NameTooShortError(Exception): 7 | """ Name less than or equal to 4 characters""" 8 | pass 9 | 10 | 11 | class InvalidDomainError(Exception): 12 | """ the domain is different than .com, .org... """ 13 | pass 14 | 15 | 16 | MIN_NAME_LEN = 5 17 | VALID_DOMAINS = ("com", "net", "bg", "org") 18 | 19 | 20 | def validate_email(email): 21 | if "@" not in email: 22 | raise MustContainAtSymbolError("Email must contain @") 23 | 24 | if len(email.split("@")[0]) < MIN_NAME_LEN: 25 | raise NameTooShortError("Name must be more than 4 characters") 26 | 27 | if email.split(".")[-1] not in VALID_DOMAINS: 28 | raise InvalidDomainError("Domain must be one of the following: .com, .bg, .org, .net") 29 | 30 | print("Email is valid") 31 | 32 | 33 | while True: 34 | email = input() 35 | 36 | if email == "End": 37 | break 38 | validate_email(email) 39 | -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Exercise/Error-Handling - Exercise.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ip681/python-advanced/d4fd461144d6eb149cc26f53728e27658bdc3109/6. Error Handling/Error-Handling - Exercise/Error-Handling - Exercise.rar -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Lab/01_so_many_exceptions.py: -------------------------------------------------------------------------------- 1 | numbers_list = [int(x) for x in input().split(", ")] 2 | result = 1 3 | 4 | for number in numbers_list: 5 | if number <= 5: 6 | result *= number 7 | elif number <= 10: 8 | result /= number 9 | 10 | print(result) 11 | -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Lab/02_value_can_not_be_negative.py: -------------------------------------------------------------------------------- 1 | class ValueCannotBeNegativeError(Exception): 2 | def __init__(self, value): 3 | super().__init__(f"{value} is negative") 4 | 5 | 6 | def validate_positive_numbers(nums): 7 | for n in nums: 8 | if n < 0: 9 | raise ValueCannotBeNegativeError(n) 10 | 11 | 12 | numbers = [1, 2, -3, 4, 5] 13 | 14 | validate_positive_numbers(numbers) 15 | print("Numbers are positive") 16 | -------------------------------------------------------------------------------- /6. Error Handling/Error-Handling - Lab/03_repeat_text.py: -------------------------------------------------------------------------------- 1 | def repeat_text(txt, cnt): 2 | return txt * int(cnt) 3 | 4 | 5 | text = "Hello" 6 | count = "asd" # "asd" 7 | 8 | try: 9 | print(repeat_text(text, count)) 10 | except ValueError: 11 | print("Variable times must be an integer") 12 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/01_even_lines.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def replace_punctuation(row): 5 | return re.sub(r"[.\,\!\?-]", "@", row) 6 | 7 | 8 | def print_even_lines(): 9 | with open("text.txt", "r") as file: 10 | rows = file.readlines() 11 | for row in range(len(rows)): 12 | if row % 2 == 0: 13 | replaced = replace_punctuation(rows[row]).split() 14 | print(" ".join(replaced[::-1])) 15 | 16 | 17 | print_even_lines() 18 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/02_line_numbers.py: -------------------------------------------------------------------------------- 1 | from string import punctuation 2 | from string import ascii_letters 3 | 4 | 5 | def read_file_content(): 6 | with open("text.txt", "r") as file: 7 | return file.readlines() 8 | 9 | 10 | def find_punctuations(txt): 11 | return [ch for ch in txt if ch in punctuation] 12 | 13 | 14 | def find_letters(txt): 15 | return [ch for ch in txt if ch in ascii_letters] 16 | 17 | 18 | def print_result(): 19 | file_content = read_file_content() 20 | 21 | counter = 1 22 | for row in file_content: 23 | punctuations = find_punctuations(row) 24 | letters = find_letters(row) 25 | print(f"Line {counter}: {row[:-1]} ({len(letters)})({len(punctuations)})") 26 | counter += 1 27 | 28 | 29 | print_result() 30 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/03_file_manipulator.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | """Using this while debugging""" 4 | 5 | 6 | # def read_file(path): 7 | # if os.path.exists(path): 8 | # with open(path, "r") as file: 9 | # open_file = file.readlines() 10 | # return open_file 11 | # return "Can't find the f..... file!" 12 | 13 | 14 | def create_file(file_name): 15 | with open(file_name, "w") as file: 16 | file.write("") 17 | 18 | 19 | def add_content(file_name, content): 20 | if os.path.exists(file_name): 21 | with open(file_name, "a") as file: 22 | file.write(f"{content}\n") 23 | else: 24 | create_file(file_name) 25 | with open(file_name, "a") as file: 26 | file.write(f"{content}\n") 27 | 28 | 29 | def replace_string(file_name, old_string, new_string): 30 | if not os.path.exists(file_name): 31 | print("An error occurred") 32 | else: 33 | with open(file_name, "r") as file: 34 | text_rows = file.readlines() 35 | for row in range(len(text_rows)): 36 | if old_string in text_rows[row]: 37 | text_rows[row] = text_rows[row].replace(old_string, new_string) 38 | with open(file_name, "w") as new_file: 39 | new_file.write(''.join(text_rows)) 40 | 41 | 42 | def delete_file(file_name): 43 | if not os.path.exists(file_name): 44 | print("An error occurred") 45 | else: 46 | os.remove(file_name) 47 | 48 | 49 | def looping_thru_actions(command): 50 | actions = command.split("-") 51 | action = actions[0] 52 | file_name = actions[1] 53 | if action == "Create": 54 | create_file(file_name) 55 | elif action == "Add": 56 | content = actions[2] 57 | add_content(file_name, content) 58 | elif action == "Replace": 59 | old_string = actions[2] 60 | new_string = actions[3] 61 | replace_string(file_name, old_string, new_string) 62 | elif action == "Delete": 63 | delete_file(file_name) 64 | 65 | 66 | def read_commands(): 67 | while True: 68 | command = input() 69 | if command == "End": 70 | break 71 | 72 | looping_thru_actions(command) 73 | 74 | 75 | read_commands() 76 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/04_directory_traversal.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def take_all_files_from_dir(path): 5 | all_files = [file for file in os.listdir(path) if os.path.isfile(file)] 6 | return all_files 7 | 8 | 9 | def separate_files_by_type(files_list): 10 | files_by_type = {} 11 | for file in files_list: 12 | file_name, file_extension = os.path.splitext(file) 13 | if file_extension not in files_by_type: 14 | files_by_type[file_extension] = [file_name] 15 | else: 16 | files_by_type[file_extension].append(file_name) 17 | return files_by_type 18 | 19 | 20 | def sort_file_alphabetically(files_dict): 21 | sorted_files = sorted(files_dict.items()) 22 | return sorted_files 23 | 24 | 25 | def extract_result(files_dict): 26 | extract_result_text = "" 27 | for file_extension, file_name in files_dict: 28 | extract_result_text += f".{file_extension}\n" 29 | for f_name in file_name: 30 | extract_result_text += f"- - - {f_name}.{file_extension}\n" 31 | extraction_file_name = "file_extraction.txt" 32 | path_to_desktop = os.path.join(os.path.expanduser("~/Desktop"), extraction_file_name) 33 | with open(path_to_desktop, "w") as file: 34 | file.write(extract_result_text) 35 | 36 | 37 | # Could be an input from an Entry widgets in Desktop App. 38 | dir_path = "E:\\Mine\\Python\\Python-Advanced-January-2021\\File-Handling\\File-Handling-Exercise" 39 | 40 | all_files_list = take_all_files_from_dir(dir_path) 41 | separated_files_by_type = separate_files_by_type(all_files_list) 42 | sorted_files_alphabetically = sort_file_alphabetically(separated_files_by_type) 43 | extract_result(sorted_files_alphabetically) 44 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/File-Handling - Exercise.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ip681/python-advanced/d4fd461144d6eb149cc26f53728e27658bdc3109/7. File Handling/File-Handling - Exercise/File-Handling - Exercise.rar -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Exercise/text.txt: -------------------------------------------------------------------------------- 1 | -I was quick to judge him, but it wasn't his fault. 2 | -Is this some kind of joke?! Is it? 3 | -Quick, hide here. It is safer. 4 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/01_file_opener.py: -------------------------------------------------------------------------------- 1 | def open_file(file_name): 2 | try: 3 | with open(file_name, "r") as file: 4 | print("File found") 5 | except FileNotFoundError: 6 | print("File not found") 7 | 8 | 9 | searched_name = "text.txt" 10 | open_file(searched_name) 11 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/02_file_reader.py: -------------------------------------------------------------------------------- 1 | def read_file_from_txt(): 2 | with open("numbers.txt", "r") as file: 3 | result = sum([int(el.strip()) for el in file.readlines()]) 4 | print(result) 5 | 6 | 7 | read_file_from_txt() 8 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/03_file_writer.py: -------------------------------------------------------------------------------- 1 | def create_write_file(): 2 | with open("my_first_file.txt", "w") as file: 3 | file.write("I just created my first file!") 4 | # with open("my_first_file.txt", "a") as file: 5 | # file.write("This is my second row\n") 6 | # file.write("And this is the third one\n") 7 | 8 | 9 | create_write_file() 10 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/04_file_delete.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def delete_file(): 5 | # try: 6 | # os.remove("my_first_file.txt") 7 | # print("Deleted") 8 | # except FileNotFoundError: 9 | # print("File already deleted!") 10 | 11 | if os.path.exists("my_first_file.txt"): 12 | os.remove("my_first_file.txt") 13 | print("Deleted") 14 | else: 15 | print("File already deleted!") 16 | 17 | 18 | delete_file() 19 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/05_word_count.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def get_file_content(path): 5 | with open(path, "r") as file: 6 | text = "".join(file.readlines()) 7 | return re.findall(r"[a-z']+", text.lower()) 8 | 9 | 10 | def count_words(words, text): 11 | res = {} 12 | for word in words: 13 | if word in text: 14 | res[word] = text.count(word) 15 | return res 16 | 17 | 18 | def sort_result(res): 19 | sorted_result = sorted(res.items(), key=lambda x: -x[1]) 20 | return sorted_result 21 | 22 | 23 | def print_result(res): 24 | for key, val in res: 25 | print(f"{key} - {val}") 26 | 27 | 28 | path_to_words = "words.txt" 29 | path_to_text = "text.txt" 30 | 31 | words_file = get_file_content(path_to_words) 32 | text_file = get_file_content(path_to_text) 33 | result = sort_result(count_words(words_file, text_file)) 34 | print_result(result) 35 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/my_first_file.txt: -------------------------------------------------------------------------------- 1 | I just created my first file! -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/numbers.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/text.txt: -------------------------------------------------------------------------------- 1 | -I was quick to judge him, but it wasn't his fault. 2 | -Is this some kind of joke?! Is it? 3 | -Quick, hide here…It is safer. 4 | -------------------------------------------------------------------------------- /7. File Handling/File-Handling - Lab/words.txt: -------------------------------------------------------------------------------- 1 | quick is fault -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-advanced 2 | Python Advanced 3 | --------------------------------------------------------------------------------