Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Exam 4."""
- def power_of_nums(nums: list) -> int:
- """
- Given an array of integers, return the first element in power of the second to the last element in array.
- #01
- You do not have to check if the input is valid.
- assert power_of_nums([1, 2, 3, 4]) == 1
- assert power_of_nums([3, 4, 5]) == 81
- assert power_of_nums([2, 5]) == 4
- assert power_of_nums([-2, -3, -4]) == -0.125
- assert power_of_nums([0, 0]) == 1
- :param nums: list of integers.
- :return: first element in power of second to last element.
- """
- return nums[0] ** nums[-2]
- print(power_of_nums([3, 4, 5]))
- print(power_of_nums([0, 0]))
- def which_number(num: int) -> str:
- """
- Decide what kind of number you are given.
- #02
- If the number is even, return string saying EVEN unless the
- number is palindromic, in that case return string saying EVEN PALINDROMIC.
- Palindromic numbers are positive numbers that remain the same when their digits are reversed.
- For example 22, 33, 121, 1234321 etc.
- The same applies to odd numbers, but in addition to that in case the odd
- number is a square number you should add INTERESTING to the output.
- In other cases, if the odd number is not a square number add BORING to the output.
- The order of the words must be EVEN/ODD, INTERESTING/BORING, PALINDROMIC
- Be careful with negative numbers!
- assert which_number(20) == "EVEN"
- assert which_number(-2) == "EVEN"
- assert which_number(-9) == "ODD BORING"
- assert which_number(5) == "ODD BORING PALINDROMIC"
- assert which_number(121) == "ODD INTERESTING PALINDROMIC"
- assert which_number(16) == "EVEN"
- :param num: -infinity < num < +infinity.
- :return: String saying some of these words EVEN, ODD, INTERESTING, BORING, PALINDROMIC
- depending on the input.
- """
- import math
- snum = str(num)
- reversed = snum[::-1]
- if num % 2 == 0:
- if str(num) == reversed and num > 0:
- return "EVEN PALIDROMIC"
- else:
- return "EVEN"
- elif num % 2 != 0:
- if num > 0:
- sqrt = math.sqrt(num)
- if num > 0 and sqrt == sqrt // 1 and str(num) == reversed:
- return "ODD INTERESTING PALINDROMIC"
- if num > 0 and sqrt == sqrt // 1:
- return "ODD INTERESTING"
- if num > 0 and str(num) == reversed:
- return "ODD BORING PALINDROMIC"
- if num < 0:
- return "ODD BORING"
- print(which_number(20)) # == "EVEN"
- print(which_number(-2)) # == "EVEN"
- print(which_number(-9)) # == "ODD BORING"
- print(which_number(5)) # == "ODD BORING PALINDROMIC"
- print(which_number(121)) # == "ODD INTERESTING PALINDROMIC"
- print(which_number(16)) # == "EVEN"
- def count_double_chars(s: str) -> int:
- """
- Count only double symbols.
- #03
- Count how many double symbols are in the text. You have to only count pairs.
- Therefore, pair of symbols which is not preceded or followed by the same symbol.
- If there are three or more of the same symbol, then this is not a pair and doesn't count.
- Any printable symbol counts (letters, digits, punctuation, space etc).
- assert count_double_chars("abc") == 0
- assert count_double_chars("aabc") == 1
- assert count_double_chars("aaabc") == 0 # (three "a"-s doesn't count)
- assert count_double_chars("aaaabc") == 0 # (four "a"-s also doesn't count)
- assert count_double_chars("aabbc") == 2
- assert count_double_chars("") == 0
- assert count_double_chars("abbcdd") == 2
- assert count_double_chars("aabbaa") == 3
- assert count_double_chars(",,!?") == 1
- assert count_double_chars("a b =") == 2
- :param s: input string.
- :return: count of double symbols.
- """
- s = list(s)
- count = 0
- double = False
- for i in s:
- for j in i:
- if i[j] == i[j + 1]:
- double = True
- if double is True and i[j] != i[j + 2]:
- count += 1
- return count
- print(count_double_chars("aabc"))
- def penguins(values: dict, nests: list) -> str:
- """
- Find the most valuable nest.
- #04
- Nest consists of stones. Each stone has its value. The value for the nest is the sum of all the values of the stones.
- Example:
- Nest contains stones: aba
- Values dict = {'a': 2, 'b': 6}
- "a" value is 2, "b" value is 6
- Total value for the nest is 2 + 6 + 2 = 10
- Nest "aa" would have the value 2 + 2 = 4 etc
- All the stones in the nests have values in the dict (no need to validate inputs).
- List contains at least one nest.
- If multiple nests have the same highest value, it doesn't matter which one to return.
- assert penguins({"a": 1}, ["a", "aa"]) == "aa"
- assert penguins({"a": -1}, ["a", ""]) == ""
- assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
- assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
- assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
- assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
- assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
- assert penguins({"a": -1, "b": -2, "c": -5}, ["cba", "bcb"]) == "cba"
- :param values: values of the stones as dictionary.
- :param nests: list of nests with stones.
- :return: the nest with the highest value.
- """
- pass
- def remove_duplicates(values: list, divisor: int) -> list:
- """
- Given an int array, return a list without certain duplicates.
- #05
- Remove all duplicates that are divisible by divisor and
- appear after the first largest element in the list.
- assert remove_duplicates([1, 3, 3], 3) == [1, 3]
- assert remove_duplicates([1, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
- assert remove_duplicates([], 5) == []
- assert remove_duplicates([1, 4, 3, 2, 3, 2], 0) == [1, 4, 3, 2, 3, 2]
- assert remove_duplicates([1, 4, 3, 2, 3, 2, 6], 2) == [1, 4, 3, 2, 3, 2, 6]
- assert remove_duplicates([1, 4, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
- :param values: list of integers.
- :param divisor: integer.
- :return: list with duplicates removed.
- """
- if divisor == 0:
- return values
- remove = False
- for i in values:
- if i / divisor == 1:
- remove = True
- continue
- if remove:
- if values[i] == values[i + 1]:
- values.pop(i)
- if values[i] != values[i + 1]:
- remove = False
- return values
- print(remove_duplicates([1, 3, 3], 3))
- def substring(string: str, count: int) -> str:
- """
- Return first part of string with length of count.
- #06
- Function should be recursive, loops (for/while) are not allowed!
- count <= len(string)
- assert substring("hello", 2) == "he"
- assert substring("hi", 2) == "hi"
- assert substring("house", -1) == ""
- :param string: input string.
- :param count: int, count < len(string).
- :return: first count symbols from string.
- """
- if count > 0:
- return string[:count]
- else:
- return ""
- print(substring("hello", 2))
- print(substring("hello", -1))
- def weighted_average_and_scholarship(students_with_results: dict) -> dict:
- """
- Return the students along with their weighted average score who get scholarship.
- #07
- The dict has student name as the key and their results for the semester as the value.
- There are two possible ways for the results:
- 1) student has declared 7 subjects with the weights: 3, 3, 3, 3, 6, 6, 6
- 2) student has declared 6 subjects with the weights: 3, 3, 6, 6, 6, 6
- The results for each subject is one symbol:
- A - passed (not included in calculation)
- M - not passed (no included in calculation)
- digit - the result used in calculation
- Both A and M do not count either for the weight or the count.
- The scholarship is given to the top 30% of students (based on their weighted average grade).
- The count of students is rounded using the rules of mathematics (5.5 => 6; 5.49 => 5).
- If the result is lower than one, then in this case it is rounded up (to 1).
- Weighted average grade is calculated:
- WAG = (grade 1 * weight 1 + ... + grade N * weight N) / (weight 1 + ... + weight N)
- Weight is EAP count.
- The example dict: {'John Smith': '24A4M5'}
- In the output dict, round all the results up to 2 decimal points.
- The example output: {'John Smith': 4.00}
- :param students_with_results: students and their results.
- :return: top 30% students and their scores.
- """
- pass
- # 8 OOP1 Basket
- class PaymentProcessingException(Exception):
- """Thrown if payment can not be processed."""
- # You don't need to change this!
- pass
- class Basket:
- """
- Shopping basket for our e-commerce site.
- Basket holds state of user selected items.
- """
- def __init__(self):
- """Constructor, creates instance variables."""
- pass
- def add_item(self, item: str, price: float) -> bool:
- """
- Add item to basket.
- Item can be added if basked is not yet paid for.
- :param item: name of the item.
- :param price: price of the item.
- :return: was item added to the basket.
- """
- pass
- def remove_item(self, item: str) -> bool:
- """
- Remove item from basket.
- Item can be removed only if it is in the basket and basket is not yet paid for.
- If there are multiple items with the given name in the basket remove item with the lowest price.
- :param item: name of the item that should be removed.
- :return: was item removed
- """
- pass
- def get_total_price(self) -> float:
- """Calculate total price of the basket."""
- pass
- def pay(self, amount) -> float:
- """
- Pay for the basket.
- After successful payments basket state cannot be changed.
- In case the problem, raise PaymentProcessingException:
- raise PaymentProcessingException()
- No need to add the message.
- :param amount: money that was given by the user.
- :return: change from the transaction.
- :raises: PaymentProcessingException if basket is empty,
- already payed for or
- amount is less than the total price of the basket.
- """
- pass
- # 9 OOP2 Warehouse
- class Product:
- """Product in the warehouse."""
- def __init__(self, name: str, weight: int):
- """Initialize the product with the name and weight."""
- pass
- class Box:
- """Box for products."""
- def __init__(self, size: str):
- """
- Initialize the box.
- size is one of:
- XS - max weight 100
- S - max weight 200
- M - max weight 300
- L - max weight 400
- XL - max weight 500
- Based on the size, the maximum weight allowed for the box is determined.
- You don't have to validate the input. It's always one of the above.
- """
- pass
- def add_product(self, product: Product) -> Product or None:
- """
- Add product to the box.
- If there are enough room, the product is added and the product itself is returned.
- Otherwise None is returned.
- :param product: Product object to be added
- :return: Added product or None
- """
- pass
- def show_content(self) -> list:
- """Return list of products in the box."""
- pass
- def get_size(self):
- """Return specified size."""
- pass
- class Worker:
- """Warehouse worker."""
- def __init__(self, name: str, experience: int):
- """Initialize the worker."""
- pass
- def get_experience_level(self) -> int:
- """
- Get experience level.
- If the experience is lower than 10, level is 3.
- If the experience is equal or greater than 10 and less than 20, the level is 2.
- If the experience is equal or greater than 20, the level is 3.
- :return:
- """
- pass
- def get_experience(self) -> int:
- """Get experience of the worker."""
- pass
- class Warehouse:
- """Warehouse itself."""
- def __init__(self, name: str, workers: list):
- """Initialize the warehouse."""
- pass
- def pack_order(self, products_to_pack: list, importance_level: int) -> Box:
- """
- Create a box with products.
- importance level indicates, which workers can work wit this order:
- - 1 - only the most experienced workers can work with this order, e.g. experience level == 1
- - 2 - workers with experience level 1 and 2 can work on the order
- - 3 - workers with experience level 1, 2 and 3 can work on the order
- The order can be fulfilled if the sum of valid workers' experience is at least (greater or equal)
- to the sum of products' name lengths.
- You have to create Product objects based on the product names. The name will be the string in products list,
- the weight will be name length * 10. For example "banana" will become Product("banana", 60).
- The minimal size box is selected for packing. If the total weight of the products is 200,
- there's no point to select "L". All the products will be placed within one box.
- If the total weight of products is higher than the largest box, the order cannot be fulfilled.
- If the order cannot be fulfilled, an empty box (what ever size) should be returned.
- If the order is fulfilled, the box with all the products should be returned.
- If the order is fulfilled, each participating worker get +2 experience.
- If the order is not fulfilled, no experience is increased.
- :param products_to_pack: list of strings (name of the products)
- :param importance_level: int, the required experience level
- :return: Box object
- """
- pass
- def max_diff_sublist_length(numbers: list) -> int:
- """
- Find the longest unique sublist length.
- Unique sublist is a list of consequent elements where all the elements are different.
- assert max_diff_sublist_length([1, 2, 3]) == 3
- assert max_diff_sublist_length([1, 2, 1, 2, 3]) == 3
- assert max_diff_sublist_length([1, 1]) == 1
- assert max_diff_sublist_length([0, 1, -10, 0, -10, -2]) == 3
- assert max_diff_sublist_length([1, 1, 2]) == 2
- assert max_diff_sublist_length([4, 3, 2, 1, 3]) == 4
- assert max_diff_sublist_length([4, 3, 2, 1, 3, 2, 4, 5]) == 5
- assert max_diff_sublist_length([]) == 0
- :param numbers: list of integers
- :return: longest unique sublist length
- """
- sort = []
- sort2 = []
- new = []
- new2 = []
- new3 = []
- new4 = []
- if len(numbers) == 0:
- return 0
- for i in numbers:
- if i not in new:
- new.append(i)
- elif i in new:
- new2.append(i)
- elif i in new2:
- new3.append(i)
- elif i in new3:
- new4.append(i)
- sort.append(new)
- sort.append(new2)
- sort.append(new3)
- sort.append(new4)
- sort = sorted(sort)
- for j in sort:
- if len(j) > 0:
- sort2.append(j)
- return len(sort2[0])
- if __name__ == '__main__':
- assert power_of_nums([1, 2, 3, 4]) == 1
- assert power_of_nums([3, 4, 5]) == 81
- assert power_of_nums([2, 5]) == 4
- assert power_of_nums([-2, -3, -4]) == -0.125
- assert power_of_nums([0, 0]) == 1
- assert which_number(20) == "EVEN"
- assert which_number(-2) == "EVEN"
- assert which_number(-9) == "ODD BORING"
- assert which_number(5) == "ODD BORING PALINDROMIC"
- assert which_number(121) == "ODD INTERESTING PALINDROMIC"
- assert which_number(16) == "EVEN"
- assert count_double_chars("abc") == 0
- assert count_double_chars("aabc") == 1
- assert count_double_chars("aaabc") == 0 # (three "a"-s doesn't count)
- assert count_double_chars("aaaabc") == 0 # (four "a"-s also doesn't count)
- assert count_double_chars("aabbc") == 2
- assert count_double_chars("") == 0
- assert count_double_chars("abbcdd") == 2
- assert count_double_chars("aabbaa") == 3
- assert count_double_chars(",,!?") == 1
- assert count_double_chars("a b =") == 2
- assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
- assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
- assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
- assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
- assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
- assert penguins({"a": 1}, ["a", "aa"]) == "aa"
- assert penguins({"a": -1}, ["a", ""]) == ""
- assert remove_duplicates([1, 3, 3], 3) == [1, 3]
- assert remove_duplicates([1, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
- assert remove_duplicates([], 5) == []
- assert remove_duplicates([1, 4, 3, 2, 3, 2], 0) == [1, 4, 3, 2, 3, 2]
- assert remove_duplicates([1, 4, 3, 2, 3, 2, 6], 2) == [1, 4, 3, 2, 3, 2, 6]
- assert remove_duplicates([1, 4, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
- assert substring("hello", 2) == "he"
- assert substring("hi", 2) == "hi"
- assert substring("house", -1) == ""
- assert penguins({"a": 1}, ["a", "aa"]) == "aa"
- assert penguins({"a": -1}, ["a", ""]) == ""
- assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
- assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
- assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
- assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
- assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
- assert penguins({"a": -1, "b": -2, "c": -5}, ["cba", "bcb"]) == "cba"
- print(weighted_average_and_scholarship(
- {
- "Mait Maasikas": "112233",
- "Kati Kaalikas": "A54A255",
- "Neeme Naeris": "AAAAAA",
- }
- ))
- assert weighted_average_and_scholarship(
- {
- "Mait Maasikas": "112233",
- "Kati Kaalikas": "A54A255",
- "Neeme Naeris": "AAAAAA"
- }
- ) == {'Kati Kaalikas': 4.12}
- assert weighted_average_and_scholarship(
- {
- "Printsess": "12543M",
- "Sinine Pall": "1522AA5",
- "Roheline Lumi": "4541MA5",
- "Pruun Uks": "12345A",
- "Punane Kauss": "123123",
- "Must Must": "0421AM3",
- "Valge Saabas": "431553",
- "Hall Varjund": "M5M5M54",
- "Roosa Pink": "4343331"
- }
- ) == {
- 'Hall Varjund': 4.67,
- 'Roheline Lumi': 4.0,
- 'Valge Saabas': 3.5
- }
- assert weighted_average_and_scholarship(
- {
- "Kuido Baggins": "010101"
- }
- ) == {"Kuido Baggins": 0.50}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement