Домашни > Функцията, която казва "Ni!" > Решения > Решението на Дейвид Барух

Резултати
9 точки от тестове
0 точки от учител

9 точки общо

9 успешни теста
1 неуспешни теста
Код (Надявам се, че всичко вече е наред)

 1BUSHES = ["храст", "shrub", "bush"]
 2
 3def evaluate_potential_bush(potentical_bush):
 4    if isinstance(potentical_bush, dict):
 5        return potentical_bush.get("name", "empty").lower() in BUSHES
 6    return False
 7               
 8def get_cost_for_bush(bush):
 9    return bush.get('cost', 0)
10
11def function_that_says_ni(*args, **kwargs):  
12    named_bushes = {}
13    nameless_bushes = []
14    for name,potentical_bush in kwargs.items():
15        if evaluate_potential_bush(potentical_bush):
16            named_bushes[name] = potentical_bush
17
18    for potentical_bush in args:
19        if evaluate_potential_bush(potentical_bush):
20            nameless_bushes.append(potentical_bush)     
21
22    fail = "Ni!"
23
24    if len(named_bushes) == 0 and len(nameless_bushes) == 0:
25        return fail
26
27    total_cost = 0
28    unique_letters = set()
29
30    for bush in nameless_bushes:
31        total_cost += get_cost_for_bush(bush)
32
33    for name,bush in named_bushes.items():
34        total_cost += get_cost_for_bush(bush)
35        unique_letters.update(name)
36
37    if total_cost > 42 or total_cost == 0:
38        return fail
39    
40    beauty_coefficient = len(unique_letters)
41        
42    if(beauty_coefficient % int(total_cost) == 0):
43        return "{:.2f}лв".format(total_cost)
44
45    return fail

