├── 00. Mid Exam ├── 01. Task.py ├── 02. Task.py └── 03. Task.py ├── 01. Basic Syntax, Conditional Statements and Loops ├── 01. Basic Syntax, Conditional Statements and Loops - Exercise │ ├── 01. Jenny's Secret Message.py │ ├── 02. Drink something.py │ ├── 03. Chat Codes.py │ ├── 04. Maximum Multiple.py │ ├── 05. Orders.py │ ├── 06. String Pureness.py │ ├── 07. Double Char.py │ ├── 08. How Much Coffee Do You Need.py │ ├── 09. Sorting Hat.py │ ├── 10. Mutate Strings.py │ ├── 11. Easter Bread.py │ └── 12. Christmas Spirit.py ├── 01. Basic Syntax, Conditional Statements and Loops - Lab │ ├── 01. Number Definer.py │ ├── 02. Largest Of Three Numbers.py │ ├── 03. Word Reverse.py │ ├── 04. Even Numbers.py │ ├── 05. Number Between 1 and 100.py │ ├── 06. Shopping.py │ └── 07. Patterns.py └── 01. Basic Syntax, Conditional Statements and Loops - More Exercise │ ├── 01. Find the largest.py │ ├── 02. Find the capitals.py │ ├── 03. Wolf in Sheep's clothing.py │ └── 04. Sum of a Beach.py ├── 02. Data Types and Variables ├── 02. Data Types and Variables - Exercise │ ├── 01. Integer operations.py │ ├── 02. Chars to String.py │ ├── 03. Elevator.py │ ├── 04. Sum of Chars.py │ ├── 05. Print Part of the ASCII Table.py │ ├── 06. Triples of Latin Letters.py │ ├── 07. Water Overflow.py │ ├── 08. Party Profit.py │ ├── 09. Snowballs.py │ └── 10. Gladiator Expenses.py ├── 02. Data Types and Variables - Lab │ ├── 01. Concat Names.py │ ├── 02. Centuries to Minutes.py │ ├── 03. Special Numbers.py │ ├── 04. Convert Meters to Kilometers.py │ ├── 05. Pounds to Dollars.py │ └── 06. Next Happy Year.py └── 02. Data Types and Variables - More Exercise │ ├── 01. Exchange Integers.py │ ├── 02. Prime Number Checker.py │ ├── 03. Decrypting Messages.py │ └── 04. Balanced Brackets.py ├── 03. Lists Basics ├── 03. Lists Basics - Exercise │ ├── 01. Invert Values.py │ ├── 02. Multiples List.py │ ├── 03. Football Cards.py │ ├── 04. Number Beggars.py │ ├── 05. Faro Shuffle.py │ ├── 06. Survival of the Biggest.py │ ├── 07. Easter Gifts.py │ ├── 08. Seize the Fire.py │ ├── 09. Hello, France.py │ └── 10. Bread Factory.py ├── 03. Lists Basics - Lab │ ├── 01. Strange Zoo.py │ ├── 02. Courses.py │ ├── 03. List Statistics.py │ ├── 04. Search.py │ └── 05. Numbers Filter.py └── 03. Lists Basics - More Exercise │ ├── 01. Zeros to Back.py │ ├── 02. Messaging.py │ ├── 03. Car Race.py │ ├── 04. Josephus Permutation.py │ ├── 05. Tic-Tac-Toe.py │ └── 06. List Manipulator.py ├── 04. Functions ├── 04. Functions - Exercise │ ├── 01. Smallest of Three Numbers.py │ ├── 02. Add and Subtract.py │ ├── 03. Characters in Range.py │ ├── 04. Odd and Even Sum.py │ ├── 05. Even Numbers.py │ ├── 06. Sort.py │ ├── 07. Min Max and Sum.py │ ├── 08. Palindrome Integers.py │ ├── 09. Password Validator.py │ ├── 10. Perfect Number.py │ ├── 11. Loading Bar.py │ └── 12. Factorial Division.py ├── 04. Functions - Lab │ ├── 01. Absolute Values.py │ ├── 02. Grades.py │ ├── 03. Calculations.py │ ├── 04. Repeat String.py │ ├── 05. Orders.py │ ├── 06. Calculate Rectangle Area.py │ └── 07. Rounding.py └── 04. Functions - More Exercise │ ├── 01. Data Types.py │ ├── 02. Center Point.py │ ├── 03. Longer Line.py │ ├── 04. Tribonacci Sequence.py │ └── 05. Multiplication Sign.py ├── 05. Lists Advanced ├── 05. Lists Advanced - Exercise │ ├── 01. Which Are In.py │ ├── 02. Next Version.py │ ├── 03. Word Filter.py │ ├── 04. Number Classification.py │ ├── 05. Office Chairs.py │ ├── 06. Electron Distribution.py │ ├── 07. Group of 10's.py │ ├── 08. Decipher This!.py │ ├── 09. Anonymous Threat.py │ ├── 10. Pokemon Don't Go.py │ └── 11. SoftUni Course Planning.py ├── 05. Lists Advanced - Lab │ ├── 01. No Vowels.py │ ├── 02. Trains.py │ ├── 03. To-do List.py │ ├── 04. Palindrome Strings.py │ ├── 05. Sorting Names.py │ ├── 06. Even Numbers.py │ └── 07. The Office.py └── 05. Lists Advanced - More Exercise │ ├── 01. Social Distribution.py │ ├── 02. TakeSkip Rope.py │ ├── 03. Kate's Way Out.py │ ├── 04. Battle Ships.py │ └── 05. Dots.py ├── 06. Objects and Classes ├── 06. Objects and Classes - Exercise │ ├── 01. Storage.py │ ├── 02. Weapon.py │ ├── 03. Catalogue.py │ ├── 04. Town.py │ ├── 05. Class.py │ ├── 06. Inventory.py │ ├── 07. Articles.py │ ├── 08. Vehicle.py │ └── 09. Movie.py └── 06. Objects and Classes - Lab │ ├── 01. Comment.py │ ├── 02. Party.py │ ├── 03. Email.py │ ├── 04. Zoo.py │ └── 05. Circle.py ├── 07. Dictionaries ├── 07. Dictionaries - Exercise │ ├── 01. Count Chars in a String.py │ ├── 02. A Miner Task.py │ ├── 03. Capitals.py │ ├── 04. Phonebook.py │ ├── 05. Legendary Farming.py │ ├── 06. Orders.py │ ├── 07. SoftUni Parking.py │ ├── 08. Courses.py │ ├── 09. Student Academy.py │ ├── 10. Company Users.py │ ├── 11. Force Book.py │ └── 12. SoftUni Exam Results.py ├── 07. Dictionaries - Lab │ ├── 01. Bakery.py │ ├── 02. Stock.py │ ├── 03 Statistics.py │ ├── 04. Students.py │ ├── 05. ASCII Values.py │ ├── 06. Odd Occurrences.py │ └── 07. Word Synonyms.py └── 07. Dictionaries - More Exercise │ ├── 01. Ranking.py │ ├── 02. Judge.py │ ├── 03. MOBA Challenger.py │ ├── 04. Snow White.py │ └── 05. Dragon Army.py ├── 08. Text Processing ├── 08. Text Processing - Exercise │ ├── 01. Valid Usernames.py │ ├── 02. Character Multiplier.py │ ├── 03. Extract File.py │ ├── 04. Caesar Cipher.py │ ├── 05. Emoticon Finder.py │ ├── 06. Replace Repeating Chars.py │ ├── 07. String Explosion.py │ ├── 08. Letters Change Numbers.py │ ├── 09. Rage Quit.py │ └── 10. Winning Ticket.py ├── 08. Text Processing - Lab │ ├── 01. Reverse Strings.py │ ├── 02. Repeat Strings.py │ ├── 03. Substring.py │ ├── 04. Text Filter.py │ └── 05. Digits, Letters and Other.py └── 08. Text Processing - More Exercise │ ├── 01. Extract Person Information.py │ ├── 02. ASCII Sumator.py │ ├── 03. Treasure Finder.py │ ├── 04. Morse Code Translator.py │ └── 05. HTML.py ├── 09. Regular Expressions ├── 09. Regular Expressions - Exercise │ ├── 01. Capture the Numbers.py │ ├── 02. Find Variable Names in Sentences.py │ ├── 03. Find Occurrences of Word in Sentence.py │ ├── 04. Extract Emails.py │ ├── 05. Furniture.py │ ├── 06. Extract the Links.py │ ├── 10_stateless.py │ ├── 11_pyramidic.py │ ├── 7_serialize_string.py │ ├── 8_deserialize_string.py │ └── 9_string_commander.py ├── 09. Regular Expressions - Lab │ ├── 01. Match Full Name.py │ ├── 02. Match Phone Number.py │ ├── 03. Match Dates.py │ └── 04. Match Numbers.py └── 09. Regular Expressions - More Exercise │ ├── 01. Race.py │ ├── 02. SoftUni Bar Income.py │ ├── 03. Star Enigma.py │ ├── 04. Nether Realms.py │ └── 05. HTML Parser.py ├── 10. Final Exam ├── 01..py ├── 02..py └── 03..py └── README.md /00. Mid Exam/01. Task.py: -------------------------------------------------------------------------------- 1 | def calculate_provision(days, players, energy, water_per_person, food_per_person, energy_loss): 2 | total_water = days * players * water_per_person 3 | total_food = days * players * food_per_person 4 | 5 | for day in range(1, days + 1): 6 | energy -= energy_loss[day - 1] 7 | 8 | if energy <= 0: 9 | return f"You will run out of energy. You will be left with {total_food:.2f} food and {total_water:.2f} water." 10 | 11 | if day % 2==0: 12 | water_to_drink = 0.3 * total_water 13 | energy += 0.05 * energy 14 | total_water -= water_to_drink 15 | 16 | if day % 3 == 0: 17 | food_to_eat = total_food / players 18 | energy *= 1.1 19 | total_food -= food_to_eat 20 | 21 | return f"You are ready for the quest. You will be left with - {energy:.2f} energy!" 22 | 23 | 24 | days = int(input()) 25 | players = int(input()) 26 | energy = float(input()) 27 | water_per_person = float(input()) 28 | food_per_person = float(input()) 29 | 30 | energy_loss = [] 31 | for _ in range(days): 32 | energy_loss.append(float(input())) 33 | 34 | result = calculate_provision(days, players, energy, water_per_person, food_per_person, energy_loss) 35 | print(result) -------------------------------------------------------------------------------- /00. Mid Exam/02. Task.py: -------------------------------------------------------------------------------- 1 | def process_fr_list(friends_list, commands): 2 | blacklisted_names = 0 3 | lost_names = 0 4 | 5 | for command in commands: 6 | if command.startswith("Blacklist"): 7 | _, name = command.split(" ") 8 | if name in friends_list: 9 | friends_list = [n if n != name else "Blacklisted" for n in friends_list] 10 | blacklisted_names += 1 11 | print(f"{name} was blacklisted.") 12 | else: 13 | print(f"{name} was not found.") 14 | 15 | elif command.startswith("Error"): 16 | _, index = command.split(" ") 17 | index = int(index) 18 | if 0 <= index < len(friends_list) and friends_list[index] != "Blacklisted" and friends_list[index] != "Lost": 19 | name = friends_list[index] 20 | friends_list[index] = "Lost" 21 | lost_names += 1 22 | print(f"{name} was lost due to an error.") 23 | 24 | elif command.startswith("Change"): 25 | _, index, new_name = command.split(" ") 26 | index = int(index) 27 | if 0 <= index < len(friends_list): 28 | current_name = friends_list[index] 29 | friends_list[index] = new_name 30 | print(f"{current_name} changed his username to {new_name}.") 31 | 32 | return blacklisted_names, lost_names, friends_list 33 | 34 | 35 | friends = input().split(", ") 36 | commands = [] 37 | while True: 38 | command = input() 39 | if command == "Report": 40 | break 41 | commands.append(command) 42 | 43 | blacklisted, lost, updated_friends = process_fr_list(friends, commands) 44 | print(f"Blacklisted names: {blacklisted}") 45 | print(f"Lost names: {lost}") 46 | print(" ".join(updated_friends)) -------------------------------------------------------------------------------- /00. Mid Exam/03. Task.py: -------------------------------------------------------------------------------- 1 | def calc_damage(numbers, target_index, size): 2 | left_sum = sum(num for num in numbers[:target_index] if is_valid(num, numbers[target_index], size)) 3 | right_sum = sum(num for num in numbers[target_index + 1:] if is_valid(num, numbers[target_index], size)) 4 | 5 | if left_sum>=right_sum: 6 | return f"Left - {left_sum}" 7 | else: 8 | return f"Right - {right_sum}" 9 | 10 | 11 | def is_valid(number, target_number, size): 12 | if size == "cheap": 13 | if target_number > number: 14 | return True 15 | else: 16 | if target_number <= number: 17 | return True 18 | return False 19 | 20 | 21 | numbers = list(map(int, input().split(','))) 22 | target_index = int(input()) 23 | size = input() 24 | 25 | result = calc_damage(numbers, target_index, size) 26 | print(result) 27 | 28 | 29 | # def calc_damage(items, e_point, i_type): 30 | # left_damage = sum(items[:e_point]) 31 | # right_damage = sum(items[e_point + 1:]) 32 | # 33 | # if i_type == "cheap": 34 | # if left_damage <= right_damage: 35 | # return f"Left - {left_damage}" 36 | # else: 37 | # return f"Right - {right_damage}" 38 | # elif i_type == "expensive": 39 | # if left_damage >= right_damage: 40 | # return f"Left - {left_damage}" 41 | # else: 42 | # return f"Right - {right_damage}" 43 | # 44 | # 45 | # price_ratings = [int(x) for x in input().split(", ")] 46 | # entry_point = int(input()) 47 | # item_type = input() 48 | # 49 | # result = calc_damage(price_ratings, entry_point, item_type) 50 | # print(result) 51 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/01. Jenny's Secret Message.py: -------------------------------------------------------------------------------- 1 | name = input() 2 | 3 | if name == "Johnny": 4 | print("Hello, my love!") 5 | else: 6 | print(f"Hello, {name}!") 7 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/02. Drink something.py: -------------------------------------------------------------------------------- 1 | age = int(input()) 2 | 3 | if age <= 14: 4 | print('drink toddy') 5 | elif age <= 18: 6 | print('drink coke') 7 | elif age <= 21: 8 | print('drink beer') 9 | else: 10 | print("drink whisky") 11 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/03. Chat Codes.py: -------------------------------------------------------------------------------- 1 | lines = int(input()) 2 | 3 | for codes in range(lines): 4 | code = int(input()) 5 | if code == 88: 6 | print("Hello") 7 | if code == 86: 8 | print("How are you?") 9 | if code < 88 and code != 86: 10 | print("GREAT!") 11 | if code > 88: 12 | print("Bye.") 13 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/04. Maximum Multiple.py: -------------------------------------------------------------------------------- 1 | divisor = int(input()) 2 | boundary = int(input()) 3 | current_number = boundary 4 | 5 | for curr_num in range(boundary, divisor, - 1): 6 | if 0 < current_number <= boundary and current_number % divisor == 0: 7 | print(current_number) 8 | break 9 | current_number -= 1 10 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/05. Orders.py: -------------------------------------------------------------------------------- 1 | total_price = 0 2 | number_of_orders = int(input()) 3 | 4 | for orders in range(number_of_orders): 5 | price_per_capsule = float(input()) 6 | days = int(input()) 7 | capsule_per_day = int(input()) 8 | price = capsule_per_day * days * price_per_capsule 9 | if 0.01 <= price_per_capsule <= 100.00 and 1 <= days <= 31 and 1 <= capsule_per_day <= 2000: 10 | total_price += price 11 | print(f"The price for the coffee is: ${price:.2f}") 12 | print(f"Total: ${total_price:.2f}") 13 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/06. String Pureness.py: -------------------------------------------------------------------------------- 1 | lines = int(input()) 2 | 3 | for strings in range(lines): 4 | string = str(input()) 5 | if ',' in string or '.' in string or '_' in string: 6 | print(f"{string} is not pure!") 7 | else: 8 | print(f"{string} is pure.") 9 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/07. Double Char.py: -------------------------------------------------------------------------------- 1 | word = input() 2 | while word != "End": 3 | if word != "SoftUni": 4 | for char in word: 5 | print(char * 2, end='') 6 | print() 7 | word = input() 8 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/08. How Much Coffee Do You Need.py: -------------------------------------------------------------------------------- 1 | coffee = 0 2 | lower_case = ["dog", "cat", "movie", "coding"] 3 | upper_case = str(lower_case).upper() 4 | command = str(input()) 5 | while command != "END": 6 | if command in lower_case: 7 | coffee += 1 8 | elif command in upper_case: 9 | coffee += 2 10 | 11 | command = str(input()) 12 | 13 | if coffee > 5: 14 | print("You need extra sleep") 15 | else: 16 | print(coffee) 17 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/09. Sorting Hat.py: -------------------------------------------------------------------------------- 1 | name = input() 2 | voldemort = False 3 | 4 | while name != "Welcome!": 5 | if name == "Voldemort": 6 | voldemort = True 7 | print("You must not speak of that name!") 8 | break 9 | elif len(name) < 5: 10 | print(f"{name} goes to Gryffindor.") 11 | elif len(name) == 5: 12 | print(f"{name} goes to Slytherin.") 13 | elif len(name) == 6: 14 | print(f"{name} goes to Ravenclaw.") 15 | else: 16 | print(f"{name} goes to Hufflepuff.") 17 | 18 | name = input() 19 | 20 | if not voldemort: 21 | print("Welcome to Hogwarts.") 22 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/10. Mutate Strings.py: -------------------------------------------------------------------------------- 1 | string_1 = input() 2 | string_2 = input() 3 | 4 | current_string = '' 5 | previous_string = string_1 6 | 7 | for iteration in range(len(string_1)): 8 | for index_str_2 in range(0, iteration+1): 9 | current_string += string_2[index_str_2] 10 | for index_str_1 in range(iteration+1, len(string_1)): 11 | current_string += string_1[index_str_1] 12 | if not previous_string == current_string: 13 | print(current_string) 14 | previous_string = current_string 15 | current_string = '' -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/11. Easter Bread.py: -------------------------------------------------------------------------------- 1 | budget = float(input()) 2 | flour_price = float(input()) 3 | 4 | easter_bread = 0 5 | colored_eggs = 0 6 | eggs_price = flour_price * 0.75 7 | milk_price = (flour_price * 1.25) / 4 8 | easter_bread_price = flour_price + eggs_price + milk_price 9 | 10 | while budget > easter_bread_price: 11 | easter_bread += 1 12 | budget -= easter_bread_price 13 | colored_eggs += 3 14 | if easter_bread % 3 == 0: 15 | colored_eggs -= easter_bread - 2 16 | 17 | print(f'You made {easter_bread} loaves of Easter bread! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.') 18 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Exercise/12. Christmas Spirit.py: -------------------------------------------------------------------------------- 1 | quantity = int(input()) 2 | days = int(input()) 3 | 4 | money = 0 5 | spirit = 0 6 | 7 | for day in range(1, days+1): 8 | if day % 11 == 0: 9 | quantity += 2 10 | if day % 2 == 0: 11 | money += quantity * 2 12 | spirit += 5 13 | if day % 3 == 0: 14 | money += quantity * 8 15 | spirit += 13 16 | if day % 5 == 0: 17 | money += quantity * 15 18 | spirit += 17 19 | if day % 3 == 0: 20 | spirit += 30 21 | if day % 10 == 0: 22 | money += 23 23 | spirit -= 20 24 | if day == days: 25 | spirit -= 30 26 | 27 | print(f'Total cost: {money}') 28 | print(f'Total spirit: {spirit}') -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/01. Number Definer.py: -------------------------------------------------------------------------------- 1 | number = float(input()) 2 | number_type = None 3 | number_size = "" 4 | 5 | if number == 0: 6 | number_type = "zero" 7 | elif number > 0: 8 | number_type = "positive" 9 | elif number < 0: 10 | number_type = "negative" 11 | 12 | if 0 < abs(number) < 1: 13 | number_size = "small " 14 | elif abs(number) > 1_000_000: 15 | number_size = "large " 16 | 17 | print(f"{number_size}{number_type}") -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/02. Largest Of Three Numbers.py: -------------------------------------------------------------------------------- 1 | first_num = int(input()) 2 | second_num = int(input()) 3 | third_num = int(input()) 4 | 5 | numbers = [first_num, second_num, third_num] 6 | 7 | print(max(numbers)) -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/03. Word Reverse.py: -------------------------------------------------------------------------------- 1 | word = input() 2 | reversed_word = "" 3 | 4 | for i in range(len(word) - 1, -1, -1): 5 | reversed_word += word[i] 6 | 7 | print(reversed_word) -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/04. Even Numbers.py: -------------------------------------------------------------------------------- 1 | count_nums = int(input()) 2 | is_all_even = True 3 | 4 | for i in range (count_nums): 5 | current_num = int(input()) 6 | if current_num % 2 != 0: 7 | is_all_even = False 8 | print(f"{current_num} is odd!") 9 | break 10 | 11 | if is_all_even: 12 | print("All numbers are even.") 13 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/05. Number Between 1 and 100.py: -------------------------------------------------------------------------------- 1 | number = float(input()) 2 | 3 | while number < 1 or number > 100: 4 | number = float(input()) 5 | 6 | else: 7 | print(f'The number {number} is between 1 and 100') -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/06. Shopping.py: -------------------------------------------------------------------------------- 1 | budget = int(input()) 2 | total_sum = 0 3 | command = input() 4 | money_is_enough = True 5 | while command != "End": 6 | product_price = int(command) 7 | total_sum += product_price 8 | if budget < total_sum: 9 | print("You went in overdraft!") 10 | money_is_enough = False 11 | break 12 | command = input() 13 | if money_is_enough: 14 | print("You bought everything needed.") -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - Lab/07. Patterns.py: -------------------------------------------------------------------------------- 1 | num = int(input()) 2 | star = "*" 3 | 4 | for i in range(1, 2*num+1): 5 | print((num - abs(num - i)) * star) -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - More Exercise/01. Find the largest.py: -------------------------------------------------------------------------------- 1 | number = list(input()) 2 | number.sort(reverse=True) 3 | print(''.join(number)) 4 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - More Exercise/02. Find the capitals.py: -------------------------------------------------------------------------------- 1 | word = input() 2 | list_capitals = [] 3 | 4 | for capitals in range(65, 90 + 1): 5 | list_capitals.append(chr(capitals)) 6 | indices = [] 7 | for index, value in enumerate(word): 8 | if value in list_capitals: 9 | indices.append(index) 10 | print(indices) 11 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - More Exercise/03. Wolf in Sheep's clothing.py: -------------------------------------------------------------------------------- 1 | animal = list(input().split(", ")) 2 | 3 | if animal[-1] == "wolf": 4 | print("Please go away and stop eating my sheep") 5 | else: 6 | if "wolf" in animal: 7 | animal.reverse() 8 | for index, value in enumerate(animal): 9 | if value == "wolf": 10 | print(f"Oi! Sheep number {index}! You are about to be eaten by a wolf!") 11 | else: 12 | pass 13 | 14 | # sheeps = list(reversed(input().split(', '))) 15 | # print('Please go away and stop eating my sheep' if sheeps[0] == 'wolf' else f'Oi! Sheep number {sheeps.index("wolf")}! You are about to be eaten by a wolf!') -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops/01. Basic Syntax, Conditional Statements and Loops - More Exercise/04. Sum of a Beach.py: -------------------------------------------------------------------------------- 1 | input_string = input() 2 | input_string_lower = input_string.lower() 3 | count_sand = 0 4 | count_water = 0 5 | count_fish = 0 6 | count_sun = 0 7 | if "sand" in input_string_lower: 8 | count_sand = input_string_lower.count('sand') 9 | if "water" in input_string_lower: 10 | count_water = input_string_lower.count('water') 11 | if "fish" in input_string_lower: 12 | count_fish = input_string_lower.count('fish') 13 | if "sun" in input_string_lower: 14 | count_sun = input_string_lower.count('sun') 15 | counter = count_sand + count_water + count_fish + count_sun 16 | print(counter) 17 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/01. Integer operations.py: -------------------------------------------------------------------------------- 1 | first_num = int(input()) 2 | second_num = int(input()) 3 | third_num = int(input()) 4 | fourth_num = int(input()) 5 | 6 | # sum_numbers = int(((first_num + second_num) / third_num)) * fourth_num 7 | sum_numbers = ((first_num + second_num) // third_num) * fourth_num 8 | 9 | print(sum_numbers) 10 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/02. Chars to String.py: -------------------------------------------------------------------------------- 1 | # string = '' 2 | # 3 | # for char in range(3): 4 | # character = input() 5 | # string += character 6 | # 7 | # print(string) 8 | 9 | 10 | letter_one = input() 11 | letter_two = input() 12 | letter_three = input() 13 | 14 | print(f"{letter_one}{letter_two}{letter_three}") 15 | 16 | # print(letter_one, letter_two, letter_three, sep="->") 17 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/03. Elevator.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | 3 | people = int(input()) 4 | capacity = int(input()) 5 | 6 | courses = ceil(people / capacity) 7 | print(courses) 8 | 9 | 10 | # people = int(input()) 11 | # capacity = int(input()) 12 | # 13 | # if people % capacity == 0: 14 | # print(int(people / capacity)) 15 | # 16 | # else: 17 | # print(int(people / capacity) + 1) 18 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/04. Sum of Chars.py: -------------------------------------------------------------------------------- 1 | lines = int(input()) 2 | sum_chars = 0 3 | 4 | for characters in range(lines): 5 | char = ord(input()) 6 | sum_chars += char 7 | 8 | print(f"The sum equals: {sum_chars}") 9 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/05. Print Part of the ASCII Table.py: -------------------------------------------------------------------------------- 1 | first_char = int(input()) 2 | last_char = int(input()) 3 | 4 | for char in range(first_char, last_char + 1): 5 | print(chr(char), end=' ') 6 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/06. Triples of Latin Letters.py: -------------------------------------------------------------------------------- 1 | number_of_letters = int(input()) 2 | 3 | for first_char in range(number_of_letters): 4 | for second_char in range(number_of_letters): 5 | for third_char in range(number_of_letters): 6 | print(f"{chr(97 + first_char)}{chr(97 + second_char)}{chr(97 + third_char)}") 7 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/07. Water Overflow.py: -------------------------------------------------------------------------------- 1 | lines = int(input()) 2 | tub_capacity = 255 # Liters 3 | total_water = 0 # Liters 4 | 5 | for capacity in range(lines): 6 | water = float(input()) 7 | 8 | if water <= tub_capacity: 9 | tub_capacity -= water 10 | total_water += water 11 | 12 | else: 13 | print("Insufficient capacity!") 14 | 15 | print(f"{total_water:.0f}") 16 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/08. Party Profit.py: -------------------------------------------------------------------------------- 1 | party_size = int(input()) 2 | days = int(input()) 3 | 4 | coins = 0 5 | 6 | for day in range(1, days+1): 7 | if day % 10 == 0: 8 | party_size -= 2 9 | if day % 15 == 0: 10 | party_size += 5 11 | coins += 50 12 | coins -= party_size * 2 13 | if day % 3 == 0: 14 | coins -= party_size * 3 15 | if day % 5 == 0: 16 | coins += party_size * 20 17 | if day % 3 == 0: 18 | coins -= party_size * 2 19 | 20 | coins_each = coins / party_size 21 | 22 | print(f"{party_size} companions received {int(coins_each)} coins each.") 23 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/09. Snowballs.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | snowballs_qty = int(input()) 4 | 5 | max_snowball_snow = 0 6 | max_snowball_time = 0 7 | max_snowball_quality = 0 8 | max_snowball_value = -sys.maxsize 9 | 10 | for snowball in range(1, snowballs_qty+1): 11 | snowball_snow = int(input()) 12 | snowball_time = int(input()) 13 | snowball_quality = int(input()) 14 | snowball_value = (snowball_snow / snowball_time) ** snowball_quality 15 | if snowball_value > max_snowball_value: 16 | max_snowball_snow = snowball_snow 17 | max_snowball_time = snowball_time 18 | max_snowball_quality = snowball_quality 19 | max_snowball_value = snowball_value 20 | 21 | print(f'{max_snowball_snow} : {max_snowball_time} = {int(max_snowball_value)} ({max_snowball_quality})') 22 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Exercise/10. Gladiator Expenses.py: -------------------------------------------------------------------------------- 1 | lost_fight = int(input()) 2 | helmet_price = float(input()) 3 | sword_price = float(input()) 4 | shield_price = float(input()) 5 | armor_price = float(input()) 6 | 7 | expenses = 0 8 | broken_shield_count = 0 9 | 10 | for fight in range(1, lost_fight+1): 11 | if fight % 2 == 0: 12 | expenses += helmet_price 13 | if fight % 3 == 0: 14 | expenses += sword_price 15 | if fight % 2 == 0 and fight % 3 == 0: 16 | expenses += shield_price 17 | broken_shield_count += 1 18 | if broken_shield_count == 2: 19 | broken_shield_count = 0 20 | expenses += armor_price 21 | 22 | print(f'Gladiator expenses: {expenses:.2f} aureus') -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/01. Concat Names.py: -------------------------------------------------------------------------------- 1 | first_person = input() 2 | second_person = input() 3 | delimiter = input() 4 | 5 | print(f'{first_person}{delimiter}{second_person}') 6 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/02. Centuries to Minutes.py: -------------------------------------------------------------------------------- 1 | centuries = int(input()) 2 | years = centuries * 100 3 | days = int(years * 365.2422) 4 | hours = days * 24 5 | minutes = hours * 60 6 | 7 | print(f"{centuries} centuries = {years} years = {days} days = {hours} hours = {minutes} minutes") 8 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/03. Special Numbers.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | 3 | for num in range(1, number + 1): 4 | sum_digits = 0 5 | digits = num 6 | while digits > 0: 7 | sum_digits += digits % 10 8 | digits = int(digits / 10) 9 | if sum_digits == 5 or sum_digits == 7 or sum_digits == 11: 10 | print(f'{num} -> True') 11 | else: 12 | print(f"{num} -> False") -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/04. Convert Meters to Kilometers.py: -------------------------------------------------------------------------------- 1 | meters = int(input()) 2 | kilometers = meters / 1000 3 | 4 | print(f'{kilometers:.2f}') 5 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/05. Pounds to Dollars.py: -------------------------------------------------------------------------------- 1 | british_pounds = int(input()) 2 | dollars = british_pounds * 1.31 3 | 4 | print(f'{dollars:.3f}') 5 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - Lab/06. Next Happy Year.py: -------------------------------------------------------------------------------- 1 | year = int(input()) 2 | happy_year = False 3 | 4 | while not happy_year: 5 | year += 1 6 | set_year = set() 7 | 8 | for years in range(len(str(year))): 9 | set_year.add(str(year)[years]) 10 | 11 | happy_year = len(set_year) == len(str(year)) 12 | 13 | print(year) 14 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - More Exercise/01. Exchange Integers.py: -------------------------------------------------------------------------------- 1 | a = input() 2 | b = input() 3 | print(f''' 4 | Before: 5 | a = {a} 6 | b = {b} 7 | After: 8 | a = {b} 9 | b = {a} 10 | ''') 11 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - More Exercise/02. Prime Number Checker.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | divider = 0 3 | for num in range(number): 4 | divider += 1 5 | if 1 < divider < number and number % divider == 0: 6 | print('False') 7 | break 8 | else: 9 | print('True') 10 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - More Exercise/03. Decrypting Messages.py: -------------------------------------------------------------------------------- 1 | key = int(input()) 2 | lines = int(input()) 3 | string = '' 4 | 5 | for word in range(lines): 6 | letter = ord(str(input())) + key 7 | string += chr(letter) 8 | 9 | print(string) 10 | -------------------------------------------------------------------------------- /02. Data Types and Variables/02. Data Types and Variables - More Exercise/04. Balanced Brackets.py: -------------------------------------------------------------------------------- 1 | lines = int(input()) 2 | balanced = 0 3 | last_bracket = '' 4 | for brackets in range(lines): 5 | string = input() 6 | if string == "(": 7 | balanced += 1 8 | last_bracket = "(" 9 | if balanced > 1: 10 | print("UNBALANCED") 11 | exit() 12 | elif string == ")": 13 | balanced -= 1 14 | last_bracket = ")" 15 | if balanced == 0 and last_bracket != "(": 16 | print("BALANCED") 17 | else: 18 | print("UNBALANCED") 19 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/01. Invert Values.py: -------------------------------------------------------------------------------- 1 | input_string = input() 2 | first_list = input_string.split(" ") 3 | second_list = [] 4 | for i in range(len(first_list)): 5 | new_value = int(first_list[i]) * -1 6 | second_list.append(new_value) 7 | print(second_list) 8 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/02. Multiples List.py: -------------------------------------------------------------------------------- 1 | factor = int(input()) 2 | count = int(input()) 3 | output_list = [factor] 4 | current_number = factor 5 | for i in range(count - 1): 6 | current_number += factor 7 | output_list.append(current_number) 8 | print(output_list) 9 | 10 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/03. Football Cards.py: -------------------------------------------------------------------------------- 1 | team_a_count = 11 2 | team_b_count = 11 3 | cards_list = input().split(" ") 4 | cards_list = list(dict.fromkeys(cards_list)) 5 | game_was_terminated = False 6 | for i in range(len(cards_list)): 7 | current_player = cards_list[i] 8 | if current_player[0] == "A": 9 | team_a_count -= 1 10 | elif current_player[0] == "B": 11 | team_b_count -= 1 12 | if team_a_count < 7 or team_b_count < 7: 13 | game_was_terminated = True 14 | break 15 | print(f"Team A - {team_a_count}; Team B - {team_b_count}") 16 | if game_was_terminated: 17 | print("Game was terminated") 18 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/04. Number Beggars.py: -------------------------------------------------------------------------------- 1 | integers_string = input() 2 | beggars_count = int(input()) 3 | all_sums = integers_string.split(", ") 4 | beggars_list = [] 5 | for beggar in range(beggars_count): 6 | current_sum = 0 7 | for i in range(len(all_sums)): 8 | if i == beggar: 9 | current_sum += int(all_sums[i]) 10 | beggar += beggars_count 11 | beggars_list.append(current_sum) 12 | print(beggars_list) 13 | 14 | 15 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/05. Faro Shuffle.py: -------------------------------------------------------------------------------- 1 | input_string = input() 2 | shuffles_count = int(input()) 3 | original_list = input_string.split(" ") 4 | middle = int(len(original_list) / 2) 5 | shuffled_string = original_list 6 | for shuffle in range(shuffles_count): 7 | first_list = shuffled_string[0:middle] 8 | second_list = shuffled_string[middle:] 9 | shuffled_string = [] 10 | for i in range(len(first_list)): 11 | shuffled_string.append(first_list[i]) 12 | shuffled_string.append(second_list[i]) 13 | print(shuffled_string) 14 | 15 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/06. Survival of the Biggest.py: -------------------------------------------------------------------------------- 1 | input_integers = input() 2 | count_to_remove = int(input()) 3 | strings_list = input_integers.split(" ") 4 | integers_list = ([int(x) for x in strings_list]) 5 | for i in range(count_to_remove): 6 | integers_list.remove(min(integers_list)) 7 | for j in range(len(integers_list)): 8 | if j == 0: 9 | print(integers_list[j], end="") 10 | else: 11 | print(f", {integers_list[j]}", end="") 12 | 13 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/07. Easter Gifts.py: -------------------------------------------------------------------------------- 1 | gifts_string = input() 2 | gifts_list = gifts_string.split(" ") 3 | command = input() 4 | while command != "No Money": 5 | command_list = command.split(" ") 6 | command = command_list[0] 7 | gift = command_list[1] 8 | index = command_list[-1] 9 | if (gift != index) and (0 <= int(index) < len(gifts_list)): 10 | index_is_valid = True 11 | else: 12 | index_is_valid = False 13 | if command == "OutOfStock": 14 | for i in range(len(gifts_list)): 15 | if gifts_list[i] == gift: 16 | gifts_list[i] = "None" 17 | elif command == "Required": 18 | if index_is_valid: 19 | gifts_list[int(index)] = gift 20 | elif command == "JustInCase": 21 | gifts_list[-1] = gift 22 | command = input() 23 | for g in range(len(gifts_list)): 24 | if gifts_list[g] != "None": 25 | print(gifts_list[g], end=" ") 26 | 27 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/08. Seize the Fire.py: -------------------------------------------------------------------------------- 1 | fires_with_cells = input() 2 | water = int(input()) 3 | effort = 0 4 | total_fire = 0 5 | put_out_cells = [] 6 | cells_list = fires_with_cells.split("#") 7 | for i in range(len(cells_list)): 8 | if water <= 0: 9 | break 10 | current_cell = cells_list[i] 11 | current_cell_list = current_cell.split(" ") 12 | current_fire_type = current_cell_list[0] 13 | current_water_needed = int(current_cell_list[-1]) 14 | if (current_fire_type == "High") and (81 <= current_water_needed <= 125): 15 | cell_is_valid = True 16 | elif (current_fire_type == "Medium") and (51 <= current_water_needed <= 80): 17 | cell_is_valid = True 18 | elif (current_fire_type == "Low") and (1 <= current_water_needed <= 50): 19 | cell_is_valid = True 20 | else: 21 | cell_is_valid = False 22 | if cell_is_valid: 23 | if water >= current_water_needed: 24 | water -= current_water_needed 25 | effort += current_water_needed * 0.25 26 | total_fire += current_water_needed 27 | put_out_cells.append(current_water_needed) 28 | print("Cells:") 29 | for j in range(len(put_out_cells)): 30 | cell_value = put_out_cells[j] 31 | print(f"- {cell_value}") 32 | print(f"Effort: {effort:.2f}") 33 | print(f"Total Fire: {total_fire}") 34 | 35 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/09. Hello, France.py: -------------------------------------------------------------------------------- 1 | items_collection = input() 2 | budget = int(input()) 3 | ticket_price = 150 4 | items_collection_list = items_collection.split("|") 5 | new_prices_list = [] 6 | profit = 0 7 | sold_items_value = 0 8 | budget_is_enough = False 9 | for i in range(len(items_collection_list)): 10 | current_items = items_collection_list[i] 11 | current_items_list = current_items.split("->") 12 | current_item_type = current_items_list[0] 13 | current_item_price = float(current_items_list[-1]) 14 | if current_item_type == "Clothes" and current_item_price <= 50: 15 | item_price_is_in_range = True 16 | elif current_item_type == "Shoes" and current_item_price <= 35: 17 | item_price_is_in_range = True 18 | elif current_item_type == "Accessories" and current_item_price <= 20.50: 19 | item_price_is_in_range = True 20 | else: 21 | item_price_is_in_range = False 22 | if item_price_is_in_range and budget >= current_item_price: 23 | budget -= current_item_price 24 | current_item_new_price = current_item_price * 1.4 25 | profit += current_item_new_price - current_item_price 26 | sold_items_value += current_item_new_price 27 | new_prices_list.append(current_item_new_price) 28 | for j in range(len(new_prices_list)): 29 | new_price = new_prices_list[j] 30 | print(f"{new_price:.2f}", end=" ") 31 | print() 32 | 33 | print(f"Profit: {profit:.2f}") 34 | if (sold_items_value + budget) >= ticket_price: 35 | print("Hello, France!") 36 | else: 37 | print("Not enough money.") 38 | 39 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Exercise/10. Bread Factory.py: -------------------------------------------------------------------------------- 1 | day_events = input() 2 | energy = 100 3 | coins = 100 4 | day_events_list = day_events.split("|") 5 | day_is_completed = True 6 | for i in range(len(day_events_list)): 7 | current_event_string = day_events_list[i] 8 | current_event_list = current_event_string.split("-") 9 | current_event = current_event_list[0] 10 | current_value = int(current_event_list[1]) 11 | if current_event == "rest": 12 | gained_energy = 0 13 | if energy >= 100: 14 | gained_energy = 0 15 | else: 16 | energy += current_value 17 | if energy > 100: 18 | gained_energy = current_value + (100 - energy) 19 | energy = 100 20 | else: 21 | gained_energy = current_value 22 | print(f"You gained {gained_energy} energy.") 23 | print(f"Current energy: {energy}.") 24 | elif current_event == "order": 25 | if (energy - 30) >= 0: 26 | energy -= 30 27 | coins += current_value 28 | print(f"You earned {current_value} coins.") 29 | else: 30 | energy += 50 31 | print("You had to rest!") 32 | else: 33 | if (coins - current_value) >= 0: 34 | coins -= current_value 35 | print(f"You bought {current_event}.") 36 | else: 37 | print(f"Closed! Cannot afford {current_event}.") 38 | day_is_completed = False 39 | break 40 | if day_is_completed: 41 | print("Day completed!") 42 | print(f"Coins: {coins}") 43 | print(f"Energy: {energy}") 44 | 45 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Lab/01. Strange Zoo.py: -------------------------------------------------------------------------------- 1 | tail = input() 2 | body = input() 3 | head = input() 4 | new_list = [head, body, tail] 5 | print(new_list) 6 | 7 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Lab/02. Courses.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | list_of_courses = [] 3 | for items in range(number): 4 | current_course = input() 5 | list_of_courses.append(current_course) 6 | print(list_of_courses) 7 | 8 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Lab/03. List Statistics.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | positives_list = [] 3 | negatives_list = [] 4 | for item in range(number): 5 | current_number = int(input()) 6 | if current_number >= 0: 7 | positives_list.append(current_number) 8 | else: 9 | negatives_list.append(current_number) 10 | print(positives_list) 11 | print(negatives_list) 12 | print(f"Count of positives: {len(positives_list)}") 13 | print(f"Sum of negatives: {sum(negatives_list)}") 14 | 15 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Lab/04. Search.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | word = input() 3 | full_list = [] 4 | filtered_list = [] 5 | for _ in range(number): 6 | input_string = input() 7 | full_list.append(input_string) 8 | if word in input_string: 9 | filtered_list.append(input_string) 10 | print(full_list) 11 | print(filtered_list) 12 | 13 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - Lab/05. Numbers Filter.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | numbers_list = [] 3 | filtered_list = [] 4 | for _ in range(number): 5 | current_number = int(input()) 6 | numbers_list.append(current_number) 7 | command = input() 8 | if command == "even": 9 | for n in numbers_list: 10 | if n % 2 == 0: 11 | filtered_list.append(n) 12 | elif command == "odd": 13 | for n in numbers_list: 14 | if n % 2 != 0: 15 | filtered_list.append(n) 16 | elif command == "negative": 17 | for n in numbers_list: 18 | if n < 0: 19 | filtered_list.append(n) 20 | elif command == "positive": 21 | for n in numbers_list: 22 | if n >= 0: 23 | filtered_list.append(n) 24 | print(filtered_list) 25 | 26 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/01. Zeros to Back.py: -------------------------------------------------------------------------------- 1 | numbers_list = input().split(", ") 2 | zeros_counter = 0 3 | final_list = [] 4 | for item in numbers_list: 5 | if item == "0": 6 | zeros_counter += 1 7 | else: 8 | final_list.append(int(item)) 9 | for zeros in range(zeros_counter): 10 | final_list.append(int(0)) 11 | print(final_list) 12 | 13 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/02. Messaging.py: -------------------------------------------------------------------------------- 1 | numbers_sequence = input() 2 | input_string = input() 3 | numbers_list = numbers_sequence.split(" ") 4 | indices_list = [] 5 | final_message = "" 6 | for index in range(len(numbers_list)): 7 | current_combination = numbers_list[index] 8 | current_sum = 0 9 | for sequence in range(len(current_combination)): 10 | current_sum += int(current_combination[sequence]) 11 | indices_list.append(current_sum) 12 | message_indices_count = len(input_string) 13 | for symbol in range(len(numbers_list)): 14 | current_index = indices_list[symbol] 15 | while current_index > (message_indices_count - 1): 16 | current_index -= message_indices_count 17 | current_symbol = input_string[current_index] 18 | input_string = input_string[:current_index] + \ 19 | input_string[current_index + 1::] 20 | final_message += current_symbol 21 | print(final_message) 22 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/03. Car Race.py: -------------------------------------------------------------------------------- 1 | numbers_sequence = input() 2 | sequence_list = numbers_sequence.split(" ") 3 | sequence_list = [int(i) for i in sequence_list] 4 | middle_index = int(len(sequence_list) / 2) 5 | left_car_time = float() 6 | right_car_time = float() 7 | for left_index in range(middle_index): 8 | current_left_time = sequence_list[left_index] 9 | if current_left_time == 0: 10 | left_car_time *= 0.80 11 | else: 12 | left_car_time += current_left_time 13 | sequence_list.reverse() 14 | for right_index in range(middle_index): 15 | current_right_time = sequence_list[right_index] 16 | if current_right_time == 0: 17 | right_car_time *= 0.80 18 | else: 19 | right_car_time += current_right_time 20 | if left_car_time < right_car_time: 21 | winner = "left" 22 | winner_time = left_car_time 23 | else: 24 | winner = "right" 25 | winner_time = right_car_time 26 | print(f"The winner is {winner} with total time: {winner_time:.1f}") 27 | 28 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/04. Josephus Permutation.py: -------------------------------------------------------------------------------- 1 | people_sequence = input() 2 | execution_number = int(input()) 3 | people_list = people_sequence.split(" ") 4 | people_list = [int(x) for x in people_list] 5 | executions_list = [] 6 | kill_counter = 0 7 | current_index = 0 8 | 9 | while len(people_list) > 0: 10 | kill_counter += 1 11 | 12 | if current_index >= len(people_list): 13 | current_index = 0 14 | 15 | if kill_counter % execution_number == 0: 16 | executions_list.append(people_list[current_index]) 17 | people_list.pop(current_index) 18 | # executions_list.append(people_list.pop(index)) 19 | else: 20 | current_index += 1 21 | 22 | print(str(executions_list).replace(" ", "")) 23 | 24 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/05. Tic-Tac-Toe.py: -------------------------------------------------------------------------------- 1 | first_line = input().split(" ") 2 | second_line = input().split(" ") 3 | third_line = input().split(" ") 4 | winner = 0 5 | if "1" == first_line[0] == first_line[1] == first_line[2] or \ 6 | "1" == second_line[0] == second_line[1] == second_line[2] or \ 7 | "1" == third_line[0] == third_line[1] == third_line[2] or \ 8 | "1" == first_line[0] == second_line[0] == third_line[0] or \ 9 | "1" == first_line[1] == second_line[1] == third_line[1] or \ 10 | "1" == first_line[2] == second_line[2] == third_line[2] or \ 11 | "1" == first_line[0] == second_line[1] == third_line[2] or \ 12 | "1" == first_line[2] == second_line[1] == third_line[0]: 13 | winner = "1" 14 | elif "2" == first_line[0] == first_line[1] == first_line[2] or \ 15 | "2" == second_line[0] == second_line[1] == second_line[2] or \ 16 | "2" == third_line[0] == third_line[1] == third_line[2] or \ 17 | "2" == first_line[0] == second_line[0] == third_line[0] or \ 18 | "2" == first_line[1] == second_line[1] == third_line[1] or \ 19 | "2" == first_line[2] == second_line[2] == third_line[2] or \ 20 | "2" == first_line[0] == second_line[1] == third_line[2] or \ 21 | "2" == first_line[2] == second_line[1] == third_line[0]: 22 | winner = "2" 23 | if winner == "1": 24 | print("First player won") 25 | elif winner == "2": 26 | print("Second player won") 27 | else: 28 | print("Draw!") 29 | 30 | -------------------------------------------------------------------------------- /03. Lists Basics/03. Lists Basics - More Exercise/06. List Manipulator.py: -------------------------------------------------------------------------------- 1 | input_numbers = input().split() 2 | numbers_list = [] 3 | for element in input_numbers: 4 | numbers_list.append(int(element)) 5 | command = input().split() 6 | 7 | while command[0] != "end": 8 | if command[0] == "exchange": 9 | if 0 <= int(command[1]) < len(numbers_list): 10 | numbers_list = numbers_list[int(command[1]) + 1:] + numbers_list[:int(command[1]) + 1] 11 | else: 12 | print(f"Invalid index") 13 | else: 14 | even_numbers = [] 15 | odd_numbers = [] 16 | index_list_even = [] 17 | index_list_odd = [] 18 | 19 | for number in numbers_list: 20 | if number % 2 == 0: 21 | even_numbers.append(int(number)) 22 | else: 23 | odd_numbers.append(int(number)) 24 | 25 | if command[0] == "max": 26 | if command[1] == "even" and even_numbers: 27 | for index, value in enumerate(numbers_list): 28 | if int(value) == max(even_numbers): 29 | index_list_even.append(index) 30 | if len(index_list_even) == 1: 31 | print(index_list_even[0]) 32 | else: 33 | print(index_list_even[-1]) 34 | elif command[1] == "odd" and odd_numbers: 35 | for index, value in enumerate(numbers_list): 36 | if int(value) == max(odd_numbers): 37 | index_list_odd.append(index) 38 | if len(index_list_odd) == 1: 39 | print(index_list_odd[0]) 40 | else: 41 | print(index_list_odd[-1]) 42 | else: 43 | print("No matches") 44 | 45 | elif command[0] == "min": 46 | if command[1] == "even" and even_numbers: 47 | for index, value in enumerate(numbers_list): 48 | if int(value) == min(even_numbers): 49 | index_list_even.append(index) 50 | if len(index_list_even) == 1: 51 | print(index_list_even[0]) 52 | else: 53 | print(index_list_even[-1]) 54 | elif command[1] == "odd" and odd_numbers: 55 | for index, value in enumerate(numbers_list): 56 | if int(value) == min(odd_numbers): 57 | index_list_odd.append(index) 58 | if len(index_list_odd) == 1: 59 | print(index_list_odd[0]) 60 | else: 61 | print(index_list_odd[-1]) 62 | else: 63 | print("No matches") 64 | 65 | elif command[0] == "first": 66 | if 0 < int(command[1]) <= len(numbers_list): 67 | if command[2] == "even": 68 | print(even_numbers[:int(command[1])]) 69 | elif command[2] == "odd": 70 | print(odd_numbers[:int(command[1])]) 71 | else: 72 | print("Invalid count") 73 | 74 | elif command[0] == "last": 75 | if 0 < int(command[1]) <= len(numbers_list): 76 | if command[2] == "even": 77 | if len(even_numbers) < int(command[1]): 78 | print(even_numbers) 79 | else: 80 | print(even_numbers[-int(command[1]):]) 81 | elif command[2] == "odd": 82 | if len(odd_numbers) < int(command[1]): 83 | print(odd_numbers) 84 | else: 85 | print(odd_numbers[-int(command[1]):]) 86 | else: 87 | print("Invalid count") 88 | 89 | command = input().split() 90 | 91 | print(numbers_list) 92 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/01. Smallest of Three Numbers.py: -------------------------------------------------------------------------------- 1 | numbers = list() 2 | 3 | for _ in range(3): 4 | num = int(input()) 5 | numbers.append(num) 6 | 7 | 8 | def find_smallest_number(list_of_numbers): 9 | result = min(list_of_numbers) 10 | return result 11 | 12 | 13 | print(find_smallest_number(numbers)) 14 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/02. Add and Subtract.py: -------------------------------------------------------------------------------- 1 | number_one = int(input()) 2 | number_two = int(input()) 3 | number_three = int(input()) 4 | 5 | 6 | def sum_numbers(one, two): 7 | result = one + two 8 | return result 9 | 10 | 11 | def subtract(three): 12 | result = sum_numbers(number_one, number_two) - three 13 | return result 14 | 15 | 16 | print(subtract(number_three)) 17 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/03. Characters in Range.py: -------------------------------------------------------------------------------- 1 | character_one = input() 2 | character_two = input() 3 | 4 | 5 | def find_range_of_characters(one, two): 6 | one = int(ord(one) + 1) 7 | two = int(ord(two)) 8 | for n in range(one, two): 9 | print(chr(n), end=" ") 10 | 11 | 12 | find_range_of_characters(character_one, character_two) 13 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/04. Odd and Even Sum.py: -------------------------------------------------------------------------------- 1 | numbers = input() 2 | 3 | 4 | def all_sum(num): 5 | return f"Odd sum = {sum(int(n) for n in num if int(n) % 2 !=0)}," \ 6 | f" Even sum = {sum(int(n) for n in num if int(n) % 2 ==0)}" 7 | 8 | 9 | print(all_sum(numbers)) 10 | 11 | 12 | 13 | # 14 | # numbers = input() 15 | # 16 | # 17 | # def all_sum(num): 18 | # even_total = 0 19 | # 20 | # odd_total = 0 21 | # for i in num: 22 | # i = int(i) 23 | # if i % 2 == 0: 24 | # even_total += i 25 | # else: 26 | # odd_total += i 27 | # return f"Odd sum = {odd_total}, Even sum = {even_total}" 28 | # 29 | # 30 | # print(all_sum(numbers)) 31 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/05. Even Numbers.py: -------------------------------------------------------------------------------- 1 | main_list = [int(n) for n in input().split()] 2 | 3 | even_numbers = list() 4 | 5 | 6 | def filter(numbers): 7 | for n in numbers: 8 | if n % 2 == 0: 9 | even_numbers.append(n) 10 | return even_numbers 11 | 12 | 13 | print(filter(main_list)) 14 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/06. Sort.py: -------------------------------------------------------------------------------- 1 | main_list = [int(n) for n in input().split()] 2 | sort_list = list() 3 | 4 | 5 | def sorted_l(numbers): 6 | numbers.sort() 7 | for n in numbers: 8 | sort_list.append(n) 9 | return sort_list 10 | 11 | 12 | print(sorted_l(main_list)) 13 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/07. Min Max and Sum.py: -------------------------------------------------------------------------------- 1 | main_list = [int(n) for n in input().split()] 2 | 3 | print(f"The minimum number is {min(main_list)}") 4 | print(f"The maximum number is {max(main_list)}") 5 | print(f"The sum number is: {sum(main_list)}") 6 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/08. Palindrome Integers.py: -------------------------------------------------------------------------------- 1 | main_list = input().split(", ") 2 | 3 | 4 | def check_palindrome(numbers): 5 | for n in numbers: 6 | if n == n[::-1]: 7 | print("True") 8 | else: 9 | print("False") 10 | 11 | 12 | check_palindrome(main_list) 13 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/09. Password Validator.py: -------------------------------------------------------------------------------- 1 | errors = [] 2 | 3 | 4 | def password_validation(password): 5 | if not 6 <= len(password) <= 10: 6 | errors.append("Password must be between 6 and 10 characters") 7 | if not password.isalnum(): 8 | errors.append("Password must consist only of letters and digits") 9 | if sum(1 for x in password if x.isdigit()) < 2: 10 | errors.append("Password must have at least 2 digits") 11 | 12 | 13 | current_password = input() 14 | password_validation(current_password) 15 | if errors: 16 | [print(show) for show in errors] 17 | else: 18 | print("Password is valid") 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | # 28 | # errors = { 29 | # "leng": "Password must be between 6 and 10 characters", 30 | # "consist": "Password must consist only of letters and digits", 31 | # "least": "Password must have at least 2 digits" 32 | # } 33 | # 34 | # 35 | # def password_validation(password): 36 | # if not 6 <= len(password) <= 10: 37 | # print(errors.pop("leng")) 38 | # if not password.isalnum(): 39 | # print(errors.pop("consist")) 40 | # if sum(1 for x in password if x.isdigit()) < 2: 41 | # print(errors.pop("least")) 42 | # 43 | # 44 | # current_password = input() 45 | # password_validation(current_password) 46 | # if len(errors) == 3: 47 | # print("Password is valid") 48 | 49 | 50 | 51 | 52 | # 53 | # 54 | # errors = { 55 | # "leng": "Password must be between 6 and 10 characters", 56 | # "consist": "Password must consist only of letters and digits", 57 | # "least": "Password must have at least 2 digits" 58 | # } 59 | # 60 | # 61 | # def password_validation(password): 62 | # result = [] 63 | # if not 6 <= len(password) <= 10: 64 | # result.append("leng") 65 | # if not password.isalnum(): 66 | # result.append("consist") 67 | # if sum(1 for x in password if x.isdigit()) < 2: 68 | # result.append("least") 69 | # return result 70 | # 71 | # 72 | # current_password = input() 73 | # result = password_validation(current_password) 74 | # if result: 75 | # [print(errors[show]) for show in result] 76 | # else: 77 | # print("Password is valid") 78 | # 79 | # 80 | # 81 | # 82 | # 83 | # 84 | # 85 | # password_to_check = input() 86 | # 87 | # characters_in_range = False 88 | # letters_digits_only = False 89 | # two_digits = False 90 | # numbers_check = 0 91 | # 92 | # 93 | # def pass_check(check): 94 | # global characters_in_range, letters_digits_only, two_digits, numbers_check 95 | # if 6 <= len(check) <= 10: 96 | # characters_in_range = True 97 | # if check.isalnum(): 98 | # letters_digits_only = True 99 | # for letter in check: 100 | # if letter.isdigit(): 101 | # numbers_check += 1 102 | # if numbers_check == 2: 103 | # two_digits = True 104 | # break 105 | # 106 | # 107 | # pass_check(password_to_check) 108 | # 109 | # if all([characters_in_range, letters_digits_only, two_digits]): 110 | # print("Password is valid") 111 | # if not characters_in_range: 112 | # print("Password must be between 6 and 10 characters") 113 | # if not letters_digits_only: 114 | # print("Password must consist only of letters and digits") 115 | # if not two_digits: 116 | # print("Password must have at least 2 digits") 117 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/10. Perfect Number.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | 3 | 4 | def check_for_perf_number(n): 5 | check_number = 0 6 | for i in range(1, n): 7 | if n % i == 0: 8 | check_number = check_number + i 9 | if check_number == number: 10 | return "We have a perfect number!" 11 | else: 12 | return "It's not so perfect." 13 | 14 | 15 | print(check_for_perf_number(number)) 16 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/11. Loading Bar.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | 3 | 4 | def loading_bar(num): 5 | num_range = int(num / 10) 6 | target = 10 7 | if target == num_range: 8 | return "100% Complete!\n" + "[" + target * "%" + "]" 9 | else: 10 | return f"{num}% " + "[" + num_range * "%" + (target - num_range) * "." + "]\n" + "Still loading..." 11 | 12 | 13 | print(loading_bar(number)) 14 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Exercise/12. Factorial Division.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | number_one = int(input()) 4 | number_two = int(input()) 5 | 6 | 7 | def factorial_division(one, two): 8 | one = math.factorial(one) 9 | two = math.factorial(two) 10 | return f"{(one / two):.2f}" 11 | 12 | 13 | print(factorial_division(number_one, number_two)) 14 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/01. Absolute Values.py: -------------------------------------------------------------------------------- 1 | main_list = [float(n) for n in input().split()] 2 | 3 | def abs_value(list): 4 | result = [abs(ele) for ele in main_list] 5 | return print(result) 6 | 7 | abs_value(main_list) -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/02. Grades.py: -------------------------------------------------------------------------------- 1 | grades = float(input()) 2 | 3 | def check_grade(grade): 4 | if 2.00 <= grade <= 2.99: 5 | return print("Fail") 6 | elif 3.00 <= grade <= 3.49: 7 | return print("Poor") 8 | elif 3.50 <= grade <= 4.49: 9 | return print("Good") 10 | elif 4.50 <= grade <= 5.49: 11 | return print("Very Good") 12 | elif 5.50 <= grade <= 6: 13 | return print("Excellent") 14 | 15 | check_grade(grades) -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/03. Calculations.py: -------------------------------------------------------------------------------- 1 | operation = input() 2 | number_one = int(input()) 3 | number_two = int(input()) 4 | 5 | 6 | def show_result(type_operation, n_one, n_two): 7 | if type_operation == "multiply": 8 | result = n_one * n_two 9 | return result 10 | 11 | elif type_operation == "divide": 12 | result = n_one / n_two 13 | return int(result) 14 | 15 | elif type_operation == "add": 16 | result = n_one + n_two 17 | return result 18 | 19 | elif type_operation == "subtract": 20 | result = n_one - n_two 21 | return result 22 | 23 | 24 | print(show_result(operation, number_one, number_two)) 25 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/04. Repeat String.py: -------------------------------------------------------------------------------- 1 | string_to_show = input() 2 | number_to_multi_string = int(input()) 3 | 4 | 5 | def multi_strint(string_show, number): 6 | result = string_show * number 7 | return result 8 | 9 | 10 | print(multi_strint(string_to_show, number_to_multi_string)) 11 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/05. Orders.py: -------------------------------------------------------------------------------- 1 | product = input() 2 | quantity_of_the_product = int(input()) 3 | 4 | product_info = { 5 | "coffee": 1.50, 6 | "coke": 1.40, 7 | "water": 1.00, 8 | "snacks": 2.00 9 | } 10 | 11 | 12 | def calc_the_price(product_type, how_many): 13 | result = product_info[product_type] * how_many 14 | return f"{result:.2f}" 15 | 16 | 17 | print(calc_the_price(product, quantity_of_the_product)) 18 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/06. Calculate Rectangle Area.py: -------------------------------------------------------------------------------- 1 | width_rectangle = int(input()) 2 | height_rectangle = int(input()) 3 | 4 | 5 | def calc_area_rectangle(a, b): 6 | result = a * b 7 | return result 8 | 9 | 10 | print(calc_area_rectangle(width_rectangle, height_rectangle)) 11 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - Lab/07. Rounding.py: -------------------------------------------------------------------------------- 1 | main_list = [float(n) for n in input().split()] 2 | 3 | 4 | def round_numbers(numbers): 5 | result = [round(num) for num in numbers] 6 | return result 7 | 8 | 9 | print(round_numbers(main_list)) 10 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - More Exercise/01. Data Types.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | number = input() 3 | 4 | 5 | def calc(arg1, arg2): 6 | if arg1 == "int": 7 | result = float(arg2) * 2 8 | return f"{result:.0f}" 9 | 10 | elif arg1 == "real": 11 | result = float(arg2) * 1.5 12 | return f"{result:.2f}" 13 | 14 | elif arg1 == "string": 15 | return f"${arg2}$" 16 | 17 | 18 | print(calc(command, number)) 19 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - More Exercise/02. Center Point.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | points = tuple(math.floor(float(input())) for _ in range(4)) 4 | sum_x = sum([abs(num) for num in points[:2]]) 5 | sum_y = sum([abs(num) for num in points[2:]]) 6 | 7 | 8 | def whats_closer(arg1, arg2): 9 | if arg1 <= arg2: 10 | return points[:2] 11 | return points[2:] 12 | 13 | 14 | print(whats_closer(sum_x, sum_y)) 15 | 16 | 17 | 18 | # 19 | # 20 | # 21 | # 22 | # 23 | # 24 | # 25 | # import math 26 | # 27 | # x1 = math.floor(float(input())) 28 | # x2 = math.floor(float(input())) 29 | # y1 = math.floor(float(input())) 30 | # y2 = math.floor(float(input())) 31 | # 32 | # sum_x = math.floor(abs(x1) + abs(x2)) 33 | # sum_y = math.floor(abs(y1) + abs(y2)) 34 | # 35 | # 36 | # def whats_closer(arg1, arg2): 37 | # if arg1 <= arg2: 38 | # return f"({x1}, {x2})" 39 | # 40 | # elif arg2 <= arg1: 41 | # return f"({y1}, {y2})" 42 | # 43 | # 44 | # print(whats_closer(sum_x, sum_y)) 45 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - More Exercise/03. Longer Line.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | x1, x2, y1, y2 = math.floor(float(input())), math.floor(float(input())), math.floor(float(input())), math.floor( 4 | float(input())) 5 | z1, z2, v1, v2 = math.floor(float(input())), math.floor(float(input())), math.floor(float(input())), math.floor( 6 | float(input())) 7 | 8 | sum_x = math.floor(abs(x1) + abs(x2)) 9 | sum_y = math.floor(abs(y1) + abs(y2)) 10 | sum_z = math.floor(abs(z1) + abs(z2)) 11 | sum_v = math.floor(abs(v1) + abs(v2)) 12 | 13 | 14 | def whats_closer(arg1, arg2, arg3, arg4): 15 | one = arg1 + arg2 16 | two = arg3 + arg4 17 | if one > two: 18 | if abs(x1) + abs(x2) > abs(y1) + abs(y2): 19 | return f"({y1}, {y2})({x1}, {x2})" 20 | else: 21 | return f"({x1}, {x2})({y1}, {y2})" 22 | elif one < two: 23 | if abs(z1) + abs(z2) > abs(v1) + abs(v2): 24 | return f"({v1}, {v2})({z1}, {z2})" 25 | else: 26 | return f"({z1}, {z2})({v1}, {v2})" 27 | else: 28 | if abs(z1) + abs(z2) > abs(v1) + abs(v2): 29 | return f"({v1}, {v2})({z1}, {z2})" 30 | else: 31 | return f"({z1}, {z2})({v1}, {v2})" 32 | 33 | 34 | print(whats_closer(sum_x, sum_y, sum_z, sum_v)) 35 | -------------------------------------------------------------------------------- /04. Functions/04. Functions - More Exercise/04. Tribonacci Sequence.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | 4 | def tribonacci(n): 5 | list = [1, 0, 0] 6 | for i in range(n): 7 | next_num = sum(list) 8 | print(next_num, end=" ") 9 | list.append(next_num) 10 | list.pop(0) 11 | 12 | 13 | tribonacci(n) 14 | 15 | 16 | # starting_number = int(input()) 17 | # 18 | # last_three = [1, 1] 19 | # 20 | # 21 | # def show_tribonacci(num): 22 | # for number in range(1, num + 1): 23 | # if number == 1 or number == 2: 24 | # print(last_three[number - 1], end=" ") 25 | # continue 26 | # else: 27 | # add_last_number = 0 28 | # if len(last_three) > 2: 29 | # add_last_number = last_three.pop(0) 30 | # print(sum(last_three) + add_last_number, end=" ") 31 | # last_three.append(sum(last_three) + add_last_number) 32 | # 33 | # 34 | # show_tribonacci(starting_number) -------------------------------------------------------------------------------- /04. Functions/04. Functions - More Exercise/05. Multiplication Sign.py: -------------------------------------------------------------------------------- 1 | number_one = int(input()) 2 | number_two = int(input()) 3 | number_three = int(input()) 4 | 5 | 6 | def check_numbers(one, two, three): 7 | if (three > 0 and one < 0 and two < 0) or \ 8 | (two > 0 and one < 0 and three < 0) or \ 9 | (one > 0 and two < 0 and three < 0) or \ 10 | (one > 0 and two > 0 and three > 0): 11 | return "positive" 12 | elif one == 0 or two == 0 or three == 0: 13 | return "zero" 14 | 15 | elif one < 0 or two < 0 or three < 0: 16 | return "negative" 17 | 18 | 19 | print(check_numbers(number_one, number_two, number_three)) 20 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/01. Which Are In.py: -------------------------------------------------------------------------------- 1 | first_sequence = input().split(", ") 2 | second_sequence = input().split(", ") 3 | result = [] 4 | for index in range(len(first_sequence)): 5 | for word in second_sequence: 6 | if first_sequence[index] in word: 7 | if first_sequence[index] not in result: 8 | result.append(first_sequence[index]) 9 | 10 | print(result) 11 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/02. Next Version.py: -------------------------------------------------------------------------------- 1 | current_version = input().split(".") 2 | version = current_version[0] + current_version[1] + current_version[2] 3 | new_version = int(version) + 1 4 | new_version_lst = [digit for digit in str(new_version)] 5 | print(".".join(new_version_lst)) 6 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/03. Word Filter.py: -------------------------------------------------------------------------------- 1 | some_text = [word for word in input().split() if len(word) % 2 == 0] 2 | print("\n".join(some_text)) 3 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/04. Number Classification.py: -------------------------------------------------------------------------------- 1 | numbers = list(map(int, input().split(", "))) 2 | positive_numbers = [str(number) for number in numbers if number >= 0] 3 | negative_numbers = [str(number) for number in numbers if number < 0] 4 | even_numbers = [str(number) for number in numbers if number % 2 == 0] 5 | odd_numbers = [str(number) for number in numbers if number % 2 != 0] 6 | print(f"Positive: {', '.join(positive_numbers)}") 7 | print(f"Negative: {', '.join(negative_numbers)}") 8 | print(f"Even: {', '.join(even_numbers)}") 9 | print(f"Odd: {', '.join(odd_numbers)}") 10 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/05. Office Chairs.py: -------------------------------------------------------------------------------- 1 | number_of_rooms = int(input()) 2 | free_chairs = [] 3 | chairs_are_enough = True 4 | for room in range(1, number_of_rooms + 1): 5 | chairs_and_visitors = input().split() 6 | current_chairs = len(chairs_and_visitors[0]) 7 | current_visitors = int(chairs_and_visitors[1]) 8 | if current_chairs >= current_visitors: 9 | free_chairs.append(current_chairs - current_visitors) 10 | else: 11 | chairs_are_enough = False 12 | needed_chairs = current_visitors - current_chairs 13 | print(f"{needed_chairs} more chairs needed in room {room}") 14 | if chairs_are_enough: 15 | print(f"Game On, {sum(free_chairs)} free chairs left") 16 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/06. Electron Distribution.py: -------------------------------------------------------------------------------- 1 | starting_electrons = int(input()) 2 | number_of_electrons = starting_electrons 3 | position = 0 4 | electrons_list = [] 5 | 6 | # TODO: Text 7 | 8 | # NORMAL COMMENT: Text 9 | 10 | # BUG: TEXT 11 | 12 | while number_of_electrons > 0: 13 | position += 1 14 | current_electrons = 2 * (position ** 2) 15 | if sum(electrons_list) + current_electrons <= starting_electrons: 16 | electrons_list.append(current_electrons) 17 | number_of_electrons -= current_electrons 18 | else: 19 | electrons_list.append(number_of_electrons) 20 | break 21 | print(electrons_list) 22 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/07. Group of 10's.py: -------------------------------------------------------------------------------- 1 | numbers_sequence = list(map(int, input().split(", "))) 2 | max_group = max(numbers_sequence) // 10 + 1 3 | if max(numbers_sequence) % 10 == 0: 4 | max_group -= 1 5 | current_group = 0 6 | for groups in range(max_group): 7 | group_list = [number for number in numbers_sequence if current_group < number <= (current_group + 10)] 8 | current_group += 10 9 | print(f"Group of {current_group}'s: {group_list}") 10 | group_list.clear() 11 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/08. Decipher This!.py: -------------------------------------------------------------------------------- 1 | def decipher(text): 2 | word_list = list(text) 3 | digits = [] 4 | letters = [] 5 | for digit in word_list: 6 | try: 7 | digits.append(int(digit)) 8 | except ValueError: 9 | letters.append(digit) 10 | number = int(''.join(map(str, digits))) 11 | word_list[0] = chr(number) 12 | result = [word_list[0]] + letters 13 | result[1], result[-1] = result[-1], result[1] 14 | return "".join(result) 15 | 16 | 17 | secret_message = input().split() 18 | for word in secret_message: 19 | print(decipher(word), end=" ") 20 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/09. Anonymous Threat.py: -------------------------------------------------------------------------------- 1 | def merge(list_name, start_index, end_index): 2 | if start_index < 0: 3 | start_index = 0 4 | result_list = list_name[:start_index] 5 | merged_element = "" 6 | index_is_in_range = True 7 | if end_index >= len(list_name): 8 | end_index = len(list_name) - 1 9 | index_is_in_range = False 10 | for index in range((end_index + 1) - start_index): 11 | current_index = index + start_index 12 | merged_element += list_name[current_index] 13 | result_list.append(merged_element) 14 | if index_is_in_range: 15 | result_list += list_name[(end_index + 1):] 16 | return result_list 17 | 18 | 19 | def divide(list_name, index, partitions): 20 | result_list = list_name[:index] 21 | string_to_divide = list_name[index] 22 | current_substring = "" 23 | last_substring = "" 24 | letters_in_partition = len(string_to_divide) // partitions 25 | if len(string_to_divide) % partitions != 0: 26 | slice_index = (partitions - 1) * letters_in_partition 27 | last_substring = string_to_divide[slice_index:] 28 | string_to_divide = string_to_divide[:slice_index] 29 | for letter in string_to_divide: 30 | current_substring += letter 31 | if len(current_substring) == letters_in_partition: 32 | result_list.append(current_substring) 33 | current_substring = "" 34 | if last_substring != "": 35 | result_list.append(last_substring) 36 | if (index + 1) < len(list_name): 37 | result_list += list_name[index + 1:] 38 | return result_list 39 | 40 | 41 | data_array = input().split() 42 | command = input() 43 | while command != "3:1": 44 | current_command = command.split()[0] 45 | first_value = int(command.split()[1]) 46 | second_value = int(command.split()[2]) 47 | if current_command == "merge": 48 | data_array = merge(data_array, first_value, second_value) 49 | elif current_command == "divide": 50 | data_array = divide(data_array, first_value, second_value) 51 | command = input() 52 | print(" ".join(data_array)) 53 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/10. Pokemon Don't Go.py: -------------------------------------------------------------------------------- 1 | numbers_sequence = list(map(int, input().split())) 2 | removed_pokemons = [] 3 | while len(numbers_sequence) > 0: 4 | current_index = int(input()) 5 | if current_index < 0: 6 | removed = numbers_sequence[0] 7 | numbers_sequence[0] = numbers_sequence[-1] 8 | elif current_index >= len(numbers_sequence): 9 | removed = numbers_sequence[-1] 10 | numbers_sequence[-1] = numbers_sequence[0] 11 | else: 12 | removed = numbers_sequence.pop(current_index) 13 | removed_pokemons.append(removed) 14 | result_list = [] 15 | for number in numbers_sequence: 16 | if number <= removed: 17 | result_list.append(number + removed) 18 | else: 19 | result_list.append(number - removed) 20 | numbers_sequence = result_list.copy() 21 | print(sum(removed_pokemons)) 22 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Exercise/11. SoftUni Course Planning.py: -------------------------------------------------------------------------------- 1 | schedule = input().split(", ") 2 | command = input() 3 | while command != "course start": 4 | modification = command.split(":")[0] 5 | title = command.split(":")[1] 6 | if modification == "Add": 7 | if title not in schedule: 8 | schedule.append(title) 9 | elif modification == "Insert": 10 | insert_index = int(command.split(":")[2]) 11 | if title not in schedule: 12 | schedule.insert(insert_index, title) 13 | elif modification == "Remove": 14 | if title in schedule: 15 | remove_index = schedule.index(title) 16 | if remove_index + 1 == len(schedule): 17 | schedule.pop() 18 | else: 19 | schedule.pop(remove_index) 20 | if schedule[remove_index] == f"{title}-Exercise": 21 | schedule.pop(remove_index) 22 | elif modification == "Swap": 23 | first_title = title 24 | second_title = command.split(":")[2] 25 | if first_title in schedule and second_title in schedule: 26 | first_title_index = schedule.index(first_title) 27 | second_title_index = schedule.index(second_title) 28 | schedule[first_title_index], schedule[second_title_index] = \ 29 | schedule[second_title_index], schedule[first_title_index] 30 | elif modification == "Exercise": 31 | if title in schedule: 32 | if f"{title}-Exercise" not in schedule: 33 | exercise_index = schedule.index(title) + 1 34 | schedule.insert(exercise_index, f"{title}-Exercise") 35 | else: 36 | schedule.append(title) 37 | schedule.append(f"{title}-Exercise") 38 | for lesson in schedule: 39 | exercise_letters = len("Exercise") 40 | if lesson[-exercise_letters:] == "Exercise": 41 | exercise_title = lesson[:-exercise_letters - 1] 42 | if schedule.index(exercise_title) + 1 == schedule.index(lesson): 43 | continue 44 | else: 45 | current_exercise_index = schedule.index(lesson) 46 | new_exercise_index = schedule.index(exercise_title) + 1 47 | if current_exercise_index > new_exercise_index: 48 | schedule.pop(current_exercise_index) 49 | schedule.insert(new_exercise_index, lesson) 50 | else: 51 | schedule.insert(new_exercise_index, lesson) 52 | schedule.pop(current_exercise_index) 53 | break 54 | command = input() 55 | lesson_counter = 0 56 | for element in schedule: 57 | lesson_counter += 1 58 | print(f"{lesson_counter}.{element}") 59 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/01. No Vowels.py: -------------------------------------------------------------------------------- 1 | text = input() 2 | vowels = ["a", "o", "e", "i", "u"] 3 | no_vowels = [letter for letter in text if letter.lower() not in vowels] 4 | print("".join(no_vowels)) 5 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/02. Trains.py: -------------------------------------------------------------------------------- 1 | number_of_wagons = int(input()) 2 | train = [0 for wagon in range(number_of_wagons)] 3 | command = input() 4 | while command != "End": 5 | current_command = command.split()[0] 6 | if current_command == "add": 7 | add_count = int(command.split()[1]) 8 | train[-1] += int(add_count) 9 | elif current_command == "insert": 10 | insert_index = int(command.split()[1]) 11 | insert_count = int(command.split()[2]) 12 | train[insert_index] += insert_count 13 | elif current_command == "leave": 14 | leave_index = int(command.split()[1]) 15 | leave_count = int(command.split()[2]) 16 | train[leave_index] -= leave_count 17 | command = input() 18 | 19 | print(train) 20 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/03. To-do List.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | to_do_list = [0] * 10 3 | while command != "End": 4 | tasks = command.split("-") 5 | current_task = tasks[1] 6 | priority = int(tasks[0]) 7 | to_do_list.pop(priority - 1) 8 | to_do_list.insert(priority - 1, current_task) 9 | command = input() 10 | final_list = [task for task in to_do_list if task != 0] 11 | print(final_list) 12 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/04. Palindrome Strings.py: -------------------------------------------------------------------------------- 1 | words = input().split() 2 | palindrome = input() 3 | palindrome_list = [word for word in words if word == word[::-1]] 4 | occurrences = palindrome_list.count(palindrome) 5 | print(palindrome_list) 6 | print(f"Found palindrome {occurrences} times") 7 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/05. Sorting Names.py: -------------------------------------------------------------------------------- 1 | names = input().split(", ") 2 | sorted_names = sorted(names, key=lambda name: (-len(name), name)) 3 | print(sorted_names) 4 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/06. Even Numbers.py: -------------------------------------------------------------------------------- 1 | numbers_string = input().split(", ") 2 | numbers = list(map(int, numbers_string)) 3 | indices = [] 4 | for index in range(len(numbers)): 5 | if numbers[index] % 2 == 0: 6 | indices.append(index) 7 | print(indices) 8 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - Lab/07. The Office.py: -------------------------------------------------------------------------------- 1 | employees_happiness = list(map(int, input().split())) 2 | improvement_factor = int(input()) 3 | calculated_happiness = list(map(lambda happiness: happiness * improvement_factor, employees_happiness)) 4 | average_happiness = sum(calculated_happiness) / len(calculated_happiness) 5 | happy_list = [item for item in calculated_happiness if item >= average_happiness] 6 | happy_count = len(happy_list) 7 | total_count = len(employees_happiness) 8 | score = happy_count / total_count 9 | if score >= 1 / 2: 10 | print(f"Score: {happy_count}/{total_count}. Employees are happy!") 11 | else: 12 | print(f"Score: {happy_count}/{total_count}. Employees are not happy!") 13 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - More Exercise/01. Social Distribution.py: -------------------------------------------------------------------------------- 1 | population = list(map(int, input().split(", "))) 2 | minimum_wealth = int(input()) 3 | countries_count = len(population) 4 | if sum(population) < countries_count * minimum_wealth: 5 | print("No equal distribution possible") 6 | else: 7 | while min(population) < minimum_wealth: 8 | for index, country in enumerate(population): 9 | if country < minimum_wealth: 10 | difference = minimum_wealth - country 11 | population[index] += difference 12 | max_population_index = population.index(max(population)) 13 | population[max_population_index] -= difference 14 | print(population) -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - More Exercise/02. TakeSkip Rope.py: -------------------------------------------------------------------------------- 1 | def uncover_message(string, take, skip): 2 | final_message = "" 3 | for change in range(len(take)): 4 | take_num = take[change] 5 | skip_num = skip[change] 6 | final_message += string[:take_num] 7 | string = string[take_num:] 8 | string = string[skip_num:] 9 | return final_message 10 | 11 | 12 | mixed_string = input() 13 | digits_list = [] 14 | symbols_list = [] 15 | take_list = [] 16 | skip_list = [] 17 | for symbol in mixed_string: 18 | if symbol.isdigit(): 19 | digits_list.append(int(symbol)) 20 | else: 21 | symbols_list.append(symbol) 22 | for index, digit in enumerate(digits_list): 23 | if index % 2 == 0: 24 | take_list.append(digit) 25 | else: 26 | skip_list.append(digit) 27 | starting_string = "".join(symbols_list) 28 | print(uncover_message(starting_string, take_list, skip_list)) -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - More Exercise/03. Kate's Way Out.py: -------------------------------------------------------------------------------- 1 | def find_position(maze): 2 | position = [] 3 | for row in range(len(maze)): 4 | for el in maze[row]: 5 | if el == 'k': 6 | position.append(row) 7 | position.append(maze[row].find('k')) 8 | return position 9 | 10 | 11 | def next_free_spot(maze): 12 | free_spots = [] 13 | 14 | for row in range(len(maze)): 15 | for el in range(len(maze[row])): 16 | tmp = [] 17 | if maze[row][el] == ' ': 18 | tmp.append(row) 19 | tmp.append(el) 20 | free_spots.insert(0, tmp) 21 | 22 | return free_spots 23 | 24 | 25 | def find_path(position, next_free, maze): 26 | is_blocked = True 27 | step = 0 28 | moves = 0 29 | 30 | while step < len(next_free): 31 | x1 = next_free[step][0] 32 | x2 = next_free[step][1] 33 | temp = [] 34 | temp.append(x1) 35 | temp.append(x2) 36 | # moving left 37 | if temp[0] == position[0] and position[1] - temp[1] == 1: 38 | position = temp 39 | moves += 1 40 | next_free.pop(step) 41 | step = 0 42 | # moving right 43 | elif temp[0] == position[0] and temp[1] - position[1] == 1: 44 | position = temp 45 | moves += 1 46 | next_free.pop(step) 47 | step = 0 48 | # moving down 49 | elif temp[0] - position[0] == 1 and position[1] == temp[1]: 50 | position = temp 51 | moves += 1 52 | next_free.pop(step) 53 | step = 0 54 | # moving up 55 | elif position[0] - temp[0] == 1 and position[1] == temp[1]: 56 | position = temp 57 | moves += 1 58 | next_free.pop(step) 59 | step = 0 60 | 61 | else: 62 | 63 | step += 1 64 | 65 | if position[0] == 0 or position[0] == (len(maze) -1) or position[1] == 0 or position[1] == len(maze[0]): 66 | return f'Kate got out in {moves + 1} moves' 67 | return f'Kate cannot get out' 68 | 69 | m_rows = int(input()) 70 | maze = [] 71 | moves = 0 72 | free_space = True 73 | for row in range(m_rows): 74 | maze.append(input()) 75 | position = find_position(maze) 76 | next_free = next_free_spot(maze) 77 | movement = find_path(position, next_free, maze) 78 | print(movement) 79 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - More Exercise/04. Battle Ships.py: -------------------------------------------------------------------------------- 1 | def ship_attack(row, ship, ship_list): 2 | attacked_row = ship_list[row] 3 | zeros_count = attacked_row.count(0) 4 | ships_destroyed = 0 5 | if attacked_row[ship] > 0: 6 | attacked_row[ship] -= 1 7 | new_zeros_count = attacked_row.count(0) 8 | if new_zeros_count > zeros_count: 9 | ships_destroyed = 1 10 | return ship_list, ships_destroyed 11 | 12 | 13 | number_of_rows = int(input()) 14 | ships_list = [] 15 | for row in range(number_of_rows): 16 | current_row_list = list(map(int, input().split())) 17 | ships_list.append(current_row_list) 18 | 19 | attacks = input().split() 20 | destroyed_ships = 0 21 | 22 | for action in attacks: 23 | current_row = int(action[0]) 24 | current_ship = int(action[2]) 25 | ships_list, current_destroyed_ships = ship_attack(current_row, current_ship, ships_list) 26 | if current_destroyed_ships != 0: 27 | destroyed_ships += 1 28 | 29 | print(destroyed_ships) 30 | -------------------------------------------------------------------------------- /05. Lists Advanced/05. Lists Advanced - More Exercise/05. Dots.py: -------------------------------------------------------------------------------- 1 | ROWS = int(input()) 2 | matrix = [input().split() for _ in range(ROWS)] 3 | COLS = len(matrix[0]) 4 | 5 | 6 | def is_safe(_matrix, row, col, visited): 7 | if (row >= 0) and (col >= 0) and (row < ROWS) and (col < COLS): 8 | if (matrix[row][col] == '.') and not visited[row][col]: 9 | return True 10 | 11 | 12 | def depth_first_search(_matrix, row, col, visited, count): 13 | _rows = [-1, 0, 1, 0] 14 | _cols = [0, 1, 0, -1] 15 | visited[row][col] = True 16 | 17 | for i in range(4): 18 | if is_safe(_matrix, row + _rows[i], col + _cols[i], visited): 19 | count[0] += 1 20 | depth_first_search(_matrix, row + _rows[i], col + _cols[i], visited, count) 21 | 22 | 23 | def largest_region(_matrix): 24 | visited = [[0] * COLS for _ in range(ROWS)] 25 | result = 0 26 | 27 | for i in range(ROWS): 28 | for j in range(COLS): 29 | if _matrix[i][j] == '.' and not visited[i][j]: 30 | count = [1] 31 | depth_first_search(_matrix, i, j, visited, count) 32 | result = max(result, count[0]) 33 | 34 | return result 35 | 36 | 37 | print(largest_region(matrix)) 38 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/01. Storage.py: -------------------------------------------------------------------------------- 1 | class Storage: 2 | 3 | def __init__(self, capacity): 4 | self.capacity = capacity 5 | self.storage = [] 6 | 7 | def add_product(self, product): 8 | if self.capacity - 1 >= 0: 9 | self.storage.append(product) 10 | self.capacity -= 1 11 | 12 | def get_products(self): 13 | return self.storage 14 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/02. Weapon.py: -------------------------------------------------------------------------------- 1 | class Weapon: 2 | 3 | def __init__(self, bullets): 4 | self.bullets = int(bullets) 5 | 6 | def shoot(self): 7 | if self.bullets - 1 >= 0: 8 | self.bullets -= 1 9 | return "shooting..." 10 | else: 11 | return "no bullets left" 12 | 13 | def __repr__(self): 14 | return f"Remaining bullets: {self.bullets}" 15 | 16 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/03. Catalogue.py: -------------------------------------------------------------------------------- 1 | class Catalogue: 2 | 3 | def __init__(self, name): 4 | self.name = str(name) 5 | self.products = [] 6 | 7 | def add_product(self, product_name): 8 | self.products.append(str(product_name)) 9 | 10 | def get_by_letter(self, first_letter): 11 | return [x for x in self.products if x.startswith(first_letter)] 12 | 13 | def __repr__(self): 14 | show_result = "Items in the {0} catalogue:\n" \ 15 | "{1}".format(self.name, '\n'.join(sorted(self.products))) 16 | return show_result 17 | 18 | 19 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/04. Town.py: -------------------------------------------------------------------------------- 1 | class Town: 2 | 3 | def __init__(self, name): 4 | self.name = name 5 | self.latitude = "0°N" 6 | self.longitude = "0°E" 7 | 8 | def set_latitude(self, latitude): 9 | self.latitude = latitude 10 | 11 | def set_longitude(self, longitude): 12 | self.longitude = longitude 13 | 14 | def __repr__(self): 15 | return f"Town: {self.name} | Latitude: {self.latitude} | Longitude: {self.longitude}" 16 | 17 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/05. Class.py: -------------------------------------------------------------------------------- 1 | class Class: 2 | __students_count = 22 3 | 4 | def __init__(self, name): 5 | self.name = name 6 | self.students = [] 7 | self.grades = [] 8 | 9 | def add_student(self, name: str, grade: float): 10 | Class.__students_count -= 1 11 | if Class.__students_count >= 0: 12 | self.students.append(name) 13 | self.grades.append(grade) 14 | 15 | def get_average_grade(self): 16 | number = f"{(sum(self.grades) / len(self.grades)):.2f}" 17 | return float(number) 18 | 19 | def __repr__(self): 20 | return f"The students in {self.name}: {', '.join(self.students)}. " \ 21 | f"Average grade: {Class.get_average_grade(self)}" 22 | 23 | a_class = Class("11B") 24 | a_class.add_student("Peter", 4.80) 25 | a_class.add_student("George", 6.00) 26 | a_class.add_student("Amy", 3.50) 27 | print(a_class.get_average_grade()) 28 | print(a_class) -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/06. Inventory.py: -------------------------------------------------------------------------------- 1 | class Inventory: 2 | 3 | def __init__(self, capacity: int): 4 | self.__capacity = int(capacity) 5 | self.items = [] 6 | self.left_over = 0 7 | 8 | def add_item(self, item: str): 9 | if self.left_over < self.__capacity: 10 | self.items.append(str(item)) 11 | self.left_over += 1 12 | else: 13 | return "not enough room in the inventory" 14 | 15 | def get_capacity(self): 16 | return self.__capacity 17 | 18 | def __repr__(self): 19 | return f"Items: {', '.join(self.items)}.\nCapacity left: {Inventory.get_capacity(self) - self.left_over}" 20 | 21 | 22 | inventory = Inventory(2) 23 | inventory.add_item("potion") 24 | inventory.add_item("sword") 25 | print(inventory.add_item("bottle")) 26 | print(inventory.get_capacity()) 27 | print(inventory) 28 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/07. Articles.py: -------------------------------------------------------------------------------- 1 | class Article: 2 | 3 | def __init__(self, title, content, author): 4 | self.title = title 5 | self.content = content 6 | self.author = author 7 | 8 | def edit(self, new_content): 9 | self.content = new_content 10 | 11 | def change_author(self, new_author): 12 | self.author = new_author 13 | 14 | def rename(self, new_title): 15 | self.title = new_title 16 | 17 | def __repr__(self): 18 | return f"{self.title} - {self.content}: {self.author}" 19 | 20 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/08. Vehicle.py: -------------------------------------------------------------------------------- 1 | class Vehicle: 2 | 3 | def __init__(self, type, model, price, owner=None): 4 | self.type = type 5 | self.model = model 6 | self.price = price 7 | self.owner = owner 8 | 9 | def buy(self, money, owner): 10 | if self.price <= money and self.owner is None: 11 | self.owner = owner 12 | return f"Successfully bought a {self.type}. Change: {(money - self.price):.2f}" 13 | elif self.price > money: 14 | return "Sorry, not enough money" 15 | elif self.owner is not None: 16 | return "Car already sold" 17 | 18 | def sell(self): 19 | if self.owner is not None: 20 | self.owner = None 21 | else: 22 | return "Vehicle has no owner" 23 | 24 | def __repr__(self): 25 | if self.owner is None: 26 | return f"{self.model} {self.type} is on sale: {self.price}" 27 | else: 28 | return f"{self.model} {self.type} is owned by: {self.owner}" 29 | 30 | # vehicle_type = "car" 31 | # model = "BMW" 32 | # price = 30000 33 | # vehicle = Vehicle(vehicle_type, model, price) 34 | # print(vehicle.buy(15000, "Peter")) 35 | # print(vehicle.buy(35000, "George")) 36 | # print(vehicle) 37 | # vehicle.sell() 38 | # print(vehicle) -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Exercise/09. Movie.py: -------------------------------------------------------------------------------- 1 | class Movie: 2 | __watched_movies = 0 3 | 4 | def __init__(self, name, director, watched=False): 5 | self.name = name 6 | self.director = director 7 | self.watched = watched 8 | 9 | def change_name(self, new_name): 10 | self.name = new_name 11 | 12 | def change_director(self, new_director): 13 | self.director = new_director 14 | 15 | def watch(self): 16 | if not self.watched: 17 | self.watched = True 18 | Movie.__watched_movies += 1 19 | 20 | def __repr__(self): 21 | return f"Movie name: {self.name}; Movie director: {self.director}. Total watched movies: {Movie.__watched_movies}" 22 | 23 | 24 | # first_movie = Movie("Inception", "Christopher Nolan") 25 | # second_movie = Movie("The Matrix", "The Wachowskis") 26 | # third_movie = Movie("The Predator", "Shane Black") 27 | # first_movie.change_director("Me") 28 | # third_movie.change_name("My Movie") 29 | # first_movie.watch() 30 | # third_movie.watch() 31 | # first_movie.watch() 32 | # print(first_movie) 33 | # print(second_movie) 34 | # print(third_movie) -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Lab/01. Comment.py: -------------------------------------------------------------------------------- 1 | class Comment: 2 | 3 | def __init__(self, username, content, likes=0): 4 | self.username = username 5 | self.content = content 6 | self.likes = likes -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Lab/02. Party.py: -------------------------------------------------------------------------------- 1 | class Party: 2 | def __init__(self): 3 | self.people = [] 4 | 5 | 6 | party_people = Party() 7 | data_input = input() 8 | while data_input != "End": 9 | party_people.people.append(data_input) 10 | data_input = input() 11 | 12 | print(f"Going: {', '.join(party_people.people)}") 13 | print(f"Total: {len(party_people.people)}") 14 | 15 | # class Party: 16 | # def __init__(self): 17 | # self.name = [] 18 | # 19 | # def add_people(self, names): 20 | # self.name.append(names) 21 | # 22 | # 23 | # party_people = Party() 24 | # 25 | # names_given = input() 26 | # 27 | # while names_given != "End": 28 | # party_people.add_people(names_given) 29 | # names_given = input() 30 | # 31 | # print("Going:", end=" ") 32 | # print(*party_people.name, sep=", ") 33 | # print(f"Total: {len(party_people.name)}") 34 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Lab/03. Email.py: -------------------------------------------------------------------------------- 1 | class Email: 2 | email_information = [] 3 | 4 | def __init__(self, sender, receiver, content): 5 | self.sender = sender 6 | self.receiver = receiver 7 | self.content = content 8 | self.is_sent = False 9 | 10 | def send(self): 11 | self.is_sent = True 12 | 13 | def get_info(self): 14 | return f"{self.sender} says to {self.receiver}: {self.content}. Sent: {self.is_sent}" 15 | 16 | 17 | data_input = input() 18 | 19 | while data_input != "Stop": 20 | sender, receiver, *content = data_input.split() 21 | Email.email_information.append(Email(sender, receiver, ''.join(content))) 22 | data_input = input() 23 | 24 | send_mails = [int(x) for x in input().split(", ")] 25 | 26 | for pos, email in enumerate(Email.email_information): 27 | if pos in send_mails: 28 | email.send() 29 | print(email.get_info()) 30 | 31 | 32 | 33 | 34 | # class Email: 35 | # def __init__(self, sender, receiver, content): 36 | # self.sender = sender 37 | # self.receiver = receiver 38 | # self.content = content 39 | # self.is_sent = False 40 | # 41 | # def send(self): 42 | # self.is_sent = True 43 | # 44 | # def get_info(self): 45 | # return f"{self.sender} says to {self.receiver}: {self.content}. Sent: {self.is_sent}" 46 | # 47 | # 48 | # emails = [] 49 | # line = input() 50 | # 51 | # while line != "Stop": 52 | # line = line.split() 53 | # email = Email(line[0], line[1], line[2]) 54 | # emails.append(email) 55 | # line = input() 56 | # 57 | # send_emails = [int(n) for n in input().split(", ")] 58 | # 59 | # for index, email in enumerate(emails): 60 | # if index in send_emails: 61 | # emails[index].send() 62 | # print(email.get_info()) 63 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Lab/04. Zoo.py: -------------------------------------------------------------------------------- 1 | animals_info = [] 2 | name_animal = {"mammal": "Mammals", "fish": "Fishes", "bird": "Birds"} 3 | 4 | 5 | class Zoo: 6 | __animals = 0 7 | 8 | def __init__(self, name_zoo, name, type): 9 | self.name_zoo = name_zoo 10 | self.name = name 11 | self.type = type 12 | 13 | def get_info(self, species): 14 | if species == self.type: 15 | return True 16 | return False 17 | 18 | 19 | zoo_name = input() 20 | Zoo.animals = int(input()) 21 | for _ in range(Zoo.animals): 22 | type, name = input().split() 23 | animals_info.append(Zoo(zoo_name, name, type)) 24 | 25 | show_animals = input() 26 | print( 27 | f"{name_animal[show_animals]} in {zoo_name}: {', '.join([x.name for x in animals_info if x.get_info(show_animals)])}") 28 | print(f"Total animals: {Zoo.animals}") 29 | 30 | 31 | 32 | 33 | # class Zoo: 34 | # __animals = 0 35 | # 36 | # def __init__(self, name_zoo): 37 | # self.name_zoo = name_zoo 38 | # self.mammals = [] 39 | # self.fishes = [] 40 | # self.birds = [] 41 | # 42 | # def add_animal(self, species, name): 43 | # if species == "mammal": 44 | # self.mammals.append(name) 45 | # elif species == "fish": 46 | # self.fishes.append(name) 47 | # elif species == "bird": 48 | # self.birds.append(name) 49 | # zoo.__animals += 1 50 | # 51 | # def get_info(self, species): 52 | # if species == "mammal": 53 | # return f"{species.capitalize()}s in {self.name_zoo}: {', '.join(self.mammals)}\nTotal animals: {zoo.__animals}" 54 | # elif species == "fish": 55 | # return f"Fishes in {self.name_zoo}: {', '.join(self.fishes)}\nTotal animals: {zoo.__animals}" 56 | # elif species == "bird": 57 | # return f"{species.capitalize()}s in {self.name_zoo}: {', '.join(self.birds)}\nTotal animals: {zoo.__animals}" 58 | # 59 | # 60 | # zoo = Zoo(input()) 61 | # 62 | # for _ in range(int(input())): 63 | # animal_type = input().split() 64 | # zoo.add_animal(animal_type[0], animal_type[-1]) 65 | # 66 | # print(zoo.get_info(input())) 67 | -------------------------------------------------------------------------------- /06. Objects and Classes/06. Objects and Classes - Lab/05. Circle.py: -------------------------------------------------------------------------------- 1 | class Circle: 2 | __pi = 3.14 3 | 4 | def __init__(self, diameter): 5 | self.diameter = diameter 6 | self.radius = diameter / 2 7 | 8 | def calculate_circumference(self): 9 | return Circle.__pi * self.diameter 10 | 11 | def calculate_area(self): 12 | return Circle.__pi * (self.radius ** 2) 13 | 14 | def calculate_area_of_sector(self, angle): 15 | return (angle / 360) * Circle.__pi * (self.radius ** 2) 16 | 17 | 18 | # circle = Circle(10) 19 | # angle = 5 20 | # 21 | # print(f"{circle.calculate_circumference():.2f}") 22 | # print(f"{circle.calculate_area():.2f}") 23 | # print(f"{circle.calculate_area_of_sector(angle):.2f}") 24 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/01. Count Chars in a String.py: -------------------------------------------------------------------------------- 1 | characters = input().replace(" ", "") 2 | 3 | character_count = {} 4 | 5 | for character in characters: 6 | character_count[character] = character_count.get(character, 0) 7 | character_count[character] += 1 8 | for key, value in character_count.items(): 9 | print(f"{key} -> {value}") 10 | 11 | 12 | 13 | 14 | 15 | 16 | # characters = input().replace(" ", "") 17 | # 18 | # character_count = {} 19 | # 20 | # for character in characters: 21 | # 22 | # if character not in character_count: 23 | # character_count[character] = 0 24 | # character_count[character] += 1 25 | # 26 | # for key, value in character_count.items(): 27 | # print(f"{key} -> {value}") 28 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/02. A Miner Task.py: -------------------------------------------------------------------------------- 1 | resourse = input() 2 | 3 | total_resourse = dict() 4 | while resourse != "stop": 5 | quantity = int(input()) 6 | total_resourse[resourse] = total_resourse.get(resourse, 0) 7 | total_resourse[resourse] += quantity 8 | resourse = input() 9 | 10 | for key, value in total_resourse.items(): 11 | print(f"{key} -> {value}") 12 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/03. Capitals.py: -------------------------------------------------------------------------------- 1 | country_name = input().split(", ") 2 | capital_name = input().split(", ") 3 | 4 | country_information = {key: value for key, value in zip(country_name, capital_name)} 5 | # for country, capital in zip(country_name, capital_name): 6 | # print(f"{country} -> {capital}") 7 | for country, capital in country_information.items(): 8 | print(f"{country} -> {capital}") -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/04. Phonebook.py: -------------------------------------------------------------------------------- 1 | phone_book = {} 2 | phone_number = input() 3 | while not phone_number.isdigit(): 4 | name, number = phone_number.split("-") 5 | phone_book[name] = phone_book.get(name, number) 6 | phone_number = input() 7 | 8 | for _ in range(int(phone_number)): 9 | name_check = input() 10 | if name_check in phone_book: 11 | print(f"{name_check} -> {phone_book[name_check]}") 12 | else: 13 | print(f"Contact {name_check} does not exist.") 14 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/05. Legendary Farming.py: -------------------------------------------------------------------------------- 1 | items_information = { 2 | "shards": 0, 3 | "fragments": 0, 4 | "motes": 0 5 | } 6 | shadowmourne = False 7 | valanyr = False 8 | dragonwrath = False 9 | 10 | 11 | def check_from_items(): 12 | global shadowmourne 13 | global valanyr 14 | global dragonwrath 15 | if items_information["shards"] >= 250: 16 | shadowmourne = True 17 | print(f"Shadowmourne obtained!") 18 | items_information["shards"] += - 250 19 | 20 | elif items_information["fragments"] >= 250: 21 | items_information["fragments"] += -250 22 | print(f"Valanyr obtained!") 23 | valanyr = True 24 | 25 | elif items_information["motes"] >= 250: 26 | items_information["motes"] += - 250 27 | print(f"Dragonwrath obtained!") 28 | dragonwrath = True 29 | 30 | 31 | def print_winner(): 32 | for key, value in items_information.items(): 33 | print(f"{key}: {value}") 34 | 35 | 36 | while not shadowmourne and not valanyr and not dragonwrath: 37 | collected_items = input().lower().split() 38 | i = 1 39 | counter = 0 40 | for _ in range(int(len(collected_items) / 2)): 41 | type_item = collected_items[i] 42 | quantity_item = int(collected_items[counter]) 43 | items_information[collected_items[i]] = items_information.get(collected_items[i], 0) 44 | items_information[type_item] += quantity_item 45 | counter += 2 46 | i += 2 47 | check_from_items() 48 | if shadowmourne or valanyr or dragonwrath: 49 | break 50 | 51 | print_winner() 52 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/06. Orders.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | 3 | drinks_info = {} 4 | price_d = "price" 5 | quantity_d = "quantity" 6 | 7 | while command != "buy": 8 | name, price, quantity = [float(x) if x[-1].isdigit() else x for x in command.split()] 9 | drinks_info[name] = drinks_info.get(name, {}) 10 | drinks_info[name][price_d] = drinks_info[name].get(price_d, 0) 11 | drinks_info[name][quantity_d] = drinks_info[name].get(quantity_d, 0) 12 | drinks_info[name][price_d] = price 13 | drinks_info[name][quantity_d] += quantity 14 | command = input() 15 | 16 | for product_name in drinks_info: 17 | result = drinks_info[product_name][price_d] * drinks_info[product_name][quantity_d] 18 | print(f"{product_name} -> {result:.2f}") 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/07. SoftUni Parking.py: -------------------------------------------------------------------------------- 1 | number_cars = int(input()) 2 | parking_info = {} 3 | 4 | 5 | def register_car(name, number): 6 | if name in parking_info: 7 | print(f"ERROR: already registered with plate number {parking_info[name]}") 8 | return 9 | parking_info[name] = number 10 | print(f"{name} registered {number} successfully") 11 | 12 | 13 | def unregister_car(name): 14 | if name not in parking_info: 15 | print(f"ERROR: user {name} not found") 16 | return 17 | del parking_info[name] 18 | print(f"{name} unregistered successfully") 19 | 20 | 21 | def all_cars_in_praking(): 22 | for key, value in parking_info.items(): 23 | print(f"{key} => {value}") 24 | 25 | 26 | for _ in range(number_cars): 27 | command, name, *number = input().split() 28 | if command == "register": 29 | number = number[-1] 30 | register_car(name, number) 31 | else: 32 | unregister_car(name) 33 | 34 | all_cars_in_praking() 35 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/08. Courses.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | 3 | school_information = {} 4 | while command != "end": 5 | command = command.split(" : ") 6 | language_name = command[0] 7 | studen_name = command[1] 8 | school_information[language_name] = school_information.get(language_name, {}) 9 | school_information[language_name][studen_name] = studen_name 10 | command = input() 11 | 12 | for lang in school_information: 13 | print(f"{lang}: {len(school_information[lang])}") 14 | for key, value in school_information[lang].items(): 15 | print(f"-- {value}") 16 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/09. Student Academy.py: -------------------------------------------------------------------------------- 1 | number_students = int(input()) 2 | 3 | students_grades = {} 4 | 5 | for _ in range(number_students): 6 | name = input() 7 | grade = float(input()) 8 | students_grades[name] = students_grades.get(name, {}) 9 | students_grades[name][name + str(grade)] = 0 10 | students_grades[name][name + str(grade)] += grade 11 | 12 | for name_student in students_grades: 13 | score = 0 14 | for key, value in students_grades[name_student].items(): 15 | score += value 16 | average_score = score / len(students_grades[name_student]) 17 | if average_score >= 4.50: 18 | print(f"{name_student} -> {average_score:.2f}") 19 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/10. Company Users.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | 3 | company_info = {} 4 | 5 | 6 | def employee_id_search(id): 7 | for value in company_info[id].values(): 8 | if id == value: 9 | return True 10 | return False 11 | 12 | 13 | while command != "End": 14 | company_name, employee_id = command.split(" -> ") 15 | company_info[company_name] = company_info.get(company_name, {}) 16 | if not employee_id_search(company_name): 17 | company_info[company_name][employee_id] = employee_id 18 | command = input() 19 | 20 | for name_uni in company_info: 21 | print(name_uni) 22 | for key, value in company_info[name_uni].items(): 23 | print(f"-- {value}") 24 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/11. Force Book.py: -------------------------------------------------------------------------------- 1 | forces = {} 2 | 3 | 4 | def add_user_to_side(name, side): 5 | for users in forces.values(): 6 | if name in users: 7 | return 8 | forces[side] = forces.get(side, []) + [name] 9 | 10 | 11 | def switch_side(side, name): 12 | for sides_, users in forces.items(): 13 | if name in users: 14 | forces[sides_].remove(name) 15 | break 16 | forces[side] = forces.get(side, []) + [name] 17 | print(f"{name} joins the {side} side!") 18 | 19 | 20 | command = input() 21 | 22 | while command != "Lumpawaroo": 23 | if "|" in command: 24 | side, name = command.split(" | ") 25 | add_user_to_side(name, side) 26 | elif "->" in command: 27 | side, name = command.split(" -> ") 28 | switch_side(name, side) 29 | 30 | command = input() 31 | 32 | for side, members in forces.items(): 33 | if members: 34 | print(f"Side: {side}, Members: {len(members)}") 35 | for user in members: 36 | print(f"! {user}") 37 | 38 | 39 | 40 | 41 | 42 | # 43 | # 44 | # force_command = input() 45 | # 46 | # force_book = {} 47 | # 48 | # 49 | # def force_side(side_, user_): 50 | # for key in force_book: 51 | # if user_ in force_book[key]: 52 | # return 53 | # force_book[side_] = force_book.get(side_, {}) 54 | # force_book[side_][user_] = force_book.get(user_, side_) 55 | # 56 | # 57 | # def force_change(user_, side_): 58 | # for key in force_book: 59 | # if user_ in force_book[key]: 60 | # del force_book[key][user_] 61 | # break 62 | # force_book[side_] = force_book.get(side_, {}) 63 | # force_book[side_][user_] = force_book.get(user_, side_) 64 | # print(f"{user_} joins the {side_} side!") 65 | # 66 | # 67 | # while force_command != "Lumpawaroo": 68 | # 69 | # if " | " in force_command: 70 | # force_command = force_command.split(" | ") 71 | # force_side(str(force_command[0]), str(force_command[-1])) 72 | # elif " -> " in force_command: 73 | # force_command = force_command.split(" -> ") 74 | # force_change(str(force_command[0]), str(force_command[-1])) 75 | # force_command = input() 76 | # 77 | # for side in force_book: 78 | # if force_book[side]: 79 | # print(f"Side: {side}, Members: {len(force_book[side])}") 80 | # for name in force_book[side]: 81 | # print(f"! {name}") 82 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Exercise/12. SoftUni Exam Results.py: -------------------------------------------------------------------------------- 1 | school = {"Submissions": {}} 2 | 3 | command = input() 4 | while command != "exam finished": 5 | if "banned" in command.split("-"): 6 | del school[username] 7 | else: 8 | username, language, points = [int(x) if x.isdigit() else x for x in command.split("-")] 9 | school["Submissions"][language] = school["Submissions"].get(language, 0) 10 | school["Submissions"][language] += 1 11 | school[username] = school.get(username, {}) 12 | school[username][language] = school[username].get(language, points) 13 | if school[username][language] < points: 14 | school[username][language] = points 15 | 16 | command = input() 17 | 18 | print("Results:") 19 | for user in school: 20 | if user != "Submissions": 21 | for k, v in school[user].items(): 22 | print(f"{user} | {v}") 23 | print("Submissions:") 24 | for lang, count in school["Submissions"].items(): 25 | print(f"{lang} - {count}") 26 | 27 | 28 | 29 | 30 | 31 | # 32 | # 33 | # user_command = input() 34 | # student_information = {} 35 | # ban_user_list = [] 36 | # submissions = "Submissions" 37 | # 38 | # 39 | # def ban_user(name): 40 | # ban_user_list.append(name) 41 | # 42 | # 43 | # def add_user(name, lang, score): 44 | # student_information[lang] = student_information.get(lang, {}) 45 | # student_information[lang][name] = student_information[lang].get(name, 0) 46 | # student_information[lang][submissions] = student_information[lang].get(submissions, 0) 47 | # if student_information[lang][name] < score: 48 | # student_information[lang][name] = score 49 | # student_information[lang][submissions] += 1 50 | # 51 | # 52 | # def show_result(): 53 | # global submissions 54 | # print("Results:") 55 | # for key in student_information: 56 | # for name, score in student_information[key].items(): 57 | # if all([name not in ban_user_list, submissions not in name]): 58 | # print(f"{name} | {score}") 59 | # print(f"{submissions}:") 60 | # for key in student_information: 61 | # if student_information[key]: 62 | # # if len(student_information[key]) > 0: 63 | # print(f"{key} - {student_information[key][submissions]}") 64 | # 65 | # 66 | # while user_command != "exam finished": 67 | # user_command = user_command.split("-") 68 | # if user_command[-1] == "banned": 69 | # ban_user(user_command[0]) 70 | # else: 71 | # add_user(user_command[0], user_command[1], int(user_command[-1])) 72 | # user_command = input() 73 | # 74 | # show_result() 75 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/01. Bakery.py: -------------------------------------------------------------------------------- 1 | food_type = input().split() 2 | 3 | food_info_dic = dict() 4 | i = 0 5 | for string in food_type: 6 | if i % 2 == 0: 7 | food_info_dic[string] = 0 8 | name = string 9 | if i % 2 != 0: 10 | food_info_dic[name] = int(string) 11 | name = "" 12 | i += 1 13 | 14 | 15 | # for i in range(0, len(food_type), 2): 16 | # food_info_dic[food_type[i]] = int(food_type[(i + 1)]) 17 | 18 | 19 | print(food_info_dic) 20 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/02. Stock.py: -------------------------------------------------------------------------------- 1 | food_type = input().split() 2 | searching_for_food = input().split() 3 | food_info_dic = dict() 4 | i = 0 5 | for string in food_type: 6 | if i % 2 == 0: 7 | food_info_dic[string] = 0 8 | name = string 9 | if i % 2 != 0: 10 | food_info_dic[name] = int(string) 11 | name = "" 12 | i += 1 13 | 14 | for product in searching_for_food: 15 | if product in food_info_dic: 16 | print(f"We have {food_info_dic[product]} of {product} left") 17 | else: 18 | print(f"Sorry, we don't have {product}") -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/03 Statistics.py: -------------------------------------------------------------------------------- 1 | product_input = input() 2 | food_info_dic = dict() 3 | while product_input != "statistics": 4 | food_type = product_input.split(": ") 5 | if food_type[0] not in food_info_dic: 6 | food_info_dic[food_type[0]] = 0 7 | food_info_dic[food_type[0]] = food_info_dic[food_type[0]] + int(food_type[-1]) 8 | product_input = input() 9 | 10 | 11 | def showing_products(dictionary): 12 | print("Products in stock:") 13 | total_products = 0 14 | total_quantity = 0 15 | for key, value in dictionary.items(): 16 | print(f"- {key}: {value}") 17 | total_products += 1 18 | total_quantity += value 19 | print(f"Total Products: {total_products}") 20 | print(f"Total Quantity: {total_quantity}") 21 | 22 | 23 | showing_products(food_info_dic) 24 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/04. Students.py: -------------------------------------------------------------------------------- 1 | student_information = input() 2 | 3 | student_dic = dict() 4 | 5 | while not student_dic.get(student_information): 6 | student_information = student_information.split(":") 7 | name_student = student_information[0] 8 | id_student = student_information[1] 9 | couse_student = student_information[-1] 10 | if couse_student not in student_dic: 11 | student_dic[couse_student] = {} 12 | student_dic[couse_student][name_student] = id_student 13 | student_information = input() 14 | student_information = student_information.replace("_", " ") 15 | 16 | for key, value in student_dic[student_information].items(): 17 | print(f"{key} - {value}") 18 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/05. ASCII Values.py: -------------------------------------------------------------------------------- 1 | list_of_characters = input().split(", ") 2 | 3 | letter_dic = {} 4 | 5 | for letter in list_of_characters: 6 | letter_dic[letter] = ord(letter) 7 | 8 | print(letter_dic) 9 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/06. Odd Occurrences.py: -------------------------------------------------------------------------------- 1 | elements = input().lower().split() 2 | 3 | # split_elements = elements.split() 4 | # check_element = list() 5 | # for element in split_elements: 6 | # count = split_elements.count(element) 7 | # if count % 2 != 0 and element not in check_element: 8 | # print(element, end= " ") 9 | # check_element.append(element) 10 | 11 | elements_dic = dict() 12 | 13 | for character in elements: 14 | if character not in elements_dic: 15 | elements_dic[character] = 0 16 | elements_dic[character] += 1 17 | 18 | for key, value in elements_dic.items(): 19 | if value % 2 != 0: 20 | print(key, end= " ") 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - Lab/07. Word Synonyms.py: -------------------------------------------------------------------------------- 1 | number_words = int(input()) 2 | 3 | 4 | synonyms = {} 5 | for _ in range(number_words): 6 | word_one = input() 7 | word_two = input() 8 | if word_one not in synonyms: 9 | synonyms[word_one] = list() 10 | synonyms[word_one].append(word_two) 11 | else: 12 | synonyms[word_one].append(word_two) 13 | 14 | for key, value in synonyms.items(): 15 | print(f"{key} - ", end="") 16 | print(*value, sep=", ") 17 | 18 | 19 | # for word in synonyms: 20 | # print(f"{word} - {', '. join(synonyms[word])}") -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - More Exercise/01. Ranking.py: -------------------------------------------------------------------------------- 1 | contests, users = {}, {} 2 | contest_data = input() 3 | 4 | while contest_data != "end of contests": 5 | contest, password = contest_data.split(":") 6 | contests[contest] = password 7 | contest_data = input() 8 | 9 | submission_data = input() 10 | 11 | while submission_data != "end of submissions": 12 | contest, password, username, points = [int(x) if x.isdigit() else x for x in submission_data.split("=>")] 13 | if contests.get(contest) == password: 14 | users[username] = users.get(username, {}) 15 | users[username][contest] = users[username].get(contest, 0) 16 | if users[username][contest] < points: 17 | users[username][contest] = points 18 | submission_data = input() 19 | 20 | 21 | candidates = {name: sum(users[name].values()) for name in users} 22 | best_candidate = max(candidates, key=candidates.get) 23 | print(f"Best candidate is {best_candidate} with total {candidates[best_candidate]} points." 24 | f"\nRanking:") 25 | 26 | for name in sorted(users): 27 | print(name) 28 | for contest, points in sorted(users[name].items(), key=lambda item: -item[1]): 29 | print(f"# {contest} -> {points}") 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | # 40 | # 41 | # contest_add = input() 42 | # 43 | # exams_information = {"contest": {}, "students": {}} 44 | # contest_d, students_d = "contest", "students" 45 | # 46 | # while contest_add != "end of contests": 47 | # contest, contest_pass = contest_add.split(":") 48 | # exams_information[contest_d][contest] = contest_pass 49 | # contest_add = input() 50 | # 51 | # submissions = input() 52 | # while submissions != "end of submissions": 53 | # contest, contest_pass, contest_user, contest_points = [int(x) if x.isdigit() else x for x in submissions.split("=>")] 54 | # if contest in exams_information[contest_d] and exams_information[contest_d][contest] == contest_pass: 55 | # exams_information[students_d][contest_user] = exams_information[students_d].get(contest_user, {}) 56 | # exams_information[students_d][contest_user][contest] = exams_information[students_d][contest_user].get(contest, 0) 57 | # if exams_information[students_d][contest_user][contest] < contest_points: 58 | # exams_information[students_d][contest_user][contest] = contest_points 59 | # submissions = input() 60 | # 61 | # 62 | # def show_result(): 63 | # best_name = "" 64 | # total_points = 0 65 | # for name in exams_information[students_d]: 66 | # score_for_user = sum(exams_information[students_d][name].values()) 67 | # if score_for_user > total_points: 68 | # total_points = score_for_user 69 | # best_name = name 70 | # print(f"Best candidate is {best_name} with total {total_points} points.\nRanking:") 71 | # for name in sorted(exams_information[students_d]): 72 | # print(name) 73 | # for contest, points in sorted(exams_information[students_d][name].items(), key=lambda item: -item[1]): 74 | # print(f"# {contest} -> {points}") 75 | # 76 | # 77 | # show_result() 78 | # 79 | # 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | # 89 | # 90 | # contest_add = input() 91 | # 92 | # exams_information = {"contest": {}, "students": {}} 93 | # contest_d = "contest" 94 | # students_d = "students" 95 | # 96 | # while contest_add != "end of contests": 97 | # contest_add = contest_add.split(":") 98 | # contest = contest_add[0] 99 | # contest_pass = contest_add[-1] 100 | # exams_information[contest_d][contest] = contest_pass 101 | # contest_add = input() 102 | # 103 | # submissions = input() 104 | # while submissions != "end of submissions": 105 | # submissions = submissions.split("=>") 106 | # contest = submissions[0] 107 | # contest_pass = submissions[1] 108 | # contest_user = submissions[2] 109 | # contest_points = int(submissions[-1]) 110 | # if contest in exams_information[contest_d]: 111 | # if exams_information[contest_d][contest] == contest_pass: 112 | # if contest_user not in exams_information[students_d]: 113 | # exams_information[students_d][contest_user] = {} 114 | # if contest not in exams_information[students_d][contest_user]: 115 | # exams_information[students_d][contest_user][contest] = 0 116 | # if exams_information[students_d][contest_user][contest] < contest_points: 117 | # exams_information[students_d][contest_user][contest] = contest_points 118 | # submissions = input() 119 | # 120 | # 121 | # def show_result(): 122 | # best_name = "" 123 | # total_points = 0 124 | # for name in exams_information[students_d]: 125 | # score_for_user = sum(exams_information[students_d][name].values()) 126 | # if score_for_user > total_points: 127 | # total_points = score_for_user 128 | # best_name = name 129 | # print(f"Best candidate is {best_name} with total {total_points} points.\nRanking:") 130 | # for name in sorted(exams_information[students_d]): 131 | # print(name) 132 | # for contest, points in sorted(exams_information[students_d][name].items(), key=lambda item: -item[1]): 133 | # print(f"# {contest} -> {points}") 134 | # 135 | # 136 | # show_result() 137 | -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - More Exercise/02. Judge.py: -------------------------------------------------------------------------------- 1 | courses, individual = {}, {} 2 | data = input() 3 | while data != "no more time": 4 | 5 | name, course, score = [x if x.isalpha() else int(x) for x in data.split(" -> ")] 6 | courses[course] = courses.get(course, {}) 7 | courses[course][name] = courses[course].get(name, 0) 8 | if courses[course][name] < score: 9 | courses[course][name] = score 10 | data = input() 11 | 12 | for course in courses: 13 | print(f"{course}: {len(courses[course])} participants") 14 | for pos, (user, score) in enumerate(sorted(courses[course].items(), key= lambda x: (-x[1], x[0])), 1): 15 | print(f"{pos}. {user} <::> {score}") 16 | individual[user] = individual.get(user, 0) + score 17 | 18 | print("Individual standings:") 19 | for pos, (user, score) in enumerate(sorted(individual.items(), key=lambda x: (-x[1], x[0])), 1): 20 | print(f"{pos}. {user} -> {score}") 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | # 35 | # 36 | # command_judge = input() 37 | # 38 | # judge_info = {"user": {}, "contest": {}} 39 | # user_d = "user" 40 | # contest_d = "contest" 41 | # 42 | # while command_judge != "no more time": 43 | # user_name, contest, points = [int(x) if x.isdigit() else x for x in command_judge.split(" -> ")] 44 | # judge_info[contest_d][contest] = judge_info[contest_d].get(contest, {}) 45 | # judge_info[contest_d][contest][user_name] = judge_info[contest_d][contest].get(user_name, 0) 46 | # judge_info[user_d][user_name] = judge_info[user_d].get(user_name, 0) 47 | # if user_name in judge_info[user_d] and judge_info[user_d][user_name] == points: 48 | # judge_info[user_d][user_name] += points 49 | # if judge_info[contest_d][contest][user_name] < points: 50 | # judge_info[user_d][user_name] += points - judge_info[contest_d][contest][user_name] 51 | # judge_info[contest_d][contest][user_name] = points 52 | # 53 | # command_judge = input() 54 | # 55 | # 56 | # def show_result(): 57 | # for contest in judge_info[contest_d]: 58 | # print(f"{contest}: {len(judge_info[contest_d][contest])} participants") 59 | # for pos, (name, points) in enumerate( 60 | # sorted(judge_info[contest_d][contest].items(), key=lambda item: (-item[1], item[0])), 1): 61 | # print(f"{pos}. {name} <::> {points}") 62 | # print("Individual standings:") 63 | # for pos, (name, points) in enumerate(sorted(judge_info[user_d].items(), key=lambda item: (-item[1], item[0])), 1): 64 | # print(f"{pos}. {name} -> {points}") 65 | # 66 | # 67 | # show_result() 68 | # 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | # 77 | # 78 | # 79 | # command_judge = input() 80 | # 81 | # judge_info = {"user": {}, "contest": {}} 82 | # user_d = "user" 83 | # contest_d = "contest" 84 | # 85 | # while command_judge != "no more time": 86 | # command_judge = command_judge.split(" -> ") 87 | # user_name = command_judge[0] 88 | # contest = command_judge[1] 89 | # points = int(command_judge[-1]) 90 | # if contest not in judge_info[contest_d]: 91 | # judge_info[contest_d][contest] = {} 92 | # if user_name not in judge_info[contest_d][contest]: 93 | # judge_info[contest_d][contest][user_name] = 0 94 | # if user_name not in judge_info[user_d]: 95 | # judge_info[user_d][user_name] = 0 96 | # if user_name in judge_info[user_d] and judge_info[user_d][user_name] == points: 97 | # judge_info[user_d][user_name] += points 98 | # if judge_info[contest_d][contest][user_name] < points: 99 | # judge_info[user_d][user_name] += points - judge_info[contest_d][contest][user_name] 100 | # judge_info[contest_d][contest][user_name] = points 101 | # 102 | # command_judge = input() 103 | # 104 | # 105 | # def show_result(): 106 | # for contest in judge_info[contest_d]: 107 | # print(f"{contest}: {len(judge_info[contest_d][contest])} participants") 108 | # for pos, (name, points) in enumerate( 109 | # sorted(judge_info[contest_d][contest].items(), key=lambda item: (-item[1], item[0])), 1): 110 | # print(f"{pos}. {name} <::> {points}") 111 | # print("Individual standings:") 112 | # for pos, (name, points) in enumerate(sorted(judge_info[user_d].items(), key=lambda item: (-item[1], item[0])), 1): 113 | # print(f"{pos}. {name} -> {points}") 114 | # 115 | # 116 | # show_result() 117 | 118 | 119 | 120 | # contests = {} 121 | # users = {} 122 | # while True: 123 | # command = input() 124 | # if command == "no more time": 125 | # break 126 | # username, contest, points = command.split(" -> ") 127 | # if contest not in contests: 128 | # contests[contest] = {} 129 | # if username not in contests[contest]: 130 | # contests[contest][username] = 0 131 | # if contests[contest][username] < int(points): 132 | # contests[contest][username] = int(points) 133 | # for contest in contests.keys(): 134 | # print(f"{contest}: {len(contests[contest].keys())} participants") 135 | # for i, (username, points) in enumerate(sorted(contests[contest].items(), key=lambda x: (-x[1], x[0])), 1): 136 | # if username not in users: 137 | # users[username] = 0 138 | # users[username] += points 139 | # print(f"{i}. {username} <::> {points}") 140 | # print("Individual standings:") 141 | # for i, (key, value) in enumerate(sorted(users.items(), key=lambda x: (-x[1], x[0])), 1): 142 | # print(f"{i}. {key} -> {value}") 143 | # -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - More Exercise/03. MOBA Challenger.py: -------------------------------------------------------------------------------- 1 | command_input = input() 2 | 3 | player_info = {} 4 | best_players = [] 5 | 6 | 7 | def duel_players(name_one, name_two): 8 | if (name_one and name_two) in player_info: 9 | for p_one in player_info[name_one]: 10 | if p_one in player_info[name_two]: 11 | total_pl_one = sum(player_info[name_one].values()) 12 | total_pl_two = sum(player_info[name_two].values()) 13 | if total_pl_one > total_pl_two: 14 | del player_info[name_two] 15 | elif total_pl_one < total_pl_two: 16 | del player_info[name_one] 17 | break 18 | 19 | 20 | def adding_players_roles(player, position, skill): 21 | if player not in player_info: 22 | player_info[player] = {} 23 | if position not in player_info[player]: 24 | player_info[player][position] = 0 25 | if player_info[player][position] < skill: 26 | player_info[player][position] = skill 27 | 28 | 29 | while command_input != "Season end": 30 | if " vs " in command_input: 31 | command_input = command_input.split(" vs ") 32 | duel_players(command_input[0], command_input[-1]) 33 | else: 34 | command_input = command_input.split(" -> ") 35 | adding_players_roles(command_input[0], command_input[1], int(command_input[-1])) 36 | command_input = input() 37 | 38 | 39 | def show_result(): 40 | for p_name in player_info: 41 | best_players.append({"name": p_name, "total_score": sum(player_info[p_name].values())}) 42 | for show in sorted(best_players, key=lambda item: (-item["total_score"], item["name"])): 43 | print(f"{show['name']}: {show['total_score']} skill") 44 | for pos, skill in sorted(player_info[show['name']].items(), key=lambda item: (-item[1], item[0])): 45 | print(f"- {pos} <::> {skill}") 46 | 47 | 48 | show_result() 49 | 50 | 51 | 52 | 53 | # pool = {} 54 | # 55 | # command = input() 56 | # while command != 'Season end': 57 | # if "->" in command: 58 | # name, skill, points = [int(i) if i.isdigit() else i for i in command.split(" -> ")] 59 | # if name not in pool: 60 | # pool[name] = {skill: points} 61 | # elif name in pool and skill not in pool[name]: 62 | # pool[name][skill] = points 63 | # elif name in pool and skill in pool[name]: 64 | # if pool[name][skill] < points: 65 | # pool[name][skill] = points 66 | # 67 | # else: 68 | # player1, player2 = command.split(" vs ") 69 | # if player1 in pool and player2 in pool: 70 | # for position, points in pool[player1].items(): 71 | # if position in pool[player2].keys(): 72 | # if points < pool[player2][position]: 73 | # del pool[player1] 74 | # elif pool[player2][position] < pool[player1][position]: 75 | # del pool[player2] 76 | # break 77 | # 78 | # 79 | # command = input() 80 | # 81 | # # total points generating and sorting 82 | # total_points = {} 83 | # for name in pool.keys(): 84 | # for v in pool[name].values(): 85 | # if name not in total_points: 86 | # total_points[name] = 0 87 | # total_points[name] += v 88 | # total_points = dict(sorted(total_points.items(), key=lambda x: (-x[1], x[0]))) 89 | # 90 | # # inside points sorting 91 | # for name in pool.keys(): 92 | # for k, v in pool[name].items(): 93 | # pool[name] = dict(sorted(pool[name].items(), key=lambda x: (-x[1], x[0]))) 94 | # 95 | # for name, totalpoints in total_points.items(): 96 | # print(f"{name}: {totalpoints} skill") 97 | # for k, v in pool[name].items(): 98 | # print(f"- {k} <::> {v}") -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - More Exercise/04. Snow White.py: -------------------------------------------------------------------------------- 1 | dwarf_input = input() 2 | 3 | dwarf_info = {} 4 | result_list = [] 5 | name_d = "name" 6 | hat_d = "hat" 7 | physic_d = "physic" 8 | hat_len = "hat len" 9 | while dwarf_input != "Once upon a time": 10 | dwarf_input = dwarf_input.split(" <:> ") 11 | dwarf_name = dwarf_input[0] 12 | dwarf_hat_color = dwarf_input[1] 13 | dwarf_physics = int(dwarf_input[-1]) 14 | if dwarf_hat_color not in dwarf_info: 15 | dwarf_info[dwarf_hat_color] = {} 16 | if dwarf_name not in dwarf_info[dwarf_hat_color]: 17 | dwarf_info[dwarf_hat_color][dwarf_name] = 0 18 | if dwarf_info[dwarf_hat_color][dwarf_name] < dwarf_physics: 19 | dwarf_info[dwarf_hat_color][dwarf_name] = dwarf_physics 20 | dwarf_input = input() 21 | 22 | 23 | def show_result(): 24 | for hat in dwarf_info: 25 | for name, physic in dwarf_info[hat].items(): 26 | result_list.append({hat_len: len(dwarf_info[hat]), name_d: name, physic_d: physic, hat_d: hat}) 27 | for show in sorted(result_list, key=lambda item: (-item[physic_d], -item[hat_len])): 28 | print(f"({show[hat_d]}) {show[name_d]} <-> {show[physic_d]}") 29 | 30 | 31 | show_result() -------------------------------------------------------------------------------- /07. Dictionaries/07. Dictionaries - More Exercise/05. Dragon Army.py: -------------------------------------------------------------------------------- 1 | dragons = int(input()) 2 | 3 | dragon_information = {} 4 | damage_d, health_d, armor_d = "damage", "health", "armor" 5 | 6 | 7 | def create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor): 8 | dragon_information[dragon_type] = dragon_information.get(dragon_type, dict()) 9 | dragon_information[dragon_type][dragon_name] = dragon_information.get(dragon_name, dict()) 10 | dragon_information[dragon_type][dragon_name][damage_d] = dragon_damage 11 | dragon_information[dragon_type][dragon_name][health_d] = dragon_health 12 | dragon_information[dragon_type][dragon_name][armor_d] = dragon_armor 13 | 14 | 15 | def show_result(): 16 | for color in dragon_information: 17 | damage, health, armor = 0, 0, 0 18 | for name in dragon_information[color]: 19 | damage += dragon_information[color][name][damage_d] 20 | health += dragon_information[color][name][health_d] 21 | armor += dragon_information[color][name][armor_d] 22 | total_dragons = len(dragon_information[color]) 23 | print(f"{color}::({(damage / total_dragons):.2f}/{(health / total_dragons):.2f}/{(armor / total_dragons):.2f})") 24 | for name in sorted(dragon_information[color].keys()): 25 | print( 26 | f"-{name} -> damage: {dragon_information[color][name][damage_d]}, health: {dragon_information[color][name][health_d]}, armor: {dragon_information[color][name][armor_d]}") 27 | 28 | 29 | for _ in range(dragons): 30 | dragon_type, dragon_name, damage, health, armor = input().split() 31 | if damage == "null": 32 | dragon_damage = 45 33 | else: 34 | dragon_damage = int(damage) 35 | if health == "null": 36 | dragon_health = 250 37 | else: 38 | dragon_health = int(health) 39 | if armor == "null": 40 | dragon_armor = 10 41 | else: 42 | dragon_armor = int(armor) 43 | create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor) 44 | 45 | show_result() 46 | 47 | 48 | 49 | 50 | 51 | # number_of_dragons = int(input()) 52 | # dragons_by_colours = {} 53 | # 54 | # for _ in range(number_of_dragons): 55 | # colour, name, damage, health, armor = (int(x) if x.isdigit() else x for x in input().split()) 56 | # dragons_by_colours[colour] = dragons_by_colours.get(colour, {}) 57 | # dragons_by_colours[colour][name] = (45 if damage == "null" else damage, 58 | # 250 if health == "null" else health, 59 | # 10 if armor == "null" else armor) 60 | # 61 | # average_per_colour = {} 62 | # for colour, name in dragons_by_colours.items(): 63 | # avg_for_color = [] 64 | # for dragon, info in name.items(): 65 | # avg_for_color.append(info) 66 | # avg_result = [sum(i) / len(avg_for_color) for i in zip(*avg_for_color)] 67 | # average_per_colour[colour] = avg_result 68 | # 69 | # sorted_dictionary = {k: {x: y for x, y in sorted(v.items())} for k, v in dragons_by_colours.items()} 70 | # 71 | # for colour, data in average_per_colour.items(): 72 | # print(f"{colour}::({'/'.join(f'{x:.2f}' for x in data)})") 73 | # for name, data in sorted_dictionary[colour].items(): 74 | # print(f"-{name} -> {', '.join(f'{x}: {y}' for x, y in zip(('damage', 'health', 'armor'), data))}") 75 | 76 | 77 | 78 | 79 | # number_of_dragons = int(input()) 80 | # dragons_by_colours = {} 81 | # 82 | # for _ in range(number_of_dragons): 83 | # colour, name, damage, health, armor = input().split() 84 | # if colour not in dragons_by_colours: 85 | # dragons_by_colours[colour] = {} 86 | # if damage == "null": 87 | # dragon_damage = 45 88 | # else: 89 | # dragon_damage = int(damage) 90 | # if health == "null": 91 | # dragon_health = 250 92 | # else: 93 | # dragon_health = int(health) 94 | # if armor == "null": 95 | # dragon_armor = 10 96 | # else: 97 | # dragon_armor = int(armor) 98 | # dragons_by_colours[colour][name] = [dragon_damage, dragon_health, dragon_armor] 99 | # 100 | # average_per_colour = {} 101 | # for colour, name in dragons_by_colours.items(): 102 | # avg_for_colour = [] 103 | # for dragon, info in name.items(): 104 | # if len(name) > 1: 105 | # avg_for_colour.append(info) 106 | # else: 107 | # avg_for_colour.append(info) 108 | # avg_result = [sum(i) / len(avg_for_colour) for i in zip(*avg_for_colour)] 109 | # average_per_colour[colour] = avg_result 110 | # 111 | # sorted_dictionary = {k: {x: y for x, y in sorted(v.items())} for k, v in dragons_by_colours.items()} 112 | # 113 | # for colour, average in average_per_colour.items(): 114 | # print(f"{colour}::({average[0]:.2f}/{average[1]:.2f}/{average[2]:.2f})") 115 | # for name, info in sorted_dictionary[colour].items(): 116 | # print(f"-{name} -> damage: {info[0]}, health: {info[1]}, armor: {info[2]}") 117 | # 118 | 119 | 120 | 121 | 122 | # 123 | # dragons = int(input()) 124 | # 125 | # dragon_information = {} 126 | # damage_d = "damage" 127 | # health_d = "health" 128 | # armor_d = "armor" 129 | # 130 | # 131 | # def create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor): 132 | # if dragon_type not in dragon_information: 133 | # dragon_information[dragon_type] = {} 134 | # if dragon_name not in dragon_information[dragon_type]: 135 | # dragon_information[dragon_type][dragon_name] = {} 136 | # dragon_information[dragon_type][dragon_name][damage_d] = dragon_damage 137 | # dragon_information[dragon_type][dragon_name][health_d] = dragon_health 138 | # dragon_information[dragon_type][dragon_name][armor_d] = dragon_armor 139 | # 140 | # 141 | # def show_result(): 142 | # for color in dragon_information: 143 | # damage = 0 144 | # health = 0 145 | # armor = 0 146 | # for name in dragon_information[color]: 147 | # damage += dragon_information[color][name][damage_d] 148 | # health += dragon_information[color][name][health_d] 149 | # armor += dragon_information[color][name][armor_d] 150 | # total_dragons = len(dragon_information[color]) 151 | # print(f"{color}::({(damage / total_dragons):.2f}/{(health / total_dragons):.2f}/{(armor / total_dragons):.2f})") 152 | # for name in sorted(dragon_information[color].keys()): 153 | # print( 154 | # f"-{name} -> damage: {dragon_information[color][name][damage_d]}, health: {dragon_information[color][name][health_d]}, armor: {dragon_information[color][name][armor_d]}") 155 | # 156 | # 157 | # for _ in range(dragons): 158 | # command = input() 159 | # command = command.split() 160 | # dragon_type = command[0] 161 | # dragon_name = command[1] 162 | # if (command[2]) == "null": 163 | # dragon_damage = 45 164 | # else: 165 | # dragon_damage = int(command[2]) 166 | # if (command[3]) == "null": 167 | # dragon_health = 250 168 | # else: 169 | # dragon_health = int(command[3]) 170 | # if (command[4]) == "null": 171 | # dragon_armor = 10 172 | # else: 173 | # dragon_armor = int(command[4]) 174 | # 175 | # create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor) 176 | # 177 | # show_result() 178 | 179 | 180 | 181 | # 182 | # dragons = int(input()) 183 | # 184 | # dragon_information = {} 185 | # 186 | # 187 | # def create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor): 188 | # if dragon_type not in dragon_information: 189 | # dragon_information[dragon_type] = {} 190 | # if dragon_name not in dragon_information[dragon_type]: 191 | # dragon_information[dragon_type][dragon_name] = {} 192 | # dragon_information[dragon_type][dragon_name]["damage"] = dragon_damage 193 | # dragon_information[dragon_type][dragon_name]["health"] = dragon_health 194 | # dragon_information[dragon_type][dragon_name]["armor"] = dragon_armor 195 | # dragon_information[dragon_type][dragon_name]["damage"] = dragon_damage 196 | # dragon_information[dragon_type][dragon_name]["health"] = dragon_health 197 | # dragon_information[dragon_type][dragon_name]["armor"] = dragon_armor 198 | # 199 | # 200 | # def show_result(): 201 | # damage_d = "damage" 202 | # health_d = "health" 203 | # armor_d = "armor" 204 | # for color in dragon_information: 205 | # i = 0 206 | # damage = 0 207 | # health = 0 208 | # armor = 0 209 | # for name in dragon_information[color]: 210 | # damage += dragon_information[color][name]["damage"] 211 | # health += dragon_information[color][name]["health"] 212 | # armor += dragon_information[color][name]["armor"] 213 | # i += 1 214 | # print(f"{color}::({(damage / i):.2f}/{(health / i):.2f}/{(armor / i):.2f})") 215 | # for name in sorted(dragon_information[color].keys()): 216 | # print( 217 | # f"-{name} -> damage: {dragon_information[color][name][damage_d]}, health: {dragon_information[color][name][health_d]}, armor: {dragon_information[color][name][armor_d]}") 218 | # 219 | # 220 | # for _ in range(dragons): 221 | # command = input() 222 | # command = command.split() 223 | # dragon_type = command[0] 224 | # dragon_name = command[1] 225 | # if (command[2]) == "null": 226 | # dragon_damage = 45 227 | # else: 228 | # dragon_damage = int(command[2]) 229 | # if (command[3]) == "null": 230 | # dragon_health = 250 231 | # else: 232 | # dragon_health = int(command[3]) 233 | # if (command[4]) == "null": 234 | # dragon_armor = 10 235 | # else: 236 | # dragon_armor = int(command[4]) 237 | # 238 | # create_dragon(dragon_type, dragon_name, dragon_damage, dragon_health, dragon_armor) 239 | # 240 | # 241 | # show_result() 242 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/01. Valid Usernames.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | usernames = input().split(", ") 4 | for username in usernames: 5 | if 3 <= len(username) <= 16: 6 | for char in username: 7 | if char not in "-_" + string.ascii_letters + string.digits: 8 | break 9 | 10 | else: 11 | print(username) 12 | 13 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/02. Character Multiplier.py: -------------------------------------------------------------------------------- 1 | first_string, second_string = input().split() 2 | 3 | first_string = [ord(num) for num in first_string] 4 | second_string = [ord(num) for num in second_string] 5 | first_string_len = len(first_string) 6 | second_string_len = len(second_string) 7 | if first_string_len > second_string_len: 8 | for _ in range(first_string_len - second_string_len): 9 | second_string.append(1) 10 | elif first_string_len < second_string_len: 11 | for _ in range(second_string_len - first_string_len): 12 | first_string.append(1) 13 | print(sum([first_string[i] * second_string[i] for i in range(len(first_string))])) 14 | 15 | 16 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/03. Extract File.py: -------------------------------------------------------------------------------- 1 | file_name = input().split(".") 2 | 3 | file = file_name[0].split("\\") 4 | print(f"File name: {file[-1]}") 5 | print(f"File extension: {file_name[1]}") 6 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/04. Caesar Cipher.py: -------------------------------------------------------------------------------- 1 | print("".join([chr(ord(letter) + 3) for letter in input()])) 2 | 3 | 4 | # main_text = input() 5 | # result = "" 6 | # for letter in main_text: 7 | # cripted_letter = ord(letter) 8 | # result += chr(cripted_letter + 3) 9 | # 10 | # print(result) -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/05. Emoticon Finder.py: -------------------------------------------------------------------------------- 1 | main_text = input() 2 | 3 | for index, letter in enumerate(main_text): 4 | if ":" == letter: 5 | print(f"{letter}{main_text[index+1]}") -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/06. Replace Repeating Chars.py: -------------------------------------------------------------------------------- 1 | main_string = input() 2 | 3 | 4 | for pos, letter in enumerate(range(len(main_string) - 1), 1): 5 | if main_string[letter] != main_string[pos]: 6 | print(main_string[letter], end="") 7 | 8 | print(main_string[-1]) 9 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/07. String Explosion.py: -------------------------------------------------------------------------------- 1 | main_string = input().split(">") 2 | 3 | show_result = "" 4 | what_left = 0 5 | for letter in main_string: 6 | if len(letter) > 1 and any(map(str.isdigit, letter)): 7 | what_left += (int(letter[0]) - 1) 8 | if what_left >= len(letter): 9 | show_result += ">" 10 | else: 11 | show_result += ">" + letter[1 + what_left:] 12 | what_left = 0 13 | elif len(letter) == 1 and letter.isdigit(): 14 | if int(letter) > 1: 15 | what_left += (int(letter) - 1) 16 | show_result += ">" 17 | else: 18 | show_result += letter 19 | 20 | print(show_result) 21 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/08. Letters Change Numbers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = re.sub("\s+", " ", input()).split() 4 | total = 0 5 | for string in main_string: 6 | numbers = int(string[1:-1]) 7 | if string[0].isupper(): 8 | first_result = numbers / ((ord(string[0].lower())) - 96) 9 | else: 10 | first_result = numbers * ((ord(string[0].lower())) - 96) 11 | 12 | if string[-1].isupper(): 13 | second_result = first_result - ((ord(string[-1].lower())) - 96) 14 | else: 15 | second_result = first_result + ((ord(string[-1].lower())) - 96) 16 | total += second_result 17 | 18 | print(f"{total:.2f}") 19 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/09. Rage Quit.py: -------------------------------------------------------------------------------- 1 | main_string = input() 2 | 3 | current_result, result_show, number = "", "", "", 4 | 5 | for index, symbols in enumerate(main_string): 6 | if not symbols.isdigit(): 7 | current_result += symbols 8 | elif symbols.isdigit(): 9 | number += symbols 10 | if index + 1 < len(main_string): 11 | if main_string[index + 1].isdigit(): 12 | continue 13 | result_show += int(number) * current_result 14 | current_result, number = "", "" 15 | 16 | result_show = result_show.upper() 17 | print(f"Unique symbols used: {len(set(result_show))}") 18 | print(result_show) 19 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Exercise/10. Winning Ticket.py: -------------------------------------------------------------------------------- 1 | 2 | tickets = input().split(", ") 3 | symbols = ('@', '#', '$', '^') 4 | correct_ticket_len = 10 5 | 6 | 7 | 8 | def find_most_symbols(ticket): 9 | return max({s: ticket.count(s) for s in symbols}.items(), key=lambda x: x[1])[0] 10 | 11 | def find_most_in_a_row(ticket, symbol): 12 | return max([len(run) for run in "".join([symbol if char == symbol else " " for char in ticket]).split()] or [0]) 13 | 14 | for ticket in tickets: 15 | ticket = ticket.strip() 16 | 17 | if len(ticket) != 20: 18 | print("invalid ticket") 19 | continue 20 | 21 | type_symbol = find_most_symbols(ticket[:correct_ticket_len]) 22 | winnings = min([find_most_in_a_row(ticket[:correct_ticket_len], type_symbol), 23 | find_most_in_a_row(ticket[correct_ticket_len:], type_symbol)]) 24 | 25 | if winnings == 10: 26 | print(f'ticket "{ticket}" - 10{type_symbol} Jackpot!') 27 | 28 | elif winnings >= 6: 29 | print(f'ticket "{ticket}" - {winnings}{type_symbol}') 30 | 31 | else: 32 | print(f'ticket "{ticket}" - no match') 33 | 34 | 35 | 36 | 37 | # tickets_sting = input().split(", ") 38 | # symbols = ['@', '#', '$', '^'] 39 | # 40 | # 41 | # def get_max_in_a_row(string, symbol): 42 | # next_, current = 0, 0 43 | # for x in range(len(string)): 44 | # if string[x] == symbol: 45 | # next_ += 1 46 | # if x == len(string) - 1: 47 | # if current < next_: 48 | # current = next_ 49 | # else: 50 | # if current < next_: 51 | # current = next_ 52 | # next_ = 0 53 | # return current 54 | # 55 | # 56 | # for ticket_characters in tickets_sting: 57 | # ticket_characters = ticket_characters.replace(" ", "") 58 | # if len(ticket_characters) == 20: 59 | # how_long = int(len(ticket_characters) / 2) 60 | # left_side, right_side = ticket_characters[:how_long], ticket_characters[how_long:] 61 | # for symbol in symbols: 62 | # sum_of_l, sum_of_r = get_max_in_a_row(left_side, symbol), get_max_in_a_row(right_side, symbol) 63 | # if sum_of_l == sum_of_r == 10: 64 | # print(f'ticket "{ticket_characters}" - 10{symbol} Jackpot!') 65 | # break 66 | # winners_price = min(sum_of_l, sum_of_r) 67 | # if winners_price >= 6: 68 | # print(f'ticket "{ticket_characters}" - {winners_price}{symbol}') 69 | # break 70 | # else: 71 | # print(f'ticket "{ticket_characters}" - no match') 72 | # else: 73 | # print("invalid ticket") 74 | 75 | 76 | 77 | 78 | 79 | # 80 | # 81 | # import re 82 | # 83 | # 84 | # tickets_sting = input().split(", ") 85 | # symbols = ['@', '#', '$', '^'] 86 | # 87 | # 88 | # for ticket_characters in tickets_sting: 89 | # ticket_characters = ticket_characters.replace(" ", "") 90 | # if len(ticket_characters) == 20: 91 | # how_long = int(len(ticket_characters) / 2) 92 | # left_side, right_side = ticket_characters[:how_long], ticket_characters[how_long:] 93 | # for symbol in symbols: 94 | # opz = f"\{symbol}+" 95 | # try: 96 | # l_occurs = max(len(i) for i in re.findall(opz, left_side)) 97 | # r_occurs = max(len(i) for i in re.findall(opz, right_side)) 98 | # except ValueError: 99 | # continue 100 | # if l_occurs == r_occurs == 10: 101 | # print(f'ticket "{ticket_characters}" - {l_occurs}{symbol} Jackpot!') 102 | # break 103 | # winners_price = min(l_occurs, r_occurs) 104 | # if winners_price >= 6: 105 | # print(f'ticket "{ticket_characters}" - {winners_price}{symbol}') 106 | # break 107 | # else: 108 | # print(f'ticket "{ticket_characters}" - no match') 109 | # else: 110 | # print("invalid ticket") 111 | # 112 | # 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | # tickets_sting = input().split(", ") 121 | # 122 | # symbols = ['@', '#', '$', '^'] 123 | # 124 | # 125 | # def check_next(symbol, first, second): 126 | # back = 6 127 | # for i in range(7, 11): 128 | # if (i * symbol) in first and (i * symbol) in second: 129 | # back += 1 130 | # return back 131 | # 132 | # 133 | # for ticket_characters in tickets_sting: 134 | # price_find = False 135 | # jackpot_find = False 136 | # ticket_characters = ticket_characters.replace(" ", "") 137 | # if len(ticket_characters) == 20: 138 | # how_long = int(len(ticket_characters) / 2) 139 | # left_side = ticket_characters[:how_long] 140 | # right_side = ticket_characters[how_long:] 141 | # for index, symbol in enumerate(symbols): 142 | # if 10 * symbol in left_side and 10 * symbol in right_side: 143 | # print(f'ticket "{ticket_characters}" - 10{symbols[index]} Jackpot!') 144 | # jackpot_find = True 145 | # break 146 | # elif 6 * symbol in left_side and 6 * symbol in right_side: 147 | # symbol_type = symbols[index] 148 | # total = check_next(symbol_type, left_side, right_side) 149 | # price_find = True 150 | # break 151 | # if price_find: 152 | # print(f'ticket "{ticket_characters}" - {total}{symbol_type}') 153 | # elif not jackpot_find and not price_find: 154 | # print(f'ticket "{ticket_characters}" - no match') 155 | # else: 156 | # print("invalid ticket") 157 | 158 | 159 | 160 | 161 | # tickets = input().replace(" ", "") 162 | # tickets = tickets.split(',') 163 | # count = 0 164 | # symb = '' 165 | # symbols = ['@', '#', '$', '^'] 166 | # 167 | # for ticket in tickets: 168 | # fins_ticket = False 169 | # if len(ticket) != 20: 170 | # print('invalid ticket') 171 | # continue 172 | # left = ticket[:int(len(ticket) / 2)] 173 | # right = ticket[int(len(ticket) / 2):] 174 | # for index, sym in enumerate(symbols): 175 | # if 6 * sym in left and 6 * sym in right: 176 | # count = 0 177 | # for i in range(7, 11): 178 | # if (i * sym) in left and (i * sym) in right: 179 | # count += 1 180 | # symb = symbols[index] 181 | # fins_ticket = True 182 | # if not fins_ticket: 183 | # print(f'ticket "{ticket}" - no match') 184 | # elif count != 4: 185 | # print(f'ticket "{ticket}" - {6 + count}{symb}') 186 | # else: 187 | # print(f'ticket "{ticket}" - {6 + count}{symb} Jackpot!') 188 | 189 | 190 | 191 | # tickets = input().replace(" ", "") 192 | # tickets = tickets.split(',') 193 | # count = 0 194 | # symb = '' 195 | # symbols = ['@', '#', '$', '^'] 196 | # 197 | # def check_next(symbol, first, second): 198 | # back = 6 199 | # for i in range(7, 11): 200 | # if (i * symbol) in first and (i * symbol) in second: 201 | # back += 1 202 | # return back 203 | # 204 | # 205 | # for ticket in tickets: 206 | # fins_ticket =False 207 | # if len(ticket) != 20: 208 | # print('invalid ticket') 209 | # continue 210 | # left = ticket[0:int(len(ticket) / 2)] 211 | # right = ticket[int(len(ticket) / 2):] 212 | # for index, sym in enumerate(symbols): 213 | # if (6 * sym) in left and (6 * sym) in right: 214 | # count = check_next(sym, left, right) 215 | # symb = symbols[index] 216 | # fins_ticket = True 217 | # if not fins_ticket: 218 | # print(f'ticket "{ticket}" - no match') 219 | # elif count != 10: 220 | # print(f'ticket "{ticket}" - {count}{symb}') 221 | # else: 222 | # print(f'ticket "{ticket}" - {count}{symb} Jackpot!') -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Lab/01. Reverse Strings.py: -------------------------------------------------------------------------------- 1 | command = input() 2 | 3 | while command != "end": 4 | reverse = command[::-1] 5 | print(f"{command} = {reverse}") 6 | command = input() 7 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Lab/02. Repeat Strings.py: -------------------------------------------------------------------------------- 1 | string_input = input().split() 2 | 3 | for letters in string_input: 4 | repeated = len(letters) 5 | print(f"{repeated * letters}", end="") 6 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Lab/03. Substring.py: -------------------------------------------------------------------------------- 1 | string_one = input() 2 | string_two = input() 3 | 4 | while string_one in string_two: 5 | string_two = string_two.replace(string_one, "") 6 | 7 | print(string_two) 8 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Lab/04. Text Filter.py: -------------------------------------------------------------------------------- 1 | ban_list = input().split(", ") 2 | text = input() 3 | 4 | replace_symbol = "*" 5 | 6 | for ban_word in ban_list: 7 | word_len = len(ban_word) 8 | text = text.replace(ban_word, f"{word_len * replace_symbol}") 9 | print(text) 10 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - Lab/05. Digits, Letters and Other.py: -------------------------------------------------------------------------------- 1 | main_text = input() 2 | 3 | digits = "" 4 | letters = "" 5 | everything_other = "" 6 | for number in main_text: 7 | if number.isdigit(): 8 | digits += number 9 | elif number.isalpha(): 10 | letters += number 11 | else: 12 | everything_other += number 13 | 14 | print(digits) 15 | print(letters) 16 | print(everything_other) 17 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - More Exercise/01. Extract Person Information.py: -------------------------------------------------------------------------------- 1 | number_strings = int(input()) 2 | 3 | for _ in range(number_strings): 4 | test_string = input() 5 | # if all([test_string.count("@") == 1, test_string.count("|") == 1, 6 | # test_string.count("#") == 1, test_string.count("*") == 1]): 7 | name = test_string[test_string.index("@") + 1:test_string.index("|")] 8 | age = test_string[test_string.index("#") + 1:test_string.index("*")] 9 | print(f"{name} is {age} years old.") 10 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - More Exercise/02. ASCII Sumator.py: -------------------------------------------------------------------------------- 1 | start_char, end_char, random_string = input(), input(), input() 2 | 3 | print(sum([ord(char) for char in random_string if ord(start_char) < ord(char) < ord(end_char)])) 4 | 5 | 6 | 7 | 8 | 9 | # start_char, end_char, random_string = input(), input(), input() 10 | # 11 | # show_result = 0 12 | # for character in random_string: 13 | # if ord(start_char) < ord(character) < ord(end_char): 14 | # show_result += ord(character) 15 | # 16 | # print(show_result) 17 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - More Exercise/03. Treasure Finder.py: -------------------------------------------------------------------------------- 1 | secret_key = [int(x) for x in input().split()] 2 | secret_msg = input() 3 | 4 | how_long = len(secret_key) 5 | while secret_msg != "find": 6 | secret_text = "".join([chr(ord(secret_msg[i]) - secret_key[i % how_long]) for i in range(len(secret_msg))]) 7 | item = secret_text.split("&")[-2] 8 | location = secret_text.split("<")[-1][:-1] 9 | print(f"Found {item} at {location}") 10 | secret_msg = input() 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | # 19 | # 20 | # 21 | # 22 | # import re 23 | # secret_key = [int(x) for x in input().split()] 24 | # secret_msg = input() 25 | # 26 | # how_long = len(secret_key) 27 | # pattern = re.compile(r"&(.+)&.+<(.+)>") 28 | # while secret_msg != "find": 29 | # decode_msg = "" 30 | # index_key = 0 31 | # for x in secret_msg: 32 | # decode_msg += chr(ord(x) - secret_key[index_key]) 33 | # index_key += 1 34 | # if index_key >= how_long: 35 | # index_key = 0 36 | # matches = pattern.finditer(decode_msg) 37 | # for show in matches: 38 | # print(f"Found {show[1]} at {show[2]}") 39 | # secret_msg = input() 40 | 41 | 42 | 43 | # import re 44 | # secret_key = [int(x) for x in input().split()] 45 | # secret_msg = input() 46 | # 47 | # decode_msg = "" 48 | # how_long = len(secret_key) 49 | # pattern = re.compile(r"&(\w+)&.+<(.+)>") 50 | # while secret_msg != "find": 51 | # decode_msg = "" 52 | # start_ = 0 53 | # for x in secret_msg: 54 | # decode_msg += chr(ord(x) - secret_key[start_]) 55 | # start_ += 1 56 | # if start_ >= how_long: 57 | # start_ = 0 58 | # matches = pattern.finditer(decode_msg) 59 | # for show in matches: 60 | # print(f"Found {show[1]} at {show[2]}") 61 | # secret_msg = input() 62 | 63 | 64 | -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - More Exercise/04. Morse Code Translator.py: -------------------------------------------------------------------------------- 1 | morse_code_msg = input().split(" | ") 2 | 3 | morse_code_dic = {'..-.': 'F', '-..-': 'X', 4 | '.--.': 'P', '-': 'T', '..---': '2', 5 | '....-': '4', '-----': '0', '--...': '7', 6 | '...-': 'V', '-.-.': 'C', '.': 'E', '.---': 'J', 7 | '---': 'O', '-.-': 'K', '----.': '9', '..': 'I', 8 | '.-..': 'L', '.....': '5', '...--': '3', '-.--': 'Y', 9 | '-....': '6', '.--': 'W', '....': 'H', '-.': 'N', '.-.': 'R', 10 | '-...': 'B', '---..': '8', '--..': 'Z', '-..': 'D', '--.-': 'Q', 11 | '--.': 'G', '--': 'M', '..-': 'U', '.-': 'A', '...': 'S', '.----': '1'} 12 | 13 | show_result = "" 14 | 15 | for letter in morse_code_msg: 16 | for ltr in letter.split(" "): 17 | if ltr != '': 18 | show_result += morse_code_dic[ltr] 19 | show_result += " " 20 | 21 | print(show_result.upper()) 22 | 23 | 24 | # show_result = "" 25 | # 26 | # for letter in morse_code_msg: 27 | # find_letters = "" 28 | # for ltr in letter: 29 | # if ltr != " ": 30 | # find_letters += ltr 31 | # elif ltr == " " and find_letters != "": 32 | # show_result += morse_code_dic[find_letters] 33 | # find_letters = "" 34 | # if find_letters != "": 35 | # show_result += morse_code_dic[find_letters] + " " 36 | # print(show_result.upper()) -------------------------------------------------------------------------------- /08. Text Processing/08. Text Processing - More Exercise/05. HTML.py: -------------------------------------------------------------------------------- 1 | title_first_line = input() 2 | content_second_line = input() 3 | 4 | comments_enter = input() 5 | print(f"

\n {title_first_line}\n

") 6 | print(f"
\n {content_second_line}\n
") 7 | 8 | while comments_enter != "end of comments": 9 | print(f"
\n {comments_enter}\n
") 10 | comments_enter = input() 11 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/01. Capture the Numbers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | pattern = re.compile(r"\d+") 4 | while True: 5 | input_string = input() 6 | if input_string: 7 | matches = pattern.finditer(input_string) 8 | 9 | for show in matches: 10 | print(show[0], end=" ") 11 | else: 12 | break 13 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/02. Find Variable Names in Sentences.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input() 4 | 5 | patterns = re.compile(r"\b_(?P[A-Za-z0-9]+\b)") 6 | result = re.finditer(patterns, main_string) 7 | result_show = [] 8 | for show in result: 9 | result_show.append(show["word"]) 10 | 11 | print(','.join(result_show)) 12 | 13 | 14 | 15 | 16 | # 17 | # 18 | # 19 | # import re 20 | # 21 | # main_string = input() 22 | # pattern = re.compile(r"\b_([a-zA-Z0-9]+)\b") 23 | # matches = pattern.finditer(main_string) 24 | # show_result = [] 25 | # for show in matches: 26 | # show_result.append(show[1]) 27 | # 28 | # print(",".join(show_result)) -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/03. Find Occurrences of Word in Sentence.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input().lower() 4 | word_to_look_for = input().lower() 5 | 6 | patterns = re.compile(r"\b" + word_to_look_for + r"\b") 7 | print(len(list(re.finditer(patterns, main_string)))) 8 | 9 | 10 | 11 | 12 | 13 | # 14 | # import re 15 | # main_string = input().lower() 16 | # find_string = input().lower() 17 | # pattern = re.compile(r"\b"+find_string+r"\b") 18 | # matches = pattern.finditer(main_string) 19 | # show_result = 0 20 | # for show in matches: 21 | # show_result += 1 22 | # 23 | # print(show_result) 24 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/04. Extract Emails.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input() 4 | 5 | pattern = re.compile( 6 | r"(^|(?<=\s))([A-Za-z0-9])+([\.\-\_][A-Za-z0-9]+)*@([A-Za-z-]+)\.([A-Za-z-]+)([\.A-Za-z-])*(\b|(?=\s))") 7 | result = re.finditer(pattern, main_string) 8 | for show in result: 9 | print(show[0]) 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | # 19 | # 20 | # import re 21 | # input_string = input() 22 | # pattern = re.compile(r"(^|(?<=\s))(([a-zA-Z0-9]+)([\.\-_]?)([A-Za-z0-9]+)(@)([a-zA-Z]+([\.\-_][A-Za-z]+)+))(\b|(?=\s))") 23 | # matches = pattern.finditer(input_string) 24 | # 25 | # for show in matches: 26 | # print(show[0]) -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/05. Furniture.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input() 4 | 5 | pattern = re.compile( 6 | r">>(?P[A-Za-z]+)<<(?P[0-9]+[\.0-9]*)!(?P[0-9]+)") 7 | 8 | total_money_spend = 0 9 | print("Bought furniture:") 10 | while main_string != "Purchase": 11 | result = re.finditer(pattern, main_string) 12 | for show in result: 13 | total_money_spend += float(show["price"]) * float(show["quantity"]) 14 | print(show["furniture_name"]) 15 | main_string = input() 16 | 17 | print(f"Total money spend: {total_money_spend:.2f}") 18 | 19 | 20 | 21 | 22 | 23 | # 24 | # import re 25 | # 26 | # main_string = input() 27 | # pattern = re.compile(r">>(\w+)<<(\d+(\.\d+)?)!(\d+)") 28 | # names_list = [] 29 | # total_price = 0 30 | # 31 | # while main_string != "Purchase": 32 | # matches = pattern.finditer(main_string) 33 | # for show in matches: 34 | # names_list.append(show[1]) 35 | # total_price += (float(show[2]) * int(show[4])) 36 | # main_string = input() 37 | # 38 | # print("Bought furniture:") 39 | # if names_list: 40 | # # print("Bought furniture:") 41 | # for name in names_list: 42 | # print(name) 43 | # print(f"Total money spend: {total_price:.2f}") 44 | # 45 | # 46 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/06. Extract the Links.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | pattern = re.compile( 4 | r"www.([A-Za-z0-9\-]+)(\.[a-z]+)+") 5 | 6 | while True: 7 | main_string = input() 8 | if main_string: 9 | result = re.finditer(pattern, main_string) 10 | for show in result: 11 | print(show[0]) 12 | else: 13 | break 14 | 15 | 16 | 17 | 18 | 19 | 20 | # 21 | # 22 | # 23 | # import re 24 | # pattern = re.compile(r"\bwww\.[a-zA-Z0-9-]+\.[a-z]+(\.[a-z]+)*\b") 25 | # while True: 26 | # main_string = input() 27 | # if main_string: 28 | # matches = pattern.finditer(main_string) 29 | # for show in matches: 30 | # print(show[0]) 31 | # else: 32 | # break 33 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/10_stateless.py: -------------------------------------------------------------------------------- 1 | command_input = input() 2 | 3 | while command_input != "collapse": 4 | fiction = input() 5 | while fiction: 6 | command_input = command_input.replace(fiction, "") 7 | fiction = fiction[1:-1] 8 | if command_input: 9 | print(command_input) 10 | else: 11 | print("(void)") 12 | command_input = input() 13 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/11_pyramidic.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ip681/python-fundamentals/ed1233796ab0e2af87fe1e99a8ff0f7413e30cf9/09. Regular Expressions/09. Regular Expressions - Exercise/11_pyramidic.py -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/7_serialize_string.py: -------------------------------------------------------------------------------- 1 | main_string = input() 2 | banned_letters = [] 3 | for ltr in main_string: 4 | show_result = [] 5 | if ltr not in banned_letters: 6 | banned_letters.append(ltr) 7 | for pos in range(len(main_string)): 8 | if ltr == main_string[pos]: 9 | show_result.append(str(pos)) 10 | print(f"{ltr}:{'/'.join(show_result)}") 11 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/8_deserialize_string.py: -------------------------------------------------------------------------------- 1 | letters_input = input() 2 | 3 | added_letter = [] 4 | result = [] 5 | 6 | while letters_input != "end": 7 | added_letter.append(letters_input) 8 | for n in letters_input[2:].split("/"): 9 | result.append(n) 10 | letters_input = input() 11 | 12 | for info in added_letter: 13 | letter, pos = info.split(":") 14 | index_letters = pos.split("/") 15 | for ind in index_letters: 16 | result[int(ind)] = letter 17 | 18 | print("".join(result)) 19 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Exercise/9_string_commander.py: -------------------------------------------------------------------------------- 1 | main_string = input() 2 | 3 | commands_string = input() 4 | 5 | while commands_string != "end": 6 | if "Delete" in commands_string: 7 | _, star_index, end_index = commands_string.split() 8 | main_string = main_string[:int(star_index)] + main_string[int(end_index) + 1:] 9 | elif "Insert" in commands_string: 10 | _, star_index, word = commands_string.split() 11 | star_index = int(star_index) 12 | if len(main_string) == star_index: 13 | main_string += word 14 | else: 15 | main_string = word + main_string[star_index:] 16 | elif "Left" in commands_string: 17 | pass 18 | commands_string = input() 19 | 20 | print(main_string) -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Lab/01. Match Full Name.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | name_string = input() 4 | 5 | find_name = re.compile(r"(\b[A-Z][a-z]+ [A-Z][a-z]+\b)") 6 | match_find = re.findall(find_name, name_string) 7 | print(*match_find, sep= " ") 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | # import re 16 | # 17 | # main_string = input() 18 | # 19 | # patterns = re.compile(r"\b(?P[A-Z][a-z]{1,}) (?P[A-Z][a-z]{1,})\b") 20 | # list_result = list() 21 | # result = re.finditer(patterns, main_string) 22 | # 23 | # for show in result: 24 | # list_result.append(f"{show['word']} {show['word2']}") 25 | # 26 | # print(*list_result) 27 | # 28 | # 29 | 30 | 31 | 32 | 33 | 34 | # import re 35 | # 36 | # main_string = input() 37 | # 38 | # patterns = re.compile(r"\b(?P[A-Z][a-z]{1,}) (?P[A-Z][a-z]{1,})\b") 39 | # list_result = list() 40 | # result = re.finditer(patterns, main_string) 41 | # 42 | # for show in result: 43 | # list_result.append(f"{show['word']} {show['word2']}") 44 | # 45 | # print(*list_result) 46 | # 47 | # 48 | # 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Lab/02. Match Phone Number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input() 4 | 5 | patterns = re.compile(r"\+359([ -])2\1([0-9]{3})\1([0-9]{4})\b") 6 | list_result = list() 7 | result = re.finditer(patterns, main_string) 8 | 9 | for show in result: 10 | list_result.append(show[0]) 11 | 12 | print(*list_result, sep=", ") 13 | 14 | 15 | 16 | 17 | 18 | # import re 19 | # 20 | # phone_number = input() 21 | # pattern = re.compile(r"((^\+|\s\+)359-2-\d{3}-\b\d{4}\b|(^\+|\s\+)359\s2\s\d{3}\s\b\d{4}\b)") 22 | # matches = pattern.finditer(phone_number) 23 | # show_result = [] 24 | # for show in matches: 25 | # show_result.append(show[0]) 26 | # 27 | # print(",".join(show_result)) 28 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Lab/03. Match Dates.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | main_string = input() 4 | 5 | patterns = re.compile(r"(?P[0-9]{2})([\.\-/])(?P[A-Z][a-z]{2})\2(?P[0-9]{4})\b") 6 | result = re.finditer(patterns, main_string) 7 | 8 | for show in result: 9 | print(f"Day: {show['Day']}, Month: {show['Month']}, Year: {show['Year']}") 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | # 19 | # import re 20 | # 21 | # dates_match = input() 22 | # pattern = re.compile( 23 | # r"(\d{2}-[A-Z]{1}[a-z]{2}-\b\d{4}\b|\d{2}\.[A-Z]{1}[a-z]{2}\.\b\d{4}\b|\d{2}/[A-Z]{1}[a-z]{2}/\b\d{4}\b)") 24 | # matches = pattern.finditer(dates_match) 25 | # for show in matches: 26 | # if "/" in show[0]: 27 | # show = show[0].split("/") 28 | # elif "-" in show[0]: 29 | # show = show[0].split("-") 30 | # elif "." in show[0]: 31 | # show = show[0].split(".") 32 | # print(f"Day: {show[0]}, Month: {show[1]}, Year: {show[2]}") 33 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - Lab/04. Match Numbers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | dates_match = input() 4 | # pattern = re.compile(r"(^|(?<=\s)-?([0]|[1-9][0-9]*)(\.\d+)?($|(?=\s)))") 5 | pattern = re.compile(r"(^|(?<=\s))-?([0]|[1-9][0-9]*)(\.\d+)?($|(?=\s))") 6 | matches = pattern.finditer(dates_match) 7 | for show in matches: 8 | print(show[0], end=" ") 9 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - More Exercise/01. Race.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | name_of_participants = {name.replace(" ", ""): 0 for name in input().split(",")} 4 | racer_code = input() 5 | letters_d = re.compile(r"([A-Za-z])") 6 | numbers_d = re.compile(r"([0-9])") 7 | while racer_code != "end of race": 8 | find_name = "".join(re.findall(letters_d, racer_code)) 9 | find_numbers = sum(int(num) for num in re.findall(numbers_d, racer_code)) 10 | if find_name in name_of_participants.keys(): 11 | name_of_participants[find_name] += find_numbers 12 | racer_code = input() 13 | 14 | name_of_participants = sorted(name_of_participants.items(), key=lambda x: -x[1]) 15 | 16 | print(f"1st place: {name_of_participants[0][0]}") 17 | print(f"2nd place: {name_of_participants[1][0]}") 18 | print(f"3rd place: {name_of_participants[2][0]}") 19 | 20 | 21 | 22 | # names_info = {x: 0 for x in input().split(", ")} 23 | # 24 | # info = input() 25 | # while info != "end of race": 26 | # name, distance = "", [] 27 | # 28 | # for char in info: 29 | # if char.isdigit(): 30 | # distance.append(int(char)) 31 | # elif char.isalpha(): 32 | # name += char 33 | # 34 | # if name in names_info: 35 | # names_info[name] += sum(distance) 36 | # info = input() 37 | # 38 | # 39 | # names_info = sorted(names_info.items(), key=lambda x: -x[1]) 40 | # 41 | # print(f"1st place: {names_info[0][0]}") 42 | # print(f"2nd place: {names_info[1][0]}") 43 | # print(f"3rd place: {names_info[2][0]}") 44 | # 45 | # 46 | # 47 | # 48 | # 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | # 57 | # 58 | # import re 59 | # 60 | # name_of_participants = {name.replace(" ", ""): 0 for name in input().split(",")} 61 | # 62 | # result_show = [] 63 | # racer_code = input() 64 | # letters_d = re.compile(r"([A-Za-z])") 65 | # numbers_d = re.compile(r"([0-9])") 66 | # score_d = "score" 67 | # name_d = "name" 68 | # while racer_code != "end of race": 69 | # find_letters_d = re.finditer(letters_d, racer_code) 70 | # find_numbers_d = re.finditer(numbers_d, racer_code) 71 | # find_name = "" 72 | # find_numbers = 0 73 | # for name in find_letters_d: 74 | # find_name += name[0] 75 | # for numbers in find_numbers_d: 76 | # find_numbers += int(numbers[0]) 77 | # if find_name in name_of_participants.keys(): 78 | # name_of_participants[find_name] += find_numbers 79 | # racer_code = input() 80 | # 81 | # for name in name_of_participants: 82 | # result_show.append({name_d: name, score_d: name_of_participants[name]}) 83 | # result_show.sort(key=lambda item: (-item[score_d])) 84 | # 85 | # print(f"1st place: {result_show[0][name_d]}") 86 | # print(f"2nd place: {result_show[1][name_d]}") 87 | # print(f"3rd place: {result_show[2][name_d]}") 88 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - More Exercise/02. SoftUni Bar Income.py: -------------------------------------------------------------------------------- 1 | import re 2 | total_income = 0 3 | pattern = re.compile( 4 | r"(%)(?P[A-Z][a-z]+)\1([^\|\$\%\.]*)" 5 | r"<(?P[\w]+)>([^\|\$\%\.]*)" 6 | r"\|(?P[\d]+)\|([^\|\$\%\.]*)" 7 | r"(?P[1-9]+[.0-9]*)\$") 8 | 9 | 10 | data_input = input() 11 | 12 | while data_input != "end of shift": 13 | result = re.finditer(pattern, data_input) 14 | for show in result: 15 | current_price = float(show["count"]) * float(show["price"]) 16 | print(f"{show['customer']}: {show['product']} - {current_price:.2f}") 17 | total_income += current_price 18 | data_input = input() 19 | 20 | print(f"Total income: {total_income:.2f}") 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | # 30 | # 31 | # import re 32 | # 33 | # customers = input() 34 | # customer_name, product_name, price_product, value_product = re.compile(r"\%{1}([A-Z]{1}[a-z]{1,})\%{1}"), \ 35 | # re.compile(r"\<{1}([\w]{1,})\>{1}"),re.compile(r"\|{1}(\d{1,})\|{1}"),re.compile(r"(\d+\.\d+)\b([$]){1}|(\d+\d+)\b([$]){1}") 36 | # total_income = 0 37 | # while customers != "end of shift": 38 | # 39 | # name_d, product_d, price_d, value_d = re.finditer(customer_name, customers), \ 40 | # re.finditer(product_name, customers), re.finditer(price_product, 41 | # customers), re.finditer( value_product, customers) 42 | # 43 | # name_find = None 44 | # product_find = None 45 | # price_find = None 46 | # value_find = None 47 | # for show, p_name, p_price, p_value in zip(name_d, product_d, price_d, value_d): 48 | # name_find = show[1] 49 | # product_find = p_name[1] 50 | # price_find = float(p_price[1]) 51 | # if p_value[1] is None: 52 | # value_find = float(p_value[3]) 53 | # elif p_value[3] is None: 54 | # value_find = float(p_value[1]) 55 | # 56 | # if all([name_find is not None, product_find is not None, 57 | # price_find is not None, value_find is not None]): 58 | # print(f"{name_find}: {product_find} - {(price_find * value_find):.2f}") 59 | # total_income += (price_find * value_find) 60 | # 61 | # customers = input() 62 | # 63 | # print(f"Total income: {total_income:.2f}") 64 | 65 | 66 | 67 | 68 | 69 | # import re 70 | # 71 | # customers = input() 72 | # 73 | # customer_name = re.compile(r"\%{1}([A-Z]{1}[a-z]{1,})\%{1}") 74 | # product_name = re.compile(r"\<{1}([\w]{1,})\>{1}") 75 | # price_product = re.compile(r"\|{1}(\d{1,})\|{1}") 76 | # value_product = re.compile(r"(\d+\.\d+)\b([$]){1}|(\d+\d+)\b([$]){1}") 77 | # 78 | # total_income = 0 79 | # while customers != "end of shift": 80 | # 81 | # name_d = re.finditer(customer_name, customers) 82 | # product_d = re.finditer(product_name, customers) 83 | # price_d = re.finditer(price_product, customers) 84 | # value_d = re.finditer(value_product, customers) 85 | # name_find = None 86 | # product_find = None 87 | # price_find = None 88 | # value_find = None 89 | # for show in name_d: 90 | # # print(show[0]) 91 | # name_find = show[1] 92 | # # print(show[1]) 93 | # for p_name in product_d: 94 | # # print(p_name[0]) 95 | # product_find = p_name[1] 96 | # # print(p_name[1]) 97 | # 98 | # for p_price in price_d: 99 | # # print(p_price[0]) 100 | # price_find = float(p_price[1]) 101 | # # print(p_price[1]) 102 | # 103 | # for p_value in value_d: 104 | # # print(p_value[0]) 105 | # if p_value[1] is None: 106 | # value_find = float(p_value[3]) 107 | # elif p_value[3] is None: 108 | # value_find = float(p_value[1]) 109 | # # print(p_value[1]) 110 | # # # print(p_value[2]) 111 | # # print(p_value[3]) 112 | # 113 | # if all([name_find != None, product_find != None, price_find != None, value_find != None]): 114 | # print(f"{name_find}: {product_find} - {(price_find * value_find):.2f}") 115 | # total_income += (price_find * value_find) 116 | # 117 | # customers = input() 118 | # 119 | # print(f"Total income: {total_income:.2f}") 120 | 121 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - More Exercise/03. Star Enigma.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | number_of_messages = int(input()) 4 | 5 | planets_info = {"Attacked": [], "Destroyed": [], "A": "Attacked", "D": "Destroyed"} 6 | pattern = re.compile(r"@(?P[A-Za-z]+)([^\@\-\!\:\>]*)" 7 | r":(?P[0-9]+)([^\@\-\!\:\>]*)" 8 | r"(\!)(?P[AD])\5([^\@\-\!\:\>]*)" 9 | r"->(?P[0-9]+)") 10 | 11 | for msg in range(number_of_messages): 12 | current_msg = input() 13 | code_decrypt = sum(current_msg.lower().count(char) for char in "star") 14 | decode_msg = "".join(chr(ord(char) - code_decrypt) for char in current_msg) 15 | result = re.finditer(pattern, decode_msg) 16 | for show in result: 17 | planets_info[planets_info[show["attack_type"]]].append(show["planet_name"]) 18 | 19 | for type_attack in list(planets_info.keys())[:2]: 20 | planet_count = len(planets_info[type_attack]) 21 | print(f"{type_attack} planets: {planet_count}") 22 | if planet_count: 23 | for planet in sorted(planets_info[type_attack]): 24 | print(f"-> {planet}") 25 | 26 | 27 | 28 | 29 | 30 | # 31 | # import re 32 | # 33 | # number_of_messages = int(input()) 34 | # attacked_planets = [] 35 | # destroyed_planets = [] 36 | # pattern = r'[starSTAR]' 37 | # planets_pattern = r'.*@(?P[A-Z][a-z]+)[^\@\-\!\:\>]*:(?P\d+)[^\@\-\!\:\>]*\!(?PA|D)\![^\@\-\!\:\>]*\->(?P\d+).*' 38 | # for message in range(number_of_messages): 39 | # encrypted_message = input() 40 | # decrypted_message = '' 41 | # matches = len(re.findall(pattern, encrypted_message)) 42 | # 43 | # for character in encrypted_message: 44 | # decrypted_character = chr((ord(character)) - matches) 45 | # decrypted_message += decrypted_character 46 | # 47 | # planet_matches = re.finditer(planets_pattern, decrypted_message) 48 | # for value in planet_matches: 49 | # planet, attack_type = value.group('planet'), value.group('attack_type') 50 | # 51 | # if attack_type == 'A': 52 | # attacked_planets.append(planet) 53 | # else: 54 | # destroyed_planets.append(planet) 55 | # 56 | # print(f'Attacked planets: {len(attacked_planets)}') 57 | # for planet in sorted(attacked_planets): 58 | # print(f'-> {planet}') 59 | # 60 | # print(f'Destroyed planets: {len(destroyed_planets)}') 61 | # for planet in sorted(destroyed_planets): 62 | # print(f'-> {planet}') 63 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - More Exercise/04. Nether Realms.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | pattern_health = r"[^\d\+\-\*\/\.]" 4 | pattern_damage = r"([-+]?\d+(\.\d+)?)" 5 | pattern_operator = r"[*\/]" 6 | 7 | demons = input().split(",") 8 | demons = [demon.strip() for demon in demons] 9 | 10 | for demon in sorted(demons): 11 | health = re.findall(pattern_health, demon) 12 | health = sum(ord(character) for character in health) 13 | damage = re.findall(pattern_damage, demon) 14 | if damage: 15 | damage = sum(float(number[0]) for number in damage) 16 | 17 | operators = re.findall(pattern_operator, demon) 18 | 19 | if operators: 20 | for operator in operators: 21 | if operator == "*": 22 | damage *= 2 23 | elif operator == "/": 24 | damage /= 2 25 | 26 | else: 27 | damage = 0 28 | print(f"{demon} - {health} health, {damage:.2f} damage") 29 | 30 | 31 | 32 | 33 | # 34 | # import re 35 | # 36 | # demons = re.split(", *", input()) 37 | # demon_book = {} 38 | # 39 | # demon_health_pattern = re.compile(r'[^\d\+\-*\/\.]') 40 | # demon_damage_pattern = re.compile(r'(?:\+|-)?[0-9]+(?:\.[0-9]+)?') 41 | # demon_operators_pattern = re.compile(r'[*\/]') 42 | # 43 | # for demon in demons: 44 | # demon = demon.strip() 45 | # demon_health = re.findall(demon_health_pattern, demon) 46 | # demon_book[demon] = demon_book.get(demon, {}) 47 | # demon_book[demon]["health"] = sum(ord(match) for match in demon_health) 48 | # 49 | # demon_damage = re.finditer(demon_damage_pattern, demon) 50 | # operators = re.findall(demon_operators_pattern, demon) 51 | # current_demon_damage = 0 52 | # 53 | # for value in demon_damage: 54 | # current_demon_damage += float(value.group()) 55 | # 56 | # for operator in operators: 57 | # if operator == '*': 58 | # current_demon_damage *= 2 59 | # elif operator == '/': 60 | # current_demon_damage /= 2 61 | # 62 | # demon_book[demon]["damage"] = current_demon_damage 63 | # 64 | # for demon in sorted(demon_book): 65 | # print(f'{demon} - {demon_book[demon]["health"]} health, {demon_book[demon]["damage"]:.2f} damage') 66 | # 67 | # 68 | 69 | 70 | 71 | 72 | 73 | # list 74 | # 75 | # 76 | # import re 77 | # 78 | # demons = re.split(", *", input()) 79 | # demon_book = {} 80 | # 81 | # demon_health_pattern = r'[^\d\+\-*\/\.]' 82 | # demon_damage_pattern = r'(?:\+|-)?[0-9]+(?:\.[0-9]+)?' 83 | # demon_operators_pattern = r'[*\/]' 84 | # 85 | # for demon in demons: 86 | # demon = demon.strip() 87 | # demon_health = re.findall(demon_health_pattern, demon) 88 | # demon_book[demon] = [] 89 | # demon_book[demon].append(sum(ord(match) for match in demon_health)) 90 | # 91 | # demon_damage = re.finditer(demon_damage_pattern, demon) 92 | # operators = re.findall(demon_operators_pattern, demon) 93 | # current_demon_damage = 0 94 | # 95 | # for value in demon_damage: 96 | # current_demon_damage += float(value.group(0)) 97 | # 98 | # for operator in operators: 99 | # if operator == '*': 100 | # current_demon_damage *= 2 101 | # elif operator == '/': 102 | # current_demon_damage /= 2 103 | # 104 | # demon_book[demon].append(current_demon_damage) 105 | # 106 | # for demon, qualities in sorted(demon_book.items()): 107 | # print(f'{demon} - {qualities[0]} health, {qualities[1]:.2f} damage') 108 | -------------------------------------------------------------------------------- /09. Regular Expressions/09. Regular Expressions - More Exercise/05. HTML Parser.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | html_content = input() 4 | pattern = re.compile(r"(?:)(?P<title_html>.+)(?:).*(?:)(?P.+)(?:)") 5 | m_space, tabs_n, between = r"[ ]+", r"\\n|\\t", r"<[^>]*>" 6 | result = re.finditer(pattern, html_content) 7 | for show in result: 8 | print(f'Title: {re.sub(m_space, " ", re.sub(tabs_n, "", re.sub(between, "", show["title_html"])))}') 9 | print(f'Content: {re.sub(m_space, " ", re.sub(tabs_n, "", re.sub(between, "", show["body_html"])))}') 10 | 11 | 12 | # 13 | # import re 14 | # 15 | # text = input() 16 | # 17 | # pattern_title = r"(?:)(?P<title>.+)(?:)" 18 | # pattern_body = r"(?:)(?P.+)(?:)" 19 | # title = re.search(pattern_title, text).group("title") 20 | # body = re.search(pattern_body, text).group("body") 21 | # title = re.sub(r"[ ]+", " ", re.sub(r"\\n|\\t", "", re.sub(r"<[^>]*>", "", title))) 22 | # body = re.sub(r"[ ]+", " ", re.sub(r"\\n|\\t", "", re.sub(r"<[^>]*>", "", body))) 23 | # print(f"Title: {title}") 24 | # print(f"Content: {body}") 25 | # 26 | # 27 | # 28 | 29 | 30 | 31 | 32 | # 33 | # 34 | # 35 | # import re 36 | # 37 | # pattern_title = r"(?:)(?P<title>.+)(?:)" 38 | # pattern_body = r"(?:)(?P.+)(?:)" 39 | # pattern_remove_tags = r"<[^>]*>" 40 | # pattern_remove_pseudo_space = r"\\n|\\t" # "new lines" and "tabs" 41 | # pattern_remove_spaces = r"[ ]+" 42 | # 43 | # text = input() 44 | # 45 | # title = re.search(pattern_title, text).group("title") 46 | # body = re.search(pattern_body, text).group("body") 47 | # 48 | # title = re.sub(pattern_remove_tags, "", title, re.IGNORECASE | re.UNICODE) 49 | # body = re.sub(pattern_remove_tags, "", body, re.IGNORECASE | re.UNICODE) 50 | # 51 | # title = re.sub(pattern_remove_pseudo_space, "", title).strip() 52 | # body = re.sub(pattern_remove_pseudo_space, "", body).strip() 53 | # 54 | # title = re.sub(pattern_remove_spaces, " ", title).strip() 55 | # body = re.sub(pattern_remove_spaces, " ", body).strip() 56 | # 57 | # print(f"Title: {title}") 58 | # print(f"Content: {body}") -------------------------------------------------------------------------------- /10. Final Exam/01..py: -------------------------------------------------------------------------------- 1 | def is_valid_length(password): 2 | return 8 <= len(password) 3 | 4 | def consists_only_letters_digits(password): 5 | return all(char.isalnum() or char == '_' for char in password) 6 | 7 | def has_uppercase_letter(password): 8 | return any(char.isupper() for char in password) 9 | 10 | def has_lowercase_letter(password): 11 | return any(char.islower() for char in password) 12 | 13 | def has_digit(password): 14 | return any(char.isdigit() for char in password) 15 | 16 | def is_valid_password(password): 17 | validation_messages = [] 18 | if not is_valid_length(password): 19 | validation_messages.append("Password must be at least 8 characters long!") 20 | if not consists_only_letters_digits(password): 21 | validation_messages.append("Password must consist only of letters, digits, and _!") 22 | if not has_uppercase_letter(password): 23 | validation_messages.append("Password must consist at least one uppercase letter!") 24 | if not has_lowercase_letter(password): 25 | validation_messages.append("Password must consist at least one lowercase letter!") 26 | if not has_digit(password): 27 | validation_messages.append("Password must consist at least one digit!") 28 | 29 | return validation_messages 30 | 31 | def manipulate_password(password, commands): 32 | for command in commands: 33 | tokens = command.split() 34 | action = tokens[0] 35 | if action == "Make": 36 | _, case, index = tokens 37 | index = int(index) 38 | if case == "Upper": 39 | password = password[:index] + password[index].upper() + password[index + 1:] 40 | print(password) 41 | elif case == "Lower": 42 | password = password[:index] + password[index].lower() + password[index + 1:] 43 | print(password) 44 | elif action == "Insert": 45 | _, index, char = tokens 46 | index = int(index) 47 | if 0 <= index <= len(password): 48 | password = password[:index] + char + password[index:] 49 | print(password) 50 | elif action == "Replace": 51 | _, char, value = tokens 52 | value = int(value) 53 | if char in password: 54 | new_char = chr(ord(char) + value) 55 | password = password.replace(char, new_char) 56 | print(password) 57 | elif action == "Validation": 58 | validation_results = is_valid_password(password) 59 | if not validation_results: 60 | encrypted_password = "".join(chr(ord(char) + 3) for char in password) 61 | # print(f"Password: {encrypted_password}") 62 | else: 63 | print("Try another password!") 64 | 65 | 66 | initial_password = input() 67 | commands = [] 68 | while True: 69 | command = input() 70 | if command == "Complete": 71 | break 72 | commands.append(command) 73 | 74 | manipulate_password(initial_password, commands) -------------------------------------------------------------------------------- /10. Final Exam/02..py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def sol(): 4 | count = int(input()) 5 | pattern = r'(.+)\>([0-9]{3})\|([a-z]{3})\|([A-Z]{3})\|([^\<\>]{3})\<\1' 6 | for i in range(count): 7 | password = input() 8 | result = re.match(pattern, password) 9 | if result: 10 | print(f"Password: {result.group(2)}{result.group(3)}{result.group(4)}{result.group(5)}") 11 | else: 12 | print("Try another password!") 13 | 14 | sol() -------------------------------------------------------------------------------- /10. Final Exam/03..py: -------------------------------------------------------------------------------- 1 | zoo = {"Area": {}} 2 | data_inp = input() 3 | 4 | while data_inp != "EndDay": 5 | 6 | command_, data = data_inp.split(": ") 7 | 8 | if command_ == "Add": 9 | animal_name, needed_food_quantity, area = data.split("-") 10 | zoo[animal_name] = zoo.get(animal_name, 0) + int(needed_food_quantity) 11 | if area not in zoo["Area"]: 12 | zoo["Area"][area] = [] 13 | if animal_name not in zoo["Area"][area]: 14 | zoo["Area"][area].append(animal_name) 15 | 16 | elif command_ == "Feed": 17 | animal_name, needed_food_quantity = data.split("-") 18 | if animal_name in zoo: 19 | zoo[animal_name] -= int(needed_food_quantity) 20 | if zoo[animal_name] <= 0: 21 | del zoo[animal_name] 22 | for pet_names in zoo["Area"].values(): 23 | if animal_name in pet_names: 24 | pet_names.remove(animal_name) 25 | break 26 | print(f"{animal_name} was successfully fed") 27 | 28 | data_inp = input() 29 | 30 | if zoo: 31 | print("Animals:") 32 | [print(f" {name} -> {quantity}g") for name, quantity in zoo.items() if name != "Area"] 33 | 34 | if zoo["Area"]: 35 | print("Areas with hungry animals:") 36 | [print(f" {area_name}: {len(zoo['Area'][area_name])}") for area_name in zoo["Area"] if zoo["Area"][area_name]] 37 | 38 | 39 | 40 | 41 | # def feeding_animals(): 42 | # class Animal: 43 | # def __init__(self, name, food, area): 44 | # self.name = name 45 | # self.food = food 46 | # self.area = area 47 | # 48 | # def handle_add(map_animals, name, food_quantity, area, hungry_animals): 49 | # if name not in map_animals: 50 | # animal = Animal(name, food_quantity, area) 51 | # map_animals[name] = animal 52 | # else: 53 | # old_food_quantity = map_animals[name].food 54 | # map_animals[name].food = food_quantity + old_food_quantity 55 | # 56 | # if area not in hungry_animals: 57 | # hungry_animals[area] = 1 58 | # else: 59 | # count_value = hungry_animals[area] 60 | # hungry_animals[area] = count_value + 1 61 | # 62 | # def handle_feed(map_animals, name, food_quantity, hungry_animals): 63 | # if name in map_animals: 64 | # animal = map_animals[name] 65 | # food_needed = animal.food 66 | # feed_result = food_needed - food_quantity 67 | # if feed_result > 0: 68 | # animal.food = feed_result 69 | # else: 70 | # print(f"{name} was successfully fed") 71 | # living_area = animal.area 72 | # value = hungry_animals[living_area] 73 | # hungry_animals[living_area] = value - 1 74 | # if hungry_animals[living_area] == 0: 75 | # del hungry_animals[living_area] 76 | # del map_animals[name] 77 | # 78 | # map_animals = {} 79 | # hungry_animals = {} 80 | # 81 | # while True: 82 | # command = input() 83 | # if command == "EndDay": 84 | # break 85 | # 86 | # action, data = command.split(": ") 87 | # animal_name, *params = data.split("-") 88 | # 89 | # if action == "Add": 90 | # handle_add(map_animals, animal_name, int(params[0]), params[1], hungry_animals) 91 | # elif action == "Feed": 92 | # handle_feed(map_animals, animal_name, int(params[0]), hungry_animals) 93 | # 94 | # print("Animals:") 95 | # for animal_name, animal in sorted(map_animals.items(), key=lambda x: x[0]): 96 | # print(f" {animal_name} -> {animal.food}g") 97 | # 98 | # print("Areas with hungry animals:") 99 | # for area, count in sorted(hungry_animals.items(), key=lambda x: -x[1]): 100 | # print(f" {area}: {count}") 101 | # 102 | # 103 | # feeding_animals() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Fundamentals 2 | 3 | ## Python 4 | 5 | - Basic Syntax, Conditional Statements and Loops 6 | - Data Types and Variables 7 | - Lists Basics 8 | - Functions 9 | - Lists Advanced 10 | - Objects and Classes 11 | - Dictionaries 12 | - Text Processing 13 | - Regular Expressions 14 | 15 | ## Other 16 | 17 | - Git and GitHub 18 | - HTTP Basics 19 | - HTML & CSS Basics 20 | - Software Development Concepts 21 | - Bitwise Operations 22 | - Problem Solving 23 | - Database Basics 24 | - QA Introduction 25 | - Basic Web Project --------------------------------------------------------------------------------