• API
• FAQ
• Tools
• Archive
SHARE
TWEET # kek a guest Jan 21st, 2020 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. """Exam 4."""
2.
3.
4. def power_of_nums(nums: list) -> int:
5.     """
6.     Given an array of integers, return the first element in power of the second to the last element in array.
7.
8.     #01
9.
10.     You do not have to check if the input is valid.
11.
12.     assert power_of_nums([1, 2, 3, 4]) == 1
13.     assert power_of_nums([3, 4, 5]) == 81
14.     assert power_of_nums([2, 5]) == 4
15.     assert power_of_nums([-2, -3, -4]) == -0.125
16.     assert power_of_nums([0, 0]) == 1
17.
18.
19.     :param nums: list of integers.
20.     :return: first element in power of second to last element.
21.     """
22.     return nums ** nums[-2]
23.
24.
25. print(power_of_nums([3, 4, 5]))
26. print(power_of_nums([0, 0]))
27.
28.
29. def which_number(num: int) -> str:
30.     """
31.     Decide what kind of number you are given.
32.
33.     #02
34.
35.     If the number is even, return string saying EVEN unless the
36.     number is palindromic, in that case return string saying EVEN PALINDROMIC.
37.     Palindromic numbers are positive numbers that remain the same when their digits are reversed.
38.     For example 22, 33, 121, 1234321 etc.
39.
40.     The same applies to odd numbers, but in addition to that in case the odd
41.     number is a square number you should add INTERESTING to the output.
42.     In other cases, if the odd number is not a square number add BORING to the output.
43.
44.     The order of the words must be EVEN/ODD, INTERESTING/BORING, PALINDROMIC
45.     Be careful with negative numbers!
46.
47.     assert which_number(20) == "EVEN"
48.     assert which_number(-2) == "EVEN"
49.     assert which_number(-9) == "ODD BORING"
50.     assert which_number(5) == "ODD BORING PALINDROMIC"
51.     assert which_number(121) == "ODD INTERESTING PALINDROMIC"
52.     assert which_number(16) == "EVEN"
53.
54.     :param num: -infinity < num < +infinity.
55.     :return: String saying some of these words EVEN, ODD, INTERESTING, BORING, PALINDROMIC
56.     depending on the input.
57.     """
58.     import math
59.     snum = str(num)
60.     reversed = snum[::-1]
61.     if num % 2 == 0:
62.         if str(num) == reversed and num > 0:
63.             return "EVEN PALIDROMIC"
64.         else:
65.             return "EVEN"
66.     elif num % 2 != 0:
67.         if num > 0:
68.             sqrt = math.sqrt(num)
69.             if num > 0 and sqrt == sqrt // 1 and str(num) == reversed:
70.                 return "ODD INTERESTING PALINDROMIC"
71.             if num > 0 and sqrt == sqrt // 1:
72.                 return "ODD INTERESTING"
73.             if num > 0 and str(num) == reversed:
74.                 return "ODD BORING PALINDROMIC"
75.         if num < 0:
76.             return "ODD BORING"
77.
78.
79. print(which_number(20))  # == "EVEN"
80. print(which_number(-2))  # == "EVEN"
81. print(which_number(-9))  # == "ODD BORING"
82. print(which_number(5))  # == "ODD BORING PALINDROMIC"
83. print(which_number(121))  # == "ODD INTERESTING PALINDROMIC"
84. print(which_number(16))  # == "EVEN"
85.
86.
87. def count_double_chars(s: str) -> int:
88.     """
89.     Count only double symbols.
90.
91.     #03
92.
93.     Count how many double symbols are in the text. You have to only count pairs.
94.     Therefore, pair of symbols which is not preceded or followed by the same symbol.
95.     If there are three or more of the same symbol, then this is not a pair and doesn't count.
96.     Any printable symbol counts (letters, digits, punctuation, space etc).
97.
98.     assert count_double_chars("abc") == 0
99.     assert count_double_chars("aabc") == 1
100.     assert count_double_chars("aaabc") == 0  # (three "a"-s doesn't count)
101.     assert count_double_chars("aaaabc") == 0  # (four "a"-s also doesn't count)
102.     assert count_double_chars("aabbc") == 2
103.     assert count_double_chars("") == 0
104.     assert count_double_chars("abbcdd") == 2
105.     assert count_double_chars("aabbaa") == 3
106.     assert count_double_chars(",,!?") == 1
107.     assert count_double_chars("a  b  =") == 2
108.
109.     :param s: input string.
110.     :return: count of double symbols.
111.     """
112.     s = list(s)
113.     count = 0
114.     double = False
115.     for i in s:
116.         for j in i:
117.             if i[j] == i[j + 1]:
118.                 double = True
119.             if double is True and i[j] != i[j + 2]:
120.                 count += 1
121.     return count
122.
123.
124. print(count_double_chars("aabc"))
125.
126.
127. def penguins(values: dict, nests: list) -> str:
128.     """
129.     Find the most valuable nest.
130.
131.     #04
132.
133.     Nest consists of stones. Each stone has its value. The value for the nest is the sum of all the values of the stones.
134.
135.     Example:
136.     Nest contains stones: aba
137.     Values dict = {'a': 2, 'b': 6}
138.     "a" value is 2, "b" value is 6
139.     Total value for the nest is 2 + 6 + 2 = 10
140.     Nest "aa" would have the value 2 + 2 = 4 etc
141.
142.     All the stones in the nests have values in the dict (no need to validate inputs).
143.     List contains at least one nest.
144.
145.     If multiple nests have the same highest value, it doesn't matter which one to return.
146.
147.     assert penguins({"a": 1}, ["a", "aa"]) == "aa"
148.     assert penguins({"a": -1}, ["a", ""]) == ""
149.     assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
150.     assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
151.     assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
152.     assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
153.     assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
154.     assert penguins({"a": -1, "b": -2, "c": -5}, ["cba", "bcb"]) == "cba"
155.
156.     :param values: values of the stones as dictionary.
157.     :param nests: list of nests with stones.
158.     :return: the nest with the highest value.
159.     """
160.     pass
161.
162.
163. def remove_duplicates(values: list, divisor: int) -> list:
164.     """
165.     Given an int array, return a list without certain duplicates.
166.
167.     #05
168.
169.     Remove all duplicates that are divisible by divisor and
170.     appear after the first largest element in the list.
171.
172.     assert remove_duplicates([1, 3, 3], 3) == [1, 3]
173.     assert remove_duplicates([1, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
174.     assert remove_duplicates([], 5) == []
175.     assert remove_duplicates([1, 4, 3, 2, 3, 2], 0) == [1, 4, 3, 2, 3, 2]
176.     assert remove_duplicates([1, 4, 3, 2, 3, 2, 6], 2) == [1, 4, 3, 2, 3, 2, 6]
177.     assert remove_duplicates([1, 4, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
178.
179.     :param values: list of integers.
180.     :param divisor: integer.
181.     :return: list with duplicates removed.
182.     """
183.     if divisor == 0:
184.         return values
185.     remove = False
186.     for i in values:
187.         if i / divisor == 1:
188.             remove = True
189.             continue
190.         if remove:
191.             if values[i] == values[i + 1]:
192.                 values.pop(i)
193.             if values[i] != values[i + 1]:
194.                 remove = False
195.     return values
196.
197.
198. print(remove_duplicates([1, 3, 3], 3))
199.
200.
201. def substring(string: str, count: int) -> str:
202.     """
203.     Return first part of string with length of count.
204.
205.     #06
206.
207.     Function should be recursive, loops (for/while) are not allowed!
208.     count <= len(string)
209.
210.     assert substring("hello", 2) == "he"
211.     assert substring("hi", 2) == "hi"
212.     assert substring("house", -1) == ""
213.
214.     :param string: input string.
215.     :param count: int, count < len(string).
216.     :return: first count symbols from string.
217.     """
218.     if count > 0:
219.         return string[:count]
220.     else:
221.         return ""
222.
223.
224. print(substring("hello", 2))
225. print(substring("hello", -1))
226.
227.
228. def weighted_average_and_scholarship(students_with_results: dict) -> dict:
229.     """
230.     Return the students along with their weighted average score who get scholarship.
231.
232.     #07
233.
234.     The dict has student name as the key and their results for the semester as the value.
235.
236.     There are two possible ways for the results:
237.     1) student has declared 7 subjects with the weights: 3, 3, 3, 3, 6, 6, 6
238.     2) student has declared 6 subjects with the weights: 3, 3, 6, 6, 6, 6
239.
240.     The results for each subject is one symbol:
241.     A - passed (not included in calculation)
242.     M - not passed (no included in calculation)
243.     digit - the result used in calculation
244.
245.     Both A and M do not count either for the weight or the count.
246.
247.     The scholarship is given to the top 30% of students (based on their weighted average grade).
248.     The count of students is rounded using the rules of mathematics (5.5 => 6; 5.49 => 5).
249.     If the result is lower than one, then in this case it is rounded up (to 1).
250.
251.     Weighted average grade is calculated:
252.
253.     WAG = (grade 1 * weight 1 + ... + grade N * weight N) / (weight 1 + ... + weight N)
254.
255.     Weight is EAP count.
256.
257.     The example dict: {'John Smith': '24A4M5'}
258.
259.     In the output dict, round all the results up to 2 decimal points.
260.
261.     The example output: {'John Smith': 4.00}
262.
263.
264.
265.
266.     :param students_with_results: students and their results.
267.     :return: top 30% students and their scores.
268.     """
269.     pass
270.
271.
273.
274.
275. class PaymentProcessingException(Exception):
276.     """Thrown if payment can not be processed."""
277.
278.     # You don't need to change this!
279.     pass
280.
281.
283.     """
284.     Shopping basket for our e-commerce site.
285.
286.     Basket holds state of user selected items.
287.     """
288.
289.     def __init__(self):
290.         """Constructor, creates instance variables."""
291.         pass
292.
293.     def add_item(self, item: str, price: float) -> bool:
294.         """
296.
297.         Item can be added if basked is not yet paid for.
298.
299.         :param item: name of the item.
300.         :param price: price of the item.
302.         """
303.         pass
304.
305.     def remove_item(self, item: str) -> bool:
306.         """
308.
309.         Item can be removed only if it is in the basket and basket is not yet paid for.
310.         If there are multiple items with the given name in the basket remove item with the lowest price.
311.
312.         :param item: name of the item that should be removed.
313.         :return: was item removed
314.         """
315.         pass
316.
317.     def get_total_price(self) -> float:
318.         """Calculate total price of the basket."""
319.         pass
320.
321.     def pay(self, amount) -> float:
322.         """
324.
325.         After successful payments basket state cannot be changed.
326.
327.         In case the problem, raise PaymentProcessingException:
328.
329.         raise PaymentProcessingException()
330.
331.         No need to add the message.
332.
333.         :param amount: money that was given by the user.
334.         :return: change from the transaction.
335.         :raises: PaymentProcessingException if basket is empty,
337.                     amount is less than the total price of the basket.
338.         """
339.         pass
340.
341.
342. # 9 OOP2 Warehouse
343.
344.
345. class Product:
346.     """Product in the warehouse."""
347.
348.     def __init__(self, name: str, weight: int):
349.         """Initialize the product with the name and weight."""
350.         pass
351.
352.
353. class Box:
354.     """Box for products."""
355.
356.     def __init__(self, size: str):
357.         """
358.         Initialize the box.
359.
360.         size is one of:
361.         XS - max weight 100
362.         S - max weight 200
363.         M - max weight 300
364.         L - max weight 400
365.         XL - max weight 500
366.
367.         Based on the size, the maximum weight allowed for the box is determined.
368.
369.         You don't have to validate the input. It's always one of the above.
370.         """
371.         pass
372.
373.     def add_product(self, product: Product) -> Product or None:
374.         """
375.         Add product to the box.
376.
377.         If there are enough room, the product is added and the product itself is returned.
378.         Otherwise None is returned.
379.
380.         :param product: Product object to be added
381.         :return: Added product or None
382.         """
383.         pass
384.
385.     def show_content(self) -> list:
386.         """Return list of products in the box."""
387.         pass
388.
389.     def get_size(self):
390.         """Return specified size."""
391.         pass
392.
393.
394. class Worker:
395.     """Warehouse worker."""
396.
397.     def __init__(self, name: str, experience: int):
398.         """Initialize the worker."""
399.         pass
400.
401.     def get_experience_level(self) -> int:
402.         """
403.         Get experience level.
404.
405.         If the experience is lower than 10, level is 3.
406.         If the experience is equal or greater than 10 and less than 20, the level is 2.
407.         If the experience is equal or greater than 20, the level is 3.
408.         :return:
409.         """
410.         pass
411.
412.     def get_experience(self) -> int:
413.         """Get experience of the worker."""
414.         pass
415.
416.
417. class Warehouse:
418.     """Warehouse itself."""
419.
420.     def __init__(self, name: str, workers: list):
421.         """Initialize the warehouse."""
422.         pass
423.
424.     def pack_order(self, products_to_pack: list, importance_level: int) -> Box:
425.         """
426.         Create a box with products.
427.
428.         importance level indicates, which workers can work wit this order:
429.          - 1 - only the most experienced workers can work with this order, e.g. experience level == 1
430.          - 2 - workers with experience level 1 and 2 can work on the order
431.          - 3 - workers with experience level 1, 2 and 3 can work on the order
432.
433.         The order can be fulfilled if the sum of valid workers' experience is at least (greater or equal)
434.         to the sum of products' name lengths.
435.
436.         You have to create Product objects based on the product names. The name will be the string in products list,
437.         the weight will be name length * 10. For example "banana" will become Product("banana", 60).
438.
439.         The minimal size box is selected for packing. If the total weight of the products is 200,
440.         there's no point to select "L". All the products will be placed within one box.
441.         If the total weight of products is higher than the largest box, the order cannot be fulfilled.
442.
443.         If the order cannot be fulfilled, an empty box (what ever size) should be returned.
444.         If the order is fulfilled, the box with all the products should be returned.
445.
446.         If the order is fulfilled, each participating worker get +2 experience.
447.         If the order is not fulfilled, no experience is increased.
448.
449.         :param products_to_pack: list of strings (name of the products)
450.         :param importance_level: int, the required experience level
451.         :return: Box object
452.         """
453.         pass
454.
455.
456. def max_diff_sublist_length(numbers: list) -> int:
457.     """
458.     Find the longest unique sublist length.
459.
460.     Unique sublist is a list of consequent elements where all the elements are different.
461.
462.     assert max_diff_sublist_length([1, 2, 3]) == 3
463.     assert max_diff_sublist_length([1, 2, 1, 2, 3]) == 3
464.     assert max_diff_sublist_length([1, 1]) == 1
465.     assert max_diff_sublist_length([0, 1, -10, 0, -10, -2]) == 3
466.     assert max_diff_sublist_length([1, 1, 2]) == 2
467.     assert max_diff_sublist_length([4, 3, 2, 1, 3]) == 4
468.     assert max_diff_sublist_length([4, 3, 2, 1, 3, 2, 4, 5]) == 5
469.     assert max_diff_sublist_length([]) == 0
470.
471.     :param numbers: list of integers
472.     :return: longest unique sublist length
473.     """
474.     sort = []
475.     sort2 = []
476.     new = []
477.     new2 = []
478.     new3 = []
479.     new4 = []
480.     if len(numbers) == 0:
481.         return 0
482.     for i in numbers:
483.         if i not in new:
484.             new.append(i)
485.         elif i in new:
486.             new2.append(i)
487.         elif i in new2:
488.             new3.append(i)
489.         elif i in new3:
490.             new4.append(i)
491.     sort.append(new)
492.     sort.append(new2)
493.     sort.append(new3)
494.     sort.append(new4)
495.     sort = sorted(sort)
496.     for j in sort:
497.         if len(j) > 0:
498.             sort2.append(j)
499.     return len(sort2)
500.
501.
502. if __name__ == '__main__':
503.     assert power_of_nums([1, 2, 3, 4]) == 1
504.     assert power_of_nums([3, 4, 5]) == 81
505.     assert power_of_nums([2, 5]) == 4
506.     assert power_of_nums([-2, -3, -4]) == -0.125
507.     assert power_of_nums([0, 0]) == 1
508.
509.     assert which_number(20) == "EVEN"
510.     assert which_number(-2) == "EVEN"
511.     assert which_number(-9) == "ODD BORING"
512.     assert which_number(5) == "ODD BORING PALINDROMIC"
513.     assert which_number(121) == "ODD INTERESTING PALINDROMIC"
514.     assert which_number(16) == "EVEN"
515.
516.     assert count_double_chars("abc") == 0
517.     assert count_double_chars("aabc") == 1
518.     assert count_double_chars("aaabc") == 0  # (three "a"-s doesn't count)
519.     assert count_double_chars("aaaabc") == 0  # (four "a"-s also doesn't count)
520.     assert count_double_chars("aabbc") == 2
521.     assert count_double_chars("") == 0
522.     assert count_double_chars("abbcdd") == 2
523.     assert count_double_chars("aabbaa") == 3
524.     assert count_double_chars(",,!?") == 1
525.     assert count_double_chars("a  b  =") == 2
526.
527.     assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
528.     assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
529.     assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
530.     assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
531.     assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
532.     assert penguins({"a": 1}, ["a", "aa"]) == "aa"
533.     assert penguins({"a": -1}, ["a", ""]) == ""
534.
535.     assert remove_duplicates([1, 3, 3], 3) == [1, 3]
536.     assert remove_duplicates([1, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
537.     assert remove_duplicates([], 5) == []
538.     assert remove_duplicates([1, 4, 3, 2, 3, 2], 0) == [1, 4, 3, 2, 3, 2]
539.     assert remove_duplicates([1, 4, 3, 2, 3, 2, 6], 2) == [1, 4, 3, 2, 3, 2, 6]
540.     assert remove_duplicates([1, 4, 4, 3, 2, 3, 2], 2) == [1, 4, 3, 2, 3]
541.
542.     assert substring("hello", 2) == "he"
543.     assert substring("hi", 2) == "hi"
544.     assert substring("house", -1) == ""
545.
546.     assert penguins({"a": 1}, ["a", "aa"]) == "aa"
547.     assert penguins({"a": -1}, ["a", ""]) == ""
548.     assert penguins({"a": 1, "b": 2}, ["aba", "bab"]) == "bab"
549.     assert penguins({"a": -3, "b": 3}, ["aba", "bab"]) == "bab"
550.     assert penguins({"a": 7, "b": -5}, ["aba", "bab"]) == "aba"
551.     assert penguins({"a": 23, "b": 2, "c": 3, "d": -2}, ["aba", "bab", "abcdabcd", "abcdabdd"]) == "abcdabcd"
552.     assert penguins({"a": 1, "b": 2, "c": 12}, ["aba", "bab", "abc", "ababac", "abacca"]) == "abacca"
553.     assert penguins({"a": -1, "b": -2, "c": -5}, ["cba", "bcb"]) == "cba"
554.
555.     print(weighted_average_and_scholarship(
556.         {
557.             "Mait Maasikas": "112233",
558.             "Kati Kaalikas": "A54A255",
559.             "Neeme Naeris": "AAAAAA",
560.         }
561.     ))
562.
563.     assert weighted_average_and_scholarship(
564.         {
565.             "Mait Maasikas": "112233",
566.             "Kati Kaalikas": "A54A255",
567.             "Neeme Naeris": "AAAAAA"
568.         }
569.     ) == {'Kati Kaalikas': 4.12}
570.
571.     assert weighted_average_and_scholarship(
572.         {
573.             "Printsess": "12543M",
574.             "Sinine Pall": "1522AA5",
575.             "Roheline Lumi": "4541MA5",
576.             "Pruun Uks": "12345A",
577.             "Punane Kauss": "123123",
578.             "Must Must": "0421AM3",
579.             "Valge Saabas": "431553",
580.             "Hall Varjund": "M5M5M54",
581.             "Roosa Pink": "4343331"
582.         }
583.     ) == {
584.                'Hall Varjund': 4.67,
585.                'Roheline Lumi': 4.0,
586.                'Valge Saabas': 3.5
587.            }
588.
589.     assert weighted_average_and_scholarship(
590.         {
591.             "Kuido Baggins": "010101"
592.         }
593.     ) == {"Kuido Baggins": 0.50}
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top