..E.......
======================================================================
ERROR: test_cost_whole_part_zero (test.TestNi.test_cost_whole_part_zero)
Test with a total cost part equal to zero.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 43, in test_cost_whole_part_zero
self.assertEqual(function_that_says_ni({'name': 'shrub', 'cost': 0.1},
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/solution.py", line 42, in function_that_says_ni
if(beauty_coefficient % int(total_cost) == 0):
~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
ZeroDivisionError: integer modulo by zero

----------------------------------------------------------------------
Ran 10 tests in 0.001s

FAILED (errors=1)

Дискусия
Дейвид Барух
22.10.2024 14:41

Сега ще поправя кода
Георги Кунчев
22.10.2024 14:09

Понеже зададе въпрос в Moodle дали можеш да ползваш неща, които не са били преподавани, искам да отговоря по-конкретно от отговора си там. Да, можеш. Дори го препоръчвам. Ние даваме основни знания и се опитваме да обясним кое как и защо работи, но не можем да ви покажем цялата вградена библиотека на Пайтън, а и няма смисъл. По-добра практика е просто да потърсиш нещо полезно в документацията, ако прецениш, че не ти харесва метода, който си използвал и предполагаш, че има нещо по-лесно. С времето се научваш на повече трикове и имаш по-добра представа какво можеш да използваш наготово и какво се очаква да напишеш сам.
История

n1hrasti = ["храст", "shrub", "bush"]n1BUSHES = ["храст", "shrub", "bush"]
22
n3def evaluate_potential_hrast(potentical_hrast):n3def evaluate_potential_bush(potentical_bush):
4    if isinstance(potentical_hrast,dict):4    if isinstance(potentical_bush, dict):
5        for key,val in potentical_hrast.items():5        return potentical_bush.get("name", "empty").lower() in BUSHES
6            if key=="name" and val.lower() in hrasti:
7                return True
8        return False
9    return False6    return False
nn7               
8def get_cost_for_bush(bush):
9    return bush.get('cost', 0)
1010
n11def get_cost_for_hrast(hrast):n11def function_that_says_ni(*args, **kwargs):  
12    for key,val in hrast.items():12    named_bushes = {}
13        if key == "cost":13    nameless_bushes = []
14            return val14    for name,potentical_bush in kwargs.items():
15    return 015        if evaluate_potential_bush(potentical_bush):
16            named_bushes[name] = potentical_bush
1617
n17def function_that_says_ni( *args, **kwargs):n18    for potentical_bush in args:
18    def get_hrasti():
19        named_hrasti={}
20        nameless_hrasti=[]
21        for name,potentical_hrast in kwargs.items():
22            if evaluate_potential_hrast(potentical_hrast):19        if evaluate_potential_bush(potentical_bush):
23                named_hrasti[name] = potentical_hrast20            nameless_bushes.append(potentical_bush)     
2421
n25        for potentical_hrast in args:n
26            if evaluate_potential_hrast(potentical_hrast):
27                nameless_hrasti.append(potentical_hrast)   
28 
29        return named_hrasti,nameless_hrasti
30   
31    #print(get_hrasti())
32    named_hrasti,nameless_hrasti = get_hrasti()
33    fail = "Ni!"22    fail = "Ni!"
3423
n35    if named_hrasti == {} and nameless_hrasti == []:n24    if len(named_bushes) == 0 and len(nameless_bushes) == 0:
36        return fail25        return fail
3726
38    total_cost = 027    total_cost = 0
39    unique_letters = set()28    unique_letters = set()
4029
n41    for hrast in nameless_hrasti:n30    for bush in nameless_bushes:
42        total_cost += get_cost_for_hrast(hrast)31        total_cost += get_cost_for_bush(bush)
4332
n44    for name,hrast in named_hrasti.items():n33    for name,bush in named_bushes.items():
45        total_cost += get_cost_for_hrast(hrast)34        total_cost += get_cost_for_bush(bush)
46        for letter in name:35        unique_letters.update(name)
47            unique_letters.add(letter)36 
48    #print("total_cost : ",total_cost)
49    if(total_cost > 42 or total_cost == 0):37    if total_cost > 42 or total_cost == 0:
50        return fail38        return fail
51    39    
52    beauty_coefficient = len(unique_letters)40    beauty_coefficient = len(unique_letters)
n53    rounded_cost = ""n
54    index_after_comma_allowed = 2
55    for sym in str(total_cost):
56        if not sym == "." and index_after_comma_allowed == 2:
57            rounded_cost+=sym
58        elif sym == ".":
59            rounded_cost+=sym
60            index_after_comma_allowed -= 1
61        elif index_after_comma_allowed == -1:
62            break
63        else :
64            rounded_cost+=sym
65            index_after_comma_allowed -= 1
66    
67    if(index_after_comma_allowed>-1):
68        while index_after_comma_allowed>-1:
69            if(index_after_comma_allowed ==2):
70                rounded_cost+="."
71            else:
72                rounded_cost+="0"
73            index_after_comma_allowed -=1
74    
75        41        
76    if(beauty_coefficient % int(total_cost) == 0):42    if(beauty_coefficient % int(total_cost) == 0):
n77        return "{}лв".format(rounded_cost)n43        return "{:.2f}лв".format(total_cost)
7844
79    return fail45    return fail
8046
t81 t
82 
83# print(function_that_says_ni({"name": "храст", "cost": 1.50}, {"name": "sHRub", "cost": 3.00}))#4.50лв
84#print(function_that_says_ni({"name": "хРАст", "cost": 150}, {"name": "shrub", "cost": 3.00}))#Ni!"
85#print(function_that_says_ni({"ddd": "храст", "cost": 1.50}, {"namae": "sHRub", "cost": 3.00}))#Ni!"
86# print(function_that_says_ni({"namdde": "хРАст", "cost": 150}, {"namse": "shrub", "cost": 3.00}))#Ni!"
87# print(function_that_says_ni({"name": "буш", "cost": 1.00}, {"name": "храст", "cost": 244.00}))#Ni!"
88# print(function_that_says_ni({"name": "буш", "cost": 1.00}, {"name": "храстченце", "cost": 2.00}))#Ni!"
89# print(function_that_says_ni({"name": "буш", "cost": 1.00}, {"name": "храст", "cost": 41.99}))#41.99лв
90# print(function_that_says_ni({"name": "храст"}, {"name": "buSh"}))#"Ni!"
91# print(function_that_says_ni(a={"name": "храст"}, b={"name": "shrub"}))#"Ni!"
92# print(function_that_says_ni({"name": "храст44"}, {"name": "bus44h"}))#"Ni!"
93# print(function_that_says_ni(a={"name": "храс124т"}, b={"name": "s52hrub"}))#
94# print(function_that_says_ni({"name": "храст"}, {"name": "bush", "cost": 33.33}))#33.33лв
95# print(function_that_says_ni(a={"name": "храст", "cost": 17}, b={"name": "shrub"}))#"Ni!"
96# print(function_that_says_ni({"name": "храсТ", "cost": 50.0}))#"Ni!"
97#print(function_that_says_ni({"name": "храст"}, {"name": "храст", "cost": 0.0}, ["ffffffffff", {1, 2, 3}]))
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op