angelstoev

Final Exam

Dec 3rd, 2022
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.13 KB | None | 0 0
  1. regex info
  2. https://www.rexegg.com/regex-quickstart.html
  3. https://regex101.com/
  4. https://www.pythontutorial.net/python-regex/
  5. ##############################################
  6. 01. Programming Fundamentals Final Exam Retake
  7.  
  8. 01. The Imitation Game
  9.  
  10. main_string = input()
  11.  
  12. command = input()
  13.  
  14.  
  15. def move_sting(number, string):
  16.     return string[number:] + string[:number]
  17.  
  18.  
  19. def insert_string(index, value, string):
  20.     return string[:index] + value + string[index:]
  21.  
  22.  
  23. def change_all(substring, replacement, string):
  24.     return string.replace(substring, replacement)
  25.  
  26.  
  27. while command != "Decode":
  28.     command_type, *info = [int(x) if x.isdigit() else x for x in command.split("|")]
  29.     if command_type == "Move":
  30.         number = info[0]
  31.         main_string = move_sting(number, main_string)
  32.     else:
  33.         index_or_substring, value_or_replacement = info
  34.         if command_type == "Insert":
  35.             main_string = insert_string(index_or_substring, value_or_replacement, main_string)
  36.         elif command_type == "ChangeAll":
  37.             main_string = change_all(index_or_substring, value_or_replacement, main_string)
  38.  
  39.     command = input()
  40.  
  41. print(f"The decrypted message is: {main_string}")
  42.  
  43.  
  44.  
  45. 02. Ad Astra
  46.  
  47.  
  48. import re
  49.  
  50. main_string = input()
  51.  
  52. pattern = re.compile(r"([#|])(?P<item_name>[A-Za-z ]+)"
  53.                      r"\1(?P<exp_date>[0-9]{2}/[0-9]{2}/[0-9]{2})"
  54.                      r"\1(?P<calories>[0-9]{1,5})\1")
  55. calories_last = 0
  56. result_show = []
  57. result = re.finditer(pattern, main_string)
  58.  
  59. for show in result:
  60.     calories_last += int(show["calories"])
  61.     result_show.append({"name": show["item_name"],
  62.                         "exp date": show["exp_date"],
  63.                         "calories": show["calories"]})
  64.  
  65. calories_last = int(calories_last / 2000)
  66. print(f"You have food to last you for: {calories_last} days!")
  67.  
  68. for show in result_show:
  69.     print(f"Item: {show['name']}, Best before: {show['exp date']}, Nutrition: {show['calories']}")
  70.  
  71.  
  72.  
  73. 03. The Pianist
  74.  
  75. number_of_pieces = int(input())
  76.  
  77. music_info = {}
  78.  
  79.  
  80. def piece_exists(piece_name):
  81.     if piece_name in music_info:
  82.         return True
  83.     return False
  84.  
  85.  
  86. def add_music_info(piece_name, composer_name, key_name, first_input):
  87.     if piece_exists(piece_name):
  88.         if not first_input:
  89.             print(f"{piece_name} is already in the collection!")
  90.             return
  91.     if not piece_exists(piece_name):
  92.         music_info[piece_name] = music_info.get(piece_name, {})
  93.         music_info[piece_name][key_name] = composer_name
  94.         if not first_input:
  95.             print(f"{piece_name} by {composer_name} in {key_name} added to the collection!")
  96.  
  97.  
  98. def remove_music_info(piece_name):
  99.     if piece_exists(piece_name):
  100.         del music_info[piece_name]
  101.         print(f"Successfully removed {piece_name}!")
  102.         return
  103.     print(f"Invalid operation! {piece_name} does not exist in the collection.")
  104.  
  105.  
  106. def change_key(piece_name, key_name):
  107.     if piece_exists(piece_name):
  108.         _, name_compositor = music_info[piece_name].popitem()
  109.         music_info[piece_name] = {}
  110.         music_info[piece_name][key_name] = name_compositor
  111.         print(f"Changed the key of {piece_name} to {key_name}!")
  112.         return
  113.     print(f"Invalid operation! {piece_name} does not exist in the collection.")
  114.  
  115.  
  116. def show_result():
  117.     for piece_name in music_info:
  118.         for key_name, name_compositor in music_info[piece_name].items():
  119.             print(f"{piece_name} -> Composer: {name_compositor}, Key: {key_name}")
  120.  
  121.  
  122. for piece in range(number_of_pieces):
  123.     piece_name, composer_name, key_name = input().split("|")
  124.     add_music_info(piece_name, composer_name, key_name, True)
  125.  
  126. command = input()
  127.  
  128. while command != "Stop":
  129.     command_type, *info = command.split("|")
  130.     if command_type == "Remove":
  131.         piece_name = info[0]
  132.         remove_music_info(piece_name)
  133.     elif command_type == "Add":
  134.         piece_name, composer_name, key_name = info
  135.         add_music_info(piece_name, composer_name, key_name, False)
  136.  
  137.     elif "ChangeKey" == command_type:
  138.         piece_name, new_key = info
  139.         change_key(piece_name, new_key)
  140.  
  141.     command = input()
  142.  
  143. show_result()
  144.  
  145. #######################################
  146. 02. Programming Fundamentals Final Exam
  147.  
  148. 01. World Tour
  149.  
  150. main_string = input()
  151.  
  152.  
  153. def valid_index(index):
  154.     if 0 <= index < len(main_string):
  155.         return True
  156.  
  157.  
  158. def add_stop(index, string, main_string):
  159.     if valid_index(index):
  160.         main_string = main_string[:index] + string + main_string[index:]
  161.     return main_string
  162.  
  163.  
  164. def remove_stop(start_index, end_index, main_string):
  165.     if valid_index(start_index) and valid_index(end_index):
  166.         main_string = main_string[:start_index] + "" + main_string[end_index + 1:]
  167.     return main_string
  168.  
  169.  
  170. def switch(old_string, new_string, main_string):
  171.     if old_string in main_string:
  172.         main_string = main_string.replace(old_string, new_string)
  173.     return main_string
  174.  
  175.  
  176. command = input()
  177.  
  178. while command != "Travel":
  179.     command_type, index_or_old_string, string_or_end_index = [int(x) if x.isdigit() else x for x in command.split(":")]
  180.     if "Add" in command_type:
  181.         main_string = add_stop(index_or_old_string, string_or_end_index, main_string)
  182.     elif "Remove" in command_type:
  183.         main_string = remove_stop(index_or_old_string, string_or_end_index, main_string)
  184.     elif "Switch" in command_type:
  185.         main_string = switch(index_or_old_string, string_or_end_index, main_string)
  186.     print(main_string)
  187.     command = input()
  188.  
  189.  
  190. print(f"Ready for world tour! Planned stops: {main_string}")
  191.  
  192.  
  193.  
  194. 02. Destination Mapper
  195.  
  196. import re
  197.  
  198. main_string = input()
  199.  
  200. pattern = re.compile(r"([=/])(?P<location>[A-Z][a-zA-Z]{2,})\1")
  201.  
  202. list_result = []
  203. result = re.finditer(pattern, main_string)
  204. total_travel_points = 0
  205. for show in result:
  206.     total_travel_points += len(show["location"])
  207.     list_result.append(show["location"])
  208.  
  209. print(f"Destinations: {', '.join(list_result)}")
  210. print(f"Travel Points: {total_travel_points}")
  211.  
  212. 03. Plant Discovery
  213.  
  214.  
  215. number_of_plants = int(input())
  216.  
  217. plant_info = {}
  218.  
  219. for plant in range(number_of_plants):
  220.     plant_name, plant_rarity = input().split("<->")
  221.     plant_info[plant_name] = plant_info.get(plant_name, {})
  222.     plant_info[plant_name]["rarity"] = float(plant_rarity)
  223.     plant_info[plant_name]["rating"] = []
  224.  
  225.  
  226. def check_plant_name(plant_name):
  227.     if plant_name not in plant_info:
  228.         print("error")
  229.         return
  230.     return True
  231.  
  232.  
  233. def rate_plant(plant, rating):
  234.     if check_plant_name(plant):
  235.         plant_info[plant]["rating"].append(rating)
  236.  
  237.  
  238. def update_plant(plant, new_rarity):
  239.     if check_plant_name(plant):
  240.         plant_info[plant]["rarity"] = new_rarity
  241.  
  242.  
  243. def reset_plant(plant):
  244.     if check_plant_name(plant):
  245.         plant_info[plant]["rating"] = []
  246.  
  247.  
  248. def show_result():
  249.     print("Plants for the exhibition:")
  250.     for plant in plant_info:
  251.         average = 0.00
  252.         if sum(plant_info[plant]["rating"]) != 0:
  253.             average = sum(plant_info[plant]["rating"]) / len(plant_info[plant]["rating"])
  254.         print(f"- {plant}; Rarity: {plant_info[plant]['rarity']:.0f}; Rating: {average:.2f}")
  255.  
  256.  
  257. command = input()
  258. while command != "Exhibition":
  259.     if "Reset" in command:
  260.         _, plant = command.split(": ")
  261.         reset_plant(plant)
  262.         command = input()
  263.         continue
  264.     plant, rating_or_new_rarity = [float(x) if x.isdigit() else x for x in command.split(": ")[1].split(" - ")]
  265.     if "Rate" in command:
  266.         rate_plant(plant, rating_or_new_rarity)
  267.     elif "Update" in command:
  268.         update_plant(plant, rating_or_new_rarity)
  269.  
  270.     command = input()
  271.  
  272. show_result()
  273.  
  274.  
  275. ##############################################
  276. 03. Programming Fundamentals Final Exam Retake
  277.  
  278. 01. Secret Chat
  279.  
  280. main_string = input()
  281. command = input()
  282.  
  283.  
  284. def insert_space(index, main_string):
  285.     return main_string[:index] + " " + main_string[index:]
  286.  
  287.  
  288. def reverse_(substring, main_string):
  289.     word_find = main_string.find(substring)
  290.     main_string = main_string[:word_find] + main_string[word_find + len(substring):]
  291.     main_string += substring[::-1]
  292.     return main_string
  293.  
  294.  
  295. def change_all(substring, replacement, main_string):
  296.     return main_string.replace(substring, replacement)
  297.  
  298.  
  299. while command != "Reveal":
  300.     command_type, *info = command.split(":|:")
  301.     found_error = False
  302.     if command_type == "ChangeAll":
  303.         substring, replacement = info
  304.         main_string = change_all(substring, replacement, main_string)
  305.     else:
  306.         if command_type == "Reverse":
  307.             substring = info[0]
  308.             if substring not in main_string:
  309.                 print("error")
  310.                 found_error = True
  311.             else:
  312.                 main_string = reverse_(substring, main_string)
  313.         elif "InsertSpace" == command_type:
  314.             index_ = int(info[0])
  315.             main_string = insert_space(index_, main_string)
  316.     if not found_error:
  317.         print(main_string)
  318.     command = input()
  319.  
  320.  
  321. print(f"You have a new text message: {main_string}")
  322.  
  323.  
  324. 02. Mirror Words
  325.  
  326. import re
  327.  
  328. main_string = input()
  329.  
  330. pattern = re.compile(r"([@#])(?P<word>[A-Za-z]{3,})\1\1(?P<word2>[A-Za-z]{3,})\1")
  331.  
  332. list_result = []
  333. result = list(re.finditer(pattern, main_string))
  334.  
  335. for show in result:
  336.     if show["word"] == show["word2"][::-1]:
  337.         list_result.append(f"{show['word']} <=> {show['word2']}")
  338.  
  339. if result:
  340.     print(f"{len(result)} word pairs found!")
  341.     if list_result:
  342.         print("The mirror words are:")
  343.         print(*list_result, sep=", ")
  344.     else:
  345.         print("No mirror words!")
  346. else:
  347.     print("No word pairs found!")
  348.     print("No mirror words!")
  349.  
  350.  
  351.  
  352.  
  353. 03. Need for Speed III
  354.  
  355.  
  356. car_numbers = int(input())
  357.  
  358. car_info = {}
  359.  
  360.  
  361. class Car:
  362.  
  363.     def __init__(self, name):
  364.         self.name = name
  365.         self.mileage = 0
  366.         self.fuel = 0
  367.  
  368.     def add_mileage(self, mileage):
  369.         self.mileage += mileage
  370.  
  371.     def add_fuel(self, fuel):
  372.         self.fuel += fuel
  373.  
  374.     def drive(self, distance, fuel):
  375.         if self.fuel > fuel:
  376.             self.fuel -= fuel
  377.             self.mileage += distance
  378.             print(f"{self.name} driven for {distance} kilometers. {fuel} liters of fuel consumed.")
  379.             if self.mileage >= 100_000:
  380.                 del car_info[self.name]
  381.                 print(f"Time to sell the {self.name}!")
  382.         else:
  383.             print("Not enough fuel to make that ride")
  384.  
  385.     def refuel(self, fuel):
  386.         if self.fuel + fuel > 75:
  387.             fuel = 75 - self.fuel
  388.         self.fuel += fuel
  389.         print(f"{self.name} refueled with {fuel} liters")
  390.  
  391.     def revert(self, kilometers):
  392.         self.mileage -= kilometers
  393.         if self.mileage < 10_000:
  394.             self.mileage = 10_000
  395.             return
  396.         print(f"{self.name} mileage decreased by {kilometers} kilometers")
  397.  
  398.     def __repr__(self):
  399.         return f"{self.name} -> Mileage: {self.mileage} kms, Fuel in the tank: {self.fuel} lt."
  400.  
  401.  
  402. for car in range(car_numbers):
  403.     car_name, mileage, fuel = [int(x) if x.isdigit() else x for x in input().split("|")]
  404.     car_info[car_name] = car_info.get(car_name, Car(car_name))
  405.     car_info[car_name].add_mileage(mileage)
  406.     car_info[car_name].add_fuel(fuel)
  407.  
  408.  
  409. command = input()
  410.  
  411. while command != "Stop":
  412.     command_type, car_name, *info = [int(x) if x.isdigit() else x for x in command.split(" : ")]
  413.     if command_type == "Drive":
  414.         distance, fuel = info
  415.         car_info[car_name].drive(distance, fuel)
  416.     elif command_type == "Refuel":
  417.         fuel = info[0]
  418.         car_info[car_name].refuel(fuel)
  419.     elif command_type == "Revert":
  420.         kilometers = info[0]
  421.         car_info[car_name].revert(kilometers)
  422.     command = input()
  423.  
  424. for car in car_info.values():
  425.     print(car)
  426.  
  427.  
  428. ########################################
  429. 04. Programming Fundamentals Final Exam
  430.  
  431.  
  432. 01. Password Reset
  433.  
  434. main_string = input()
  435. command = input()
  436.  
  437.  
  438. def take_odd_char(main_string):
  439.    
  440.     return "".join(main_string[i] for i in range(len(main_string)) if i % 2 != 0)
  441.  
  442.  
  443. def cut_string(index, length, main_string):
  444.     return main_string[:index] + main_string[index + length:]
  445.  
  446.  
  447. def substitute(substring, substitute, main_string):
  448.     return main_string.replace(substring, substitute)
  449.  
  450.  
  451. while command != "Done":
  452.     nothing_to_replace = False
  453.     if "TakeOdd" in command:
  454.         main_string = take_odd_char(main_string)
  455.     else:
  456.         _, index_or_substring, length_or_substitute = [int(x) if x.isdigit() else x for x in command.split()]
  457.         if "Cut" in command:
  458.             main_string = cut_string(index_or_substring, length_or_substitute, main_string)
  459.         elif "Substitute" in command:
  460.             if index_or_substring in main_string:
  461.                 main_string = substitute(index_or_substring, length_or_substitute, main_string)
  462.             else:
  463.                 print("Nothing to replace!")
  464.                 nothing_to_replace = True
  465.     if not nothing_to_replace:
  466.         print(main_string)
  467.  
  468.     command = input()
  469.  
  470. print(f"Your password is: {main_string}")
  471.  
  472.  
  473.  
  474. 02. Fancy Barcodes
  475. import re
  476.  
  477. number_products = int(input())
  478.  
  479. pattern = re.compile(r"@[#]+(?P<found_text>[A-Z][a-zA-Z0-9]{4,}[A-Z])@[#]+")
  480.  
  481.  
  482. for product_input in range(number_products):
  483.     bar_code = input()
  484.     find_result = re.finditer(pattern, bar_code)
  485.     found = False
  486.     for show in find_result:
  487.         found = True
  488.         result_print = ''.join(x for x in show["found_text"] if x.isdigit())
  489.         if result_print:
  490.             print(f"Product group: {result_print}")
  491.         else:
  492.             print(f"Product group: 00")
  493.     if not found:
  494.         print("Invalid barcode")
  495.  
  496. 03. Heroes of Code and Logic VII
  497.  
  498.  
  499. number_heroes = int(input())
  500.  
  501. heroes_info = {}
  502.  
  503.  
  504. class Heroes:
  505.     def __init__(self, name):
  506.         self.name = name
  507.         self.hp = 0
  508.         self.mp = 0
  509.  
  510.     def add_hp(self, hp):
  511.         self.hp += hp
  512.  
  513.     def add_mp(self, mp):
  514.         self.mp += mp
  515.  
  516.     def cast_spall(self, mp_need, spell_name):
  517.         if self.mp >= mp_need:
  518.             self.mp -= mp_need
  519.             return f"{self.name} has successfully cast {spell_name} and now has {self.mp} MP!"
  520.         return f"{self.name} does not have enough MP to cast {spell_name}!"
  521.  
  522.     def take_damage(self, damage, attacker):
  523.         self.hp -= damage
  524.         if self.hp > 0:
  525.             return f"{self.name} was hit for {damage} HP by {attacker} and now has {self.hp} HP left!"
  526.         del heroes_info[self.name]
  527.         return f"{self.name} has been killed by {attacker}!"
  528.  
  529.     def recharge(self, amount):
  530.         if self.mp + amount > 200:
  531.             amount = 200 - self.mp
  532.         self.mp += amount
  533.         return f"{self.name} recharged for {amount} MP!"
  534.  
  535.     def heal(self, amount):
  536.         if self.hp + amount > 100:
  537.             amount = 100 - self.hp
  538.         self.hp += amount
  539.         return f"{self.name} healed for {amount} HP!"
  540.  
  541.     def __repr__(self):
  542.         return f"{self.name}\n  " \
  543.                f"HP: {self.hp}\n  " \
  544.                f"MP: {self.mp}"
  545.  
  546.  
  547. for hero in range(number_heroes):
  548.     hero_name, hp, mp = [int(x) if x.isdigit() else x for x in input().split()]
  549.     heroes_info[hero_name] = heroes_info.get(hero_name, Heroes(hero_name))
  550.     heroes_info[hero_name].add_hp(hp)
  551.     heroes_info[hero_name].add_mp(mp)
  552.  
  553. command = input()
  554.  
  555. while command != "End":
  556.     command_type, hero_name, *info = [int(x) if x.isdigit() else x for x in command.split(" - ")]
  557.     if command_type == "Heal":
  558.         hp = info[0]
  559.         print(heroes_info[hero_name].heal(hp))
  560.     elif command_type == "Recharge":
  561.         mp = info[0]
  562.         print(heroes_info[hero_name].recharge(mp))
  563.     elif command_type == "TakeDamage":
  564.         damage, attacker = info
  565.         print(heroes_info[hero_name].take_damage(damage, attacker))
  566.     elif command_type == "CastSpell":
  567.         mp_need, spell_name = info
  568.         print(heroes_info[hero_name].cast_spall(mp_need, spell_name))
  569.  
  570.     command = input()
  571.  
  572. for hero in heroes_info.values():
  573.     print(hero)
  574.  
  575. ########################################
  576. 05. Programming Fundamentals Final Exam
  577.  
  578. 01. Activation Keys
  579.  
  580. main_string = input()
  581.  
  582.  
  583. def contains(substring, main_string):
  584.     if substring in main_string:
  585.         return f"{main_string} contains {substring}"
  586.     return "Substring not found!"
  587.  
  588.  
  589. def flip(type_flip, start_index, end_index, main_string):
  590.     if type_flip == "Upper":
  591.         result = main_string[:start_index] + \
  592.                  main_string[start_index:end_index].upper() + \
  593.                  main_string[end_index:]
  594.     elif type_flip == "Lower":
  595.         result = main_string[:start_index] + \
  596.                  main_string[start_index:end_index].lower() + \
  597.                  main_string[end_index:]
  598.     return result
  599.  
  600.  
  601. def slice_(start_index, end_index, main_string):
  602.     return main_string[:start_index] + main_string[end_index:]
  603.  
  604.  
  605. command = input()
  606.  
  607. while command != "Generate":
  608.     command_name, *info = command.split(">>>")
  609.     if command_name == "Contains":
  610.         substring = info[0]
  611.         print(contains(substring, main_string))
  612.     elif command_name == "Flip":
  613.         type_flip, start_index, end_index = info
  614.         main_string = flip(type_flip, int(start_index), int(end_index), main_string)
  615.     elif command_name == "Slice":
  616.         start_index, end_index = info
  617.         main_string = slice_(int(start_index), int(end_index), main_string)
  618.     if "Contains" != command_name:
  619.         print(main_string)
  620.  
  621.     command = input()
  622.  
  623.  
  624. print(f"Your activation key is: {main_string}")
  625.  
  626.  
  627. 02. Emoji Detector
  628.  
  629. import re
  630.  
  631. main_string = input()
  632.  
  633. # all_digits = ''.join(re.findall(r"\d+", main_string))
  634. all_digits = ''.join(x for x in main_string if x.isdigit())
  635. cool_threshold = 1
  636. for num in all_digits:
  637.     cool_threshold *= int(num)
  638.  
  639. patterns = re.compile(r"(::|\*\*)(?P<emoji>[A-Z][a-z]{2,})\1")
  640. print(f"Cool threshold: {cool_threshold}")
  641. result = list(re.finditer(patterns, main_string))
  642. print(f"{len(result)} emojis found in the text. The cool ones are:")
  643.  
  644.  
  645. for found in result:
  646.     find_cool = 0
  647.     for letter in found["emoji"]:
  648.         find_cool += ord(letter)
  649.     if find_cool >= cool_threshold:
  650.         print(found[0])
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.  
  658. 03. P!rates
  659.  
  660. towns_info = {}
  661.  
  662.  
  663. class Town:
  664.     def __init__(self, name):
  665.         self.name = name
  666.         self.population = 0
  667.         self.gold = 0
  668.  
  669.     def add_people(self, people):
  670.         self.population += people
  671.  
  672.     def add_gold(self, gold):
  673.         self.gold += gold
  674.  
  675.     def plunder(self, people, gold):
  676.         self.population -= people
  677.         self.gold -= gold
  678.         print(f"{self.name} plundered! {gold} gold stolen, {people} citizens killed.")
  679.         if self.population <= 0 or self.gold <= 0:
  680.             del towns_info[self.name]
  681.             print(f"{self.name} has been wiped off the map!")
  682.  
  683.     def prosper(self, gold):
  684.         if gold < 0:
  685.             print("Gold added cannot be a negative number!")
  686.         else:
  687.             self.gold += gold
  688.             print(f"{gold} gold added to the city treasury. {self.name} now has {self.gold} gold.")
  689.  
  690.     def __repr__(self):
  691.         return f"{self.name} -> Population: {self.population} citizens, Gold: {self.gold} kg"
  692.  
  693.  
  694. command = input()
  695.        
  696. while command != "Sail":
  697.     town, people, gold = [int(x) if x.isdigit() else x for x in command.split("||")]
  698.     towns_info[town] = towns_info.get(town, Town(town))
  699.     towns_info[town].add_gold(gold)
  700.     towns_info[town].add_people(people)
  701.     command = input()
  702.  
  703. command = input()
  704. while command != "End":
  705.     command_type, town_name, *info = [int(x) if x.isdigit() else x for x in command.split("=>")]
  706.     if command_type == "Plunder":
  707.         people, gold = info
  708.         towns_info[town_name].plunder(people, gold)
  709.     elif command_type == "Prosper":
  710.         gold = int(info[0])
  711.         towns_info[town_name].prosper(gold)
  712.     command = input()
  713.  
  714. if towns_info:
  715.     print(f"Ahoy, Captain! There are {len(towns_info.keys())} wealthy settlements to go to:")
  716.     for town in towns_info.values():
  717.         print(town)
  718. else:
  719.     print("Ahoy, Captain! All targets have been plundered and destroyed!")
  720.  
  721.  
  722.  
  723.  
  724.  
  725.  
  726.  
  727.  
  728.  
Add Comment
Please, Sign In to add comment