Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- regex info
- https://www.rexegg.com/regex-quickstart.html
- https://regex101.com/
- https://www.pythontutorial.net/python-regex/
- ##############################################
- 01. Programming Fundamentals Final Exam Retake
- 01. The Imitation Game
- main_string = input()
- command = input()
- def move_sting(number, string):
- return string[number:] + string[:number]
- def insert_string(index, value, string):
- return string[:index] + value + string[index:]
- def change_all(substring, replacement, string):
- return string.replace(substring, replacement)
- while command != "Decode":
- command_type, *info = [int(x) if x.isdigit() else x for x in command.split("|")]
- if command_type == "Move":
- number = info[0]
- main_string = move_sting(number, main_string)
- else:
- index_or_substring, value_or_replacement = info
- if command_type == "Insert":
- main_string = insert_string(index_or_substring, value_or_replacement, main_string)
- elif command_type == "ChangeAll":
- main_string = change_all(index_or_substring, value_or_replacement, main_string)
- command = input()
- print(f"The decrypted message is: {main_string}")
- 02. Ad Astra
- import re
- main_string = input()
- pattern = re.compile(r"([#|])(?P<item_name>[A-Za-z ]+)"
- r"\1(?P<exp_date>[0-9]{2}/[0-9]{2}/[0-9]{2})"
- r"\1(?P<calories>[0-9]{1,5})\1")
- calories_last = 0
- result_show = []
- result = re.finditer(pattern, main_string)
- for show in result:
- calories_last += int(show["calories"])
- result_show.append({"name": show["item_name"],
- "exp date": show["exp_date"],
- "calories": show["calories"]})
- calories_last = int(calories_last / 2000)
- print(f"You have food to last you for: {calories_last} days!")
- for show in result_show:
- print(f"Item: {show['name']}, Best before: {show['exp date']}, Nutrition: {show['calories']}")
- 03. The Pianist
- number_of_pieces = int(input())
- music_info = {}
- def piece_exists(piece_name):
- if piece_name in music_info:
- return True
- return False
- def add_music_info(piece_name, composer_name, key_name, first_input):
- if piece_exists(piece_name):
- if not first_input:
- print(f"{piece_name} is already in the collection!")
- return
- if not piece_exists(piece_name):
- music_info[piece_name] = music_info.get(piece_name, {})
- music_info[piece_name][key_name] = composer_name
- if not first_input:
- print(f"{piece_name} by {composer_name} in {key_name} added to the collection!")
- def remove_music_info(piece_name):
- if piece_exists(piece_name):
- del music_info[piece_name]
- print(f"Successfully removed {piece_name}!")
- return
- print(f"Invalid operation! {piece_name} does not exist in the collection.")
- def change_key(piece_name, key_name):
- if piece_exists(piece_name):
- _, name_compositor = music_info[piece_name].popitem()
- music_info[piece_name] = {}
- music_info[piece_name][key_name] = name_compositor
- print(f"Changed the key of {piece_name} to {key_name}!")
- return
- print(f"Invalid operation! {piece_name} does not exist in the collection.")
- def show_result():
- for piece_name in music_info:
- for key_name, name_compositor in music_info[piece_name].items():
- print(f"{piece_name} -> Composer: {name_compositor}, Key: {key_name}")
- for piece in range(number_of_pieces):
- piece_name, composer_name, key_name = input().split("|")
- add_music_info(piece_name, composer_name, key_name, True)
- command = input()
- while command != "Stop":
- command_type, *info = command.split("|")
- if command_type == "Remove":
- piece_name = info[0]
- remove_music_info(piece_name)
- elif command_type == "Add":
- piece_name, composer_name, key_name = info
- add_music_info(piece_name, composer_name, key_name, False)
- elif "ChangeKey" == command_type:
- piece_name, new_key = info
- change_key(piece_name, new_key)
- command = input()
- show_result()
- #######################################
- 02. Programming Fundamentals Final Exam
- 01. World Tour
- main_string = input()
- def valid_index(index):
- if 0 <= index < len(main_string):
- return True
- def add_stop(index, string, main_string):
- if valid_index(index):
- main_string = main_string[:index] + string + main_string[index:]
- return main_string
- def remove_stop(start_index, end_index, main_string):
- if valid_index(start_index) and valid_index(end_index):
- main_string = main_string[:start_index] + "" + main_string[end_index + 1:]
- return main_string
- def switch(old_string, new_string, main_string):
- if old_string in main_string:
- main_string = main_string.replace(old_string, new_string)
- return main_string
- command = input()
- while command != "Travel":
- command_type, index_or_old_string, string_or_end_index = [int(x) if x.isdigit() else x for x in command.split(":")]
- if "Add" in command_type:
- main_string = add_stop(index_or_old_string, string_or_end_index, main_string)
- elif "Remove" in command_type:
- main_string = remove_stop(index_or_old_string, string_or_end_index, main_string)
- elif "Switch" in command_type:
- main_string = switch(index_or_old_string, string_or_end_index, main_string)
- print(main_string)
- command = input()
- print(f"Ready for world tour! Planned stops: {main_string}")
- 02. Destination Mapper
- import re
- main_string = input()
- pattern = re.compile(r"([=/])(?P<location>[A-Z][a-zA-Z]{2,})\1")
- list_result = []
- result = re.finditer(pattern, main_string)
- total_travel_points = 0
- for show in result:
- total_travel_points += len(show["location"])
- list_result.append(show["location"])
- print(f"Destinations: {', '.join(list_result)}")
- print(f"Travel Points: {total_travel_points}")
- 03. Plant Discovery
- number_of_plants = int(input())
- plant_info = {}
- for plant in range(number_of_plants):
- plant_name, plant_rarity = input().split("<->")
- plant_info[plant_name] = plant_info.get(plant_name, {})
- plant_info[plant_name]["rarity"] = float(plant_rarity)
- plant_info[plant_name]["rating"] = []
- def check_plant_name(plant_name):
- if plant_name not in plant_info:
- print("error")
- return
- return True
- def rate_plant(plant, rating):
- if check_plant_name(plant):
- plant_info[plant]["rating"].append(rating)
- def update_plant(plant, new_rarity):
- if check_plant_name(plant):
- plant_info[plant]["rarity"] = new_rarity
- def reset_plant(plant):
- if check_plant_name(plant):
- plant_info[plant]["rating"] = []
- def show_result():
- print("Plants for the exhibition:")
- for plant in plant_info:
- average = 0.00
- if sum(plant_info[plant]["rating"]) != 0:
- average = sum(plant_info[plant]["rating"]) / len(plant_info[plant]["rating"])
- print(f"- {plant}; Rarity: {plant_info[plant]['rarity']:.0f}; Rating: {average:.2f}")
- command = input()
- while command != "Exhibition":
- if "Reset" in command:
- _, plant = command.split(": ")
- reset_plant(plant)
- command = input()
- continue
- plant, rating_or_new_rarity = [float(x) if x.isdigit() else x for x in command.split(": ")[1].split(" - ")]
- if "Rate" in command:
- rate_plant(plant, rating_or_new_rarity)
- elif "Update" in command:
- update_plant(plant, rating_or_new_rarity)
- command = input()
- show_result()
- ##############################################
- 03. Programming Fundamentals Final Exam Retake
- 01. Secret Chat
- main_string = input()
- command = input()
- def insert_space(index, main_string):
- return main_string[:index] + " " + main_string[index:]
- def reverse_(substring, main_string):
- word_find = main_string.find(substring)
- main_string = main_string[:word_find] + main_string[word_find + len(substring):]
- main_string += substring[::-1]
- return main_string
- def change_all(substring, replacement, main_string):
- return main_string.replace(substring, replacement)
- while command != "Reveal":
- command_type, *info = command.split(":|:")
- found_error = False
- if command_type == "ChangeAll":
- substring, replacement = info
- main_string = change_all(substring, replacement, main_string)
- else:
- if command_type == "Reverse":
- substring = info[0]
- if substring not in main_string:
- print("error")
- found_error = True
- else:
- main_string = reverse_(substring, main_string)
- elif "InsertSpace" == command_type:
- index_ = int(info[0])
- main_string = insert_space(index_, main_string)
- if not found_error:
- print(main_string)
- command = input()
- print(f"You have a new text message: {main_string}")
- 02. Mirror Words
- import re
- main_string = input()
- pattern = re.compile(r"([@#])(?P<word>[A-Za-z]{3,})\1\1(?P<word2>[A-Za-z]{3,})\1")
- list_result = []
- result = list(re.finditer(pattern, main_string))
- for show in result:
- if show["word"] == show["word2"][::-1]:
- list_result.append(f"{show['word']} <=> {show['word2']}")
- if result:
- print(f"{len(result)} word pairs found!")
- if list_result:
- print("The mirror words are:")
- print(*list_result, sep=", ")
- else:
- print("No mirror words!")
- else:
- print("No word pairs found!")
- print("No mirror words!")
- 03. Need for Speed III
- car_numbers = int(input())
- car_info = {}
- class Car:
- def __init__(self, name):
- self.name = name
- self.mileage = 0
- self.fuel = 0
- def add_mileage(self, mileage):
- self.mileage += mileage
- def add_fuel(self, fuel):
- self.fuel += fuel
- def drive(self, distance, fuel):
- if self.fuel > fuel:
- self.fuel -= fuel
- self.mileage += distance
- print(f"{self.name} driven for {distance} kilometers. {fuel} liters of fuel consumed.")
- if self.mileage >= 100_000:
- del car_info[self.name]
- print(f"Time to sell the {self.name}!")
- else:
- print("Not enough fuel to make that ride")
- def refuel(self, fuel):
- if self.fuel + fuel > 75:
- fuel = 75 - self.fuel
- self.fuel += fuel
- print(f"{self.name} refueled with {fuel} liters")
- def revert(self, kilometers):
- self.mileage -= kilometers
- if self.mileage < 10_000:
- self.mileage = 10_000
- return
- print(f"{self.name} mileage decreased by {kilometers} kilometers")
- def __repr__(self):
- return f"{self.name} -> Mileage: {self.mileage} kms, Fuel in the tank: {self.fuel} lt."
- for car in range(car_numbers):
- car_name, mileage, fuel = [int(x) if x.isdigit() else x for x in input().split("|")]
- car_info[car_name] = car_info.get(car_name, Car(car_name))
- car_info[car_name].add_mileage(mileage)
- car_info[car_name].add_fuel(fuel)
- command = input()
- while command != "Stop":
- command_type, car_name, *info = [int(x) if x.isdigit() else x for x in command.split(" : ")]
- if command_type == "Drive":
- distance, fuel = info
- car_info[car_name].drive(distance, fuel)
- elif command_type == "Refuel":
- fuel = info[0]
- car_info[car_name].refuel(fuel)
- elif command_type == "Revert":
- kilometers = info[0]
- car_info[car_name].revert(kilometers)
- command = input()
- for car in car_info.values():
- print(car)
- ########################################
- 04. Programming Fundamentals Final Exam
- 01. Password Reset
- main_string = input()
- command = input()
- def take_odd_char(main_string):
- return "".join(main_string[i] for i in range(len(main_string)) if i % 2 != 0)
- def cut_string(index, length, main_string):
- return main_string[:index] + main_string[index + length:]
- def substitute(substring, substitute, main_string):
- return main_string.replace(substring, substitute)
- while command != "Done":
- nothing_to_replace = False
- if "TakeOdd" in command:
- main_string = take_odd_char(main_string)
- else:
- _, index_or_substring, length_or_substitute = [int(x) if x.isdigit() else x for x in command.split()]
- if "Cut" in command:
- main_string = cut_string(index_or_substring, length_or_substitute, main_string)
- elif "Substitute" in command:
- if index_or_substring in main_string:
- main_string = substitute(index_or_substring, length_or_substitute, main_string)
- else:
- print("Nothing to replace!")
- nothing_to_replace = True
- if not nothing_to_replace:
- print(main_string)
- command = input()
- print(f"Your password is: {main_string}")
- 02. Fancy Barcodes
- import re
- number_products = int(input())
- pattern = re.compile(r"@[#]+(?P<found_text>[A-Z][a-zA-Z0-9]{4,}[A-Z])@[#]+")
- for product_input in range(number_products):
- bar_code = input()
- find_result = re.finditer(pattern, bar_code)
- found = False
- for show in find_result:
- found = True
- result_print = ''.join(x for x in show["found_text"] if x.isdigit())
- if result_print:
- print(f"Product group: {result_print}")
- else:
- print(f"Product group: 00")
- if not found:
- print("Invalid barcode")
- 03. Heroes of Code and Logic VII
- number_heroes = int(input())
- heroes_info = {}
- class Heroes:
- def __init__(self, name):
- self.name = name
- self.hp = 0
- self.mp = 0
- def add_hp(self, hp):
- self.hp += hp
- def add_mp(self, mp):
- self.mp += mp
- def cast_spall(self, mp_need, spell_name):
- if self.mp >= mp_need:
- self.mp -= mp_need
- return f"{self.name} has successfully cast {spell_name} and now has {self.mp} MP!"
- return f"{self.name} does not have enough MP to cast {spell_name}!"
- def take_damage(self, damage, attacker):
- self.hp -= damage
- if self.hp > 0:
- return f"{self.name} was hit for {damage} HP by {attacker} and now has {self.hp} HP left!"
- del heroes_info[self.name]
- return f"{self.name} has been killed by {attacker}!"
- def recharge(self, amount):
- if self.mp + amount > 200:
- amount = 200 - self.mp
- self.mp += amount
- return f"{self.name} recharged for {amount} MP!"
- def heal(self, amount):
- if self.hp + amount > 100:
- amount = 100 - self.hp
- self.hp += amount
- return f"{self.name} healed for {amount} HP!"
- def __repr__(self):
- return f"{self.name}\n " \
- f"HP: {self.hp}\n " \
- f"MP: {self.mp}"
- for hero in range(number_heroes):
- hero_name, hp, mp = [int(x) if x.isdigit() else x for x in input().split()]
- heroes_info[hero_name] = heroes_info.get(hero_name, Heroes(hero_name))
- heroes_info[hero_name].add_hp(hp)
- heroes_info[hero_name].add_mp(mp)
- command = input()
- while command != "End":
- command_type, hero_name, *info = [int(x) if x.isdigit() else x for x in command.split(" - ")]
- if command_type == "Heal":
- hp = info[0]
- print(heroes_info[hero_name].heal(hp))
- elif command_type == "Recharge":
- mp = info[0]
- print(heroes_info[hero_name].recharge(mp))
- elif command_type == "TakeDamage":
- damage, attacker = info
- print(heroes_info[hero_name].take_damage(damage, attacker))
- elif command_type == "CastSpell":
- mp_need, spell_name = info
- print(heroes_info[hero_name].cast_spall(mp_need, spell_name))
- command = input()
- for hero in heroes_info.values():
- print(hero)
- ########################################
- 05. Programming Fundamentals Final Exam
- 01. Activation Keys
- main_string = input()
- def contains(substring, main_string):
- if substring in main_string:
- return f"{main_string} contains {substring}"
- return "Substring not found!"
- def flip(type_flip, start_index, end_index, main_string):
- if type_flip == "Upper":
- result = main_string[:start_index] + \
- main_string[start_index:end_index].upper() + \
- main_string[end_index:]
- elif type_flip == "Lower":
- result = main_string[:start_index] + \
- main_string[start_index:end_index].lower() + \
- main_string[end_index:]
- return result
- def slice_(start_index, end_index, main_string):
- return main_string[:start_index] + main_string[end_index:]
- command = input()
- while command != "Generate":
- command_name, *info = command.split(">>>")
- if command_name == "Contains":
- substring = info[0]
- print(contains(substring, main_string))
- elif command_name == "Flip":
- type_flip, start_index, end_index = info
- main_string = flip(type_flip, int(start_index), int(end_index), main_string)
- elif command_name == "Slice":
- start_index, end_index = info
- main_string = slice_(int(start_index), int(end_index), main_string)
- if "Contains" != command_name:
- print(main_string)
- command = input()
- print(f"Your activation key is: {main_string}")
- 02. Emoji Detector
- import re
- main_string = input()
- # all_digits = ''.join(re.findall(r"\d+", main_string))
- all_digits = ''.join(x for x in main_string if x.isdigit())
- cool_threshold = 1
- for num in all_digits:
- cool_threshold *= int(num)
- patterns = re.compile(r"(::|\*\*)(?P<emoji>[A-Z][a-z]{2,})\1")
- print(f"Cool threshold: {cool_threshold}")
- result = list(re.finditer(patterns, main_string))
- print(f"{len(result)} emojis found in the text. The cool ones are:")
- for found in result:
- find_cool = 0
- for letter in found["emoji"]:
- find_cool += ord(letter)
- if find_cool >= cool_threshold:
- print(found[0])
- 03. P!rates
- towns_info = {}
- class Town:
- def __init__(self, name):
- self.name = name
- self.population = 0
- self.gold = 0
- def add_people(self, people):
- self.population += people
- def add_gold(self, gold):
- self.gold += gold
- def plunder(self, people, gold):
- self.population -= people
- self.gold -= gold
- print(f"{self.name} plundered! {gold} gold stolen, {people} citizens killed.")
- if self.population <= 0 or self.gold <= 0:
- del towns_info[self.name]
- print(f"{self.name} has been wiped off the map!")
- def prosper(self, gold):
- if gold < 0:
- print("Gold added cannot be a negative number!")
- else:
- self.gold += gold
- print(f"{gold} gold added to the city treasury. {self.name} now has {self.gold} gold.")
- def __repr__(self):
- return f"{self.name} -> Population: {self.population} citizens, Gold: {self.gold} kg"
- command = input()
- while command != "Sail":
- town, people, gold = [int(x) if x.isdigit() else x for x in command.split("||")]
- towns_info[town] = towns_info.get(town, Town(town))
- towns_info[town].add_gold(gold)
- towns_info[town].add_people(people)
- command = input()
- command = input()
- while command != "End":
- command_type, town_name, *info = [int(x) if x.isdigit() else x for x in command.split("=>")]
- if command_type == "Plunder":
- people, gold = info
- towns_info[town_name].plunder(people, gold)
- elif command_type == "Prosper":
- gold = int(info[0])
- towns_info[town_name].prosper(gold)
- command = input()
- if towns_info:
- print(f"Ahoy, Captain! There are {len(towns_info.keys())} wealthy settlements to go to:")
- for town in towns_info.values():
- print(town)
- else:
- print("Ahoy, Captain! All targets have been plundered and destroyed!")
Add Comment
Please, Sign In to add comment