Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Exam3."""
- from typing import List, Tuple, Optional
- import re
- def sum_nums(num1: int, num2: int) -> List:
- """
- Sum two numbers as an integer and as a string.
- #01
- sum_nums(1, 2) -> [3, '12']
- sum_nums(12, 34) -> [46, '1234']
- sum_nums(33, 44) -> [77, '3344']
- sum_nums(0, 0) -> [0, '00']
- :param num1: Given non-negative integer
- :param num2: Given non-negative integer
- :return: Sums of num1, num2; list with one integer and one string.
- """
- return [num1 + num2, str(num1) + str(num2)]
- def numbers_in_list(number1: int, number2: int, numbers: List[int]) -> int:
- """
- Given two integers and a list, return the required result.
- #02
- Return sum of the two numbers if both numbers are in the given list.
- If only one of these numbers is in the list, return that number minus the other number.
- If both of them are not in the list, return product of their multiplication, unless they differ from 0 equally,
- then return 0.
- numbers_in_list(3, 5, [5, 6, 3, 1]) -> 8
- numbers_in_list(0, 2, [3, 2, 9]) -> 2
- numbers_in_list(0, 2, [3, 0, 9]) -> -2
- numbers_in_list(3, 6, [5, 9, 8]) -> 18
- numbers_in_list(9, 9, [0, 6, 32]) -> 0
- :param number1: First given number
- :param number2: Second given number
- :param numbers: Given list
- :return: Required result.
- """
- if number1 in numbers and number2 in numbers:
- return number1 + number2
- elif number1 in numbers and number2 not in numbers:
- return number1 - number2
- elif number2 in numbers and number1 not in numbers:
- return number2 - number1
- elif number1 not in numbers and number2 not in numbers and abs(number1) != abs(number2):
- return number1 * number2
- elif number1 not in numbers and number2 not in numbers and abs(number1) == abs(number2):
- return 0
- def multiply_after_digit(s: str) -> str:
- """
- Given a string where the number before letter stands for its quantity, return the result string.
- #03
- You get 80% (40 points out of 50) if the function works with one digit. To get 100%, is should also work with more digits.
- multiply_after_digit('a5b4c') -> 'abbbbbcccc'
- multiply_after_digit('2 0nhe2lo world3!') -> ' hello world!!!'
- multiply_after_digit('thi10s end3s wit3h 31') -> 'thissssssssss endsss withhh ' (to get 100%)
- :param s: Given input string
- :return: Result string.
- """
- string = ""
- pattern = r"\d+\s|\s|\d+[^\d]|[^\d]"
- mps = [n for n in re.findall(pattern, s)]
- print(mps)
- for i in mps:
- if len(i) == 1:
- try:
- if int(i) and i != " ":
- return string
- except ValueError:
- string += i
- elif len(i) > 1:
- if i[-1] == " ":
- string += i[-1] * int(i[:-1])
- try:
- if int(i) and i[-1] != " ":
- return string
- except ValueError:
- string += i[-1] * int(i[:-1])
- return string
- def mastermind_guess(solution: List[int], guess: List[int]) -> List[int]:
- """
- Return the result of the guess in Mastermind game.
- #04
- Mastermind is a game where the player tries to guess the correct order of numbers.
- The function has a parameter solution, which indicates the correct order of elements.
- All the elements are positive numbers, there are no duplicate elements in the solution.
- The parameter guess indicates a guess by the player.
- The length of the solution and guess is always the same.
- The function should return the outcome of the guess,
- where for every element in guess there is a number in the result:
- - 2 if the given element in guess was in the correct position (in solution)
- - 1 if the given element in guess is in solution, but not in the correct position,
- - 0 if the given element is not in the solution.
- The length of the solution (and guess) is at least 1.
- Examples:
- mastermind_guess([1, 2, 3], [1, 2, 3]) => [2, 2, 2]
- mastermind_guess([1, 2, 3], [3, 1, 2]) => [1, 1, 1]
- mastermind_guess([1, 2, 3], [3, 3, 3]) => [1, 1, 2]
- mastermind_guess([1, 2], [7, 3]) => [0, 0]
- :param solution: Non-empty list of positive integers.
- :param guess: Non-empty list of positive integers.
- :return: Result for the guess.
- """
- answer = []
- for n in range(0, len(solution)):
- if solution[n] == guess[n]:
- answer.append(2)
- elif guess[n] in solution:
- answer.append(1)
- else:
- answer.append(0)
- return answer
- def reformat_money(data: dict) -> dict:
- """
- Reformat data in dictionary.
- #05
- Dictionary represents money (integers) as keys and people's names (strings) as values.
- You should switch key-value pairs in dictionary, to know, how much money each person has.
- There can be different money entries with same names, you have to sum the money for each person.
- If a persons name contains the words james or bond (non-case sensitive), double the money to be added.
- The order of the dict is not important.
- reformat_money({10: 'A', 20: 'B', 30: 'a', 40: 'A', 50: 'James'}) => {'A': 50, 'B': 20, 'a': 30, 'James': 100}
- :param data: Dictionary with data
- :return: Dictionary with reformatted data.
- """
- new_dict = {}
- keys = [i for i in data.keys()]
- values = [i for i in data.values()]
- for i in range(len(keys)):
- if values[i].lower() == "james" or values[i].lower() == "bond" and values[i] not in new_dict:
- new_dict[values[i]] = keys[i] * 2
- elif values[i].lower() == "james" or values[i].lower() == "bond":
- new_dict[values[i]] += keys[i] * 2
- elif values[i] not in new_dict:
- new_dict[values[i]] = keys[i]
- else:
- new_dict[values[i]] += keys[i]
- return new_dict
- def collatz_conjecture(num: int, i=0, max_term=0) -> Optional[Tuple[int, int]]:
- """
- Given integer, return the number of steps Collatz sequence needed to reach 1 and the biggest term on the way.
- #06
- The solution has to be recursive!
- The Collatz conjecture is a conjecture that concerns a sequence that started with any positive integer n.
- If the previous term is even, the next term is previous term / 2.
- If the previous term is odd, the next term is 3 * previous term + 1.
- The conjecture states that no matter what value of n, the sequence will always reach 1.
- collatz_conjecture(12) -> 9, 16 (sequence is [12, 6, 3, 10, 5, 16, 8, 4, 2, 1], steps - 9, biggest term - 16)
- collatz_conjecture(1) -> 0, 1 (sequence is [1], steps - 0, biggest term - 1)
- collatz_conjecture(27) -> 111, 9232
- collatz_conjecture(670617279) -> 949, 966616035460 (close to the border of RecursionError, but should still work)
- collatz_conjecture(0) -> None
- :param num: Given integer
- :return: Tuple with length of sequence and biggest term or None if input is not valid.
- """
- if num <= 0:
- return None
- if num > max_term:
- max_term = num
- if num == 1:
- return i, max_term
- elif num > 1:
- i += 1
- if num % 2 == 0:
- num = num // 2
- return collatz_conjecture(num, i, max_term)
- else:
- num = 3 * num + 1
- return collatz_conjecture(num, i, max_term)
- def plot_the_tangerines(integers: List[int]) -> str:
- """
- Given list of non-negative integers create a bar graph.
- #07
- Recently you have noticed that your consumption of tangerines is too high.
- You want to monitor the situation so you try to make a bar graph of tangerines consumption in Excel.
- But Excel won't work, because you have just started using Linux.
- Oh well, it seems that you have to make your own program to plot graphs and do fancy calculations.
- Graph consists of scale (left) and stack of '#'s that represent integer in the list (consumed tangerines in a day).
- 0 means stack of 0 '#', 1 means stack of 1 '#', 2 means stack of 2 '#' and so on.
- Graph max height should be the maximum value from the list, max is always at least 1.
- There is always at least one element in the list.
- Graph needs to be in a frame consisting of '|', '-' and '+' characters as shown in examples.
- There should be no newlines before or after the graph.
- plot_the_tangerines([1, 0, 2, 3, 4, 5, 4, 3, 2, 1, 0, 3, 2, 1]) =>
- +--------------+
- 5| # |
- 4| ### |
- 3| ##### # |
- 2| ####### ## |
- 1|# ######## ###|
- 0+--------------+
- plot_the_tangerines([0]) =>
- +-+
- 1+ +
- 0+-+
- plot_the_tangerines([0, 0, 0, 0, 0, 0])) =>
- +------+
- 1| |
- 0+------+
- plot_the_tangerines([1, 4, 5, 3, 1]) =>
- +-----+
- 5| # |
- 4| ## |
- 3| ### |
- 2| ### |
- 1|#####|
- 0+-----+
- In case the maximum value is is more than 9, the left side should be wider, aligned to right:
- +-----
- 100|
- 99|
- ....
- 9|#
- 8|#
- ...
- 0+-----
- all.
- """
- nr_len = len(str(max(integers)))
- upper = f"{' ' * nr_len}+{'-' * len(integers)}+"
- lower = f"{' ' * (nr_len - 1)}0+{'-' * len(integers)}+"
- fill = [f"{' ' * (nr_len - 1)}{i}|{' ' * len(integers)}|" if i <= 9 else f"{' ' * (nr_len - 2)}{i}|{' ' * len(integers)}|" for i in range(1, max(integers) + 1)]
- fill.reverse()
- # upper = f" +{'-' * len(integers)}+"
- # lower = f"0+{'-' * len(integers)}+"
- # fill = [f"{i}|{' ' * len(integers)}|" for i in range(1, max(integers) + 1)]
- # fill.reverse()
- lines = ""
- if not fill:
- lines = f"1|{' ' * len(integers)}|" + "\n"
- for n in range(len(integers)):
- for l in range(len(fill)):
- if help_func2(fill[l]) <= integers[n]:
- length = len(str(help_func2(fill[l])))
- fill[l] = fill[l][:n + 1 + length] + "#" + fill[l][n + 2 + length:]
- # line[n + 2].replace("#", line[n + 2])
- for line in fill:
- lines += line + "\n"
- table = upper + "\n" + lines + lower
- return table
- # upper = f" +{'-' * len(integers)}+"
- # lower = f"0+{'-' * len(integers)}+"
- # fill = [f"{i}|{' ' * len(integers)}|" for i in range(1, max(integers) + 1)]
- # fill.reverse()
- # lines = ""
- # if not fill:
- # lines = f"1|{' ' * len(integers)}|" + "\n"
- # for n in range(len(integers)):
- # for l in range(len(fill)):
- # if int(fill[l][0]) <= integers[n]:
- # fill[l] = fill[l][:n + 2] + "#" + fill[l][n + 3:]
- # # line[n + 2].replace("#", line[n + 2])
- # for line in fill:
- # lines += line + "\n"
- # table = upper + "\n" + lines + lower
- # return table
- def help_func2(line):
- """Help."""
- return int([n for n in re.findall(r"\d+", line)][0])
- # 08 - OOP1 - transport
- class Passenger:
- """Class that defines passenger object."""
- def __init__(self, first_name: str, age: int):
- """
- Initialize passenger.
- self.is_validated - when passenger arrives to the vehicle, they should validate themselves.
- If the passenger doesn't do that and inspector arrives, the passenger will be kicked out from the vehicle.
- self.vehicle - describes vehicle, where passenger is at the moment.
- One passenger can't be on multiple vehicles at the same time.
- :param first_name: Passenger's first name.
- :param age: Passenger's age.
- """
- self.first_name = first_name
- self.age = age
- self.is_validated = False
- self.vehicle = None
- def validate(self):
- """Validate passenger."""
- self.is_validated = True
- class PublicTransportVehicle:
- """Class that defines public transport vehicle object."""
- def __init__(self, seats: int):
- """
- Initialize vehicle.
- :param seats: Amount of seats in the public transport vehicle. If the amount of seats is smaller than 0, then it should be determined that there is 1 seat in the vehicle.
- Vehicle driver does not need a seat.
- """
- self.seats = seats
- self.passengers = []
- if self.seats <= 0:
- self.seats = 1
- def get_amount_of_people(self) -> int:
- """
- Return amount of people in the bus including the vehicle driver.
- Assume that driver is always in the vehicle.
- :return: Amount of people as integer.
- """
- return len(self.passengers) + 1
- def get_all_passengers(self) -> List:
- """
- Return the list of passengers.
- :return: Passengers as list.
- """
- return self.passengers
- def add_new_passenger(self, passenger: Passenger) -> bool:
- """
- Register new passenger if there is a seat for him/her.
- :return: True if passenger can be added, otherwise (if not enough seats or passenger is already there) False.
- """
- if len(self.passengers) < self.seats and passenger not in self.passengers:
- self.passengers.append(passenger)
- return True
- return False
- def release_passenger(self, passenger: Passenger):
- """Release passenger (passenger leaves the vehicle)."""
- self.passengers.remove(passenger) if passenger in self.passengers else None
- def inspector_arrival(self):
- """All passengers, who are not validated, will be kicked out from vehicle."""
- self.passengers = [p for p in self.passengers if p.is_validated]
- # 09 - OOP2 - village
- class Building:
- """Represents one building."""
- def __init__(self, name: str, resources: dict):
- """Initialize building."""
- self.name = name
- self.resources = resources
- self.level = 1
- def upgrade(self):
- """Upgrade building."""
- self.level += 1
- def downgrade(self):
- """Downgrade building."""
- self.level -= 1
- def get_name(self):
- """Return building name."""
- return self.name
- def get_level(self):
- """Return building level."""
- return self.level
- def __repr__(self):
- """Representation of Building."""
- return f"{self.name} ({self.level})"
- class Village:
- """Represents village."""
- def __init__(self, name: str, resources: dict):
- """Constructor."""
- self.name = name
- self.resources = resources
- self.buildings = [Building("Main building", {"Wood": 200, "Clay": 200, "Iron": 200, "Wheat": 200})]
- def can_build(self, resources_needed: dict):
- """True if can build building, else False."""
- if self.resources["Wood"] - resources_needed["Wood"] >= 0 and self.resources["Clay"] - \
- resources_needed["Clay"] >= 0 and self.resources["Iron"] - \
- resources_needed["Iron"] >= 0 and self.resources["Wheat"] - resources_needed["Wheat"] >= 0:
- return True
- return False
- def build_building(self, resources_needed: dict, name: str) -> bool:
- """
- Build building.
- You can build a building if there is room for a new building in the village and you have enough resources.
- There can't be multiple buildings with the same name and name can't be empty.
- If you can build the building, build it and add it the buildings list.
- Return True if building was successful, else False.
- :param resources_needed: Resources needed for building the building.
- :param name: Name of the building to be built.
- :return: True if building was successful, else False.
- """
- if len(self.buildings) <= 20 and self.can_build(resources_needed):
- self.buildings.append(Building(name, resources_needed))
- self.resources["Wood"] -= resources_needed["Wood"]
- self.resources["Clay"] -= resources_needed["Clay"]
- self.resources["Iron"] -= resources_needed["Iron"]
- self.resources["Wheat"] -= resources_needed["Wheat"]
- return True
- return False
- def downgrade_building(self, building_name: str) -> bool:
- """
- Downgrade building.
- Building can be downgraded if it's in the village. If the building's level is 1 and it is being downgraded,
- demolish it (remove completely from village).
- If it's the Main Building, its level can't be lower than 1.
- Return True if downgrading was successful, else False.
- :param building_name: Name of the building to be downgraded.
- :return: True if downgrading was successful, else False.
- """
- if self.get_building_by_name(building_name):
- building = self.get_building_by_name(building_name)
- if building_name.lower() != "main building" and building.level == 1:
- self.buildings.remove(building)
- elif building_name.lower() == "main building" and building.level == 1:
- return False
- else:
- building.downgrade()
- return False
- def can_upgrade(self, building):
- """Returns True if can upgrade building, else False."""
- if self.resources["Wood"] - ((10 + (building.level + 1) * 4) % building.resources["Wood"]) >= 0 and \
- self.resources["Clay"] - ((10 + (building.level + 1) * 4) % building.resources["Clay"]) >= 0 and \
- self.resources["Iron"] - ((10 + (building.level + 1) * 4) % building.resources["Iron"]) >= 0 and \
- self.resources["Wheat"] - ((10 + (building.level + 1) * 4) % building.resources["Wheat"]) >= 0:
- return True
- return False
- def upgrade_building(self, building_name: str) -> bool:
- """
- Upgrade building.
- Building can be upgraded if its level is not equal to them Main Building's level less than 20
- and there is enough resources in the village for the upgrade.
- Return True if upgrading was successful, else False.
- :param building_name: Name of the building to be upgraded.
- # :param resources_needed: Resources needed for the upgrade.
- :return: True if upgrading was successful, else False.
- """
- # (10 + level * 4)% ehitise algsest maksumusest
- if self.get_building_by_name(building_name):
- building = self.get_building_by_name(building_name)
- main_building = self.get_building_by_name("Main building")
- if self.can_upgrade(building) and building.level <= 19 and \
- (building.level + 1 > main_building.level or building == main_building):
- self.resources["Wood"] -= (10 + (building.level + 1) * 4) % building.resources["Wood"]
- self.resources["Clay"] -= (10 + (building.level + 1) * 4) % building.resources["Clay"]
- self.resources["Iron"] -= (10 + (building.level + 1) * 4) % building.resources["Iron"]
- self.resources["Wheat"] -= (10 + (building.level + 1) * 4) % building.resources["Wheat"]
- building.upgrade()
- return False
- def get_building_by_name(self, name: str) -> Building:
- """Return Building object corresponding to the given name. If no such building, return None."""
- b_names = [b.name.lower() for b in self.buildings]
- if name.lower() in b_names:
- for b in self.buildings:
- if b.name.lower() == name.lower():
- return b
- return None
- def get_resources(self) -> dict: # ?
- """Return the dict of resources."""
- return self.resources
- def add_resources(self, resources_to_add: dict):
- """Add resources to the resource dict."""
- self.resources["Wood"] += resources_to_add["Wood"]
- self.resources["Clay"] += resources_to_add["Clay"]
- self.resources["Iron"] += resources_to_add["Iron"]
- self.resources["Wheat"] += resources_to_add["Wheat"]
- def get_buildings(self) -> list:
- """Return buildings."""
- return self.buildings
- def __repr__(self) -> str:
- """Village representation."""
- return f"Village: {self.name}, Buildings: {self.buildings}"
- def group_the_minions(group_sizes: List[int]) -> List[List[int]]:
- """
- You have to split minions into different groups.
- #10
- Each minion belongs to one certain group.
- You are given an array of numbers, which represents the size of the group in which the Minion belongs to.
- Put the minions into the right sized group. The order of groups (lists inside lists) does not matter.
- Example:
- group_the_minions([3,3,3,3,3,1,3]) -> [[5],[0,1,2],[3,4,6]]
- and this would also be correct as order does not matter -> [[0,1,2],[3,4,6], [5]]
- group_the_minions([2, 2]) -> [[0, 1]].
- """
- final_list = []
- for i in range(len(group_sizes)):
- if not final_list:
- final_list.append([i])
- else:
- for f in final_list:
- if len(f) < group_sizes[i]:
- f.append(i)
- if help_func(final_list, i):
- final_list.append([i])
- return final_list
- def help_func(listy, i):
- """Help func."""
- for l in listy:
- if i in l:
- return False
- return True
- if __name__ == "__main__":
- # print(sum_nums(1, 2)) # -> [3, '12']
- # print(sum_nums(12, 34)) # -> [46, '1234']
- # print(sum_nums(33, 44)) # -> [77, '3344']
- # print(sum_nums(0, 0)) # -> [0, '00']
- # print(numbers_in_list(3, 5, [5, 6, 3, 1])) # -> 8
- # print(numbers_in_list(0, 2, [3, 2, 9])) # -> 2
- # print(numbers_in_list(0, 2, [3, 0, 9])) # -> -2
- # print(numbers_in_list(3, 6, [5, 9, 8])) # -> 18
- # print(numbers_in_list(9, 9, [0, 6, 32])) # -> 0
- # print(multiply_after_digit('a5b4c')) # -> 'abbbbbcccc'
- # print(multiply_after_digit('2 0nhe2lo world3!')) # -> ' hello world!!!'
- # print(multiply_after_digit('thi10s end3s wit3h 31')) # -> 'thissssssssss endsss withhh '(to get 100 %)
- # print(mastermind_guess([1, 2, 3], [1, 2, 3])) # = > [2, 2, 2]
- # print(mastermind_guess([1, 2, 3], [3, 1, 2])) # = > [1, 1, 1]
- # print(mastermind_guess([1, 2, 3], [3, 3, 3])) # = > [1, 1, 2]
- # print(mastermind_guess([1, 2], [7, 3])) # = > [0, 0]
- # print(reformat_money({10: 'A', 20: 'B', 30: 'a', 40: 'A', 50: 'James'})) # => {'A': 50, 'B': 20, 'a': 30,
- # 'James': 100}
- # print(collatz_conjecture(12)) # -> 9, 16(sequence is [12, 6, 3, 10, 5, 16, 8, 4, 2, 1], steps - 9, biggestterm -
- # # 16)
- # print(collatz_conjecture(1)) # -> 0, 1(sequence is [1], steps - 0, biggestterm - 1)
- # print(collatz_conjecture(27)) # -> 111, 9232
- # print(collatz_conjecture(670617279)) # -> 949,
- # 966616035460(closetotheborderofRecursionError, butshould stillwork)
- # print(collatz_conjecture(0)) # -> None
- print(plot_the_tangerines([1, 0, 2, 3, 4, 5, 4, 3, 2, 10, 0, 3, 2, 1])) # = >
- # +--------------+
- # 5| # |
- # 4| ### |
- # 3| ##### # |
- # 2| ####### ## |
- # 1|# ######## ###|
- # 0+--------------+
- print(plot_the_tangerines([0])) # = >
- # +-+
- # 1+ +
- # 0+-+
- print(plot_the_tangerines([0, 0, 0, 0, 0, 0])) # = >
- # +------+
- # 1| |
- # 0+------+
- print(plot_the_tangerines([1, 4, 5, 3, 1])) # = >
- # +-----+
- # 5| # |
- # 4| ## |
- # 3| ### |
- # 2| ### |
- # 1|#####|
- # 0+-----+
- print(group_the_minions([3, 3, 3, 3, 3, 1, 3])) # -> [[5],[0,1,2],[3,4,6]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement