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

Резултати
8 точки от тестове
1 точки от учител

9 точки общо

8 успешни теста
2 неуспешни теста
Код (така става ли 🤔️)

 1def function_that_says_ni(*args, **kwargs):    
 2    total_cost = 0.0
 3    named_shrubs_names = []
 4    found_valid_shrub = False
 5
 6    def process_shrub(value, key=None):
 7        if isinstance(value, dict) and 'name' in value:
 8            name = value['name'].lower()
 9            if name in ["храст", "shrub", "bush"]:  
10                nonlocal total_cost, found_valid_shrub 
11                found_valid_shrub = True
12                cost = value.get('cost', 0)
13                if isinstance(cost, (int, float)):
14                    total_cost += round(cost, 2)
15                    if key:
16                        named_shrubs_names.append(key)
17
18    for item in args:
19        process_shrub(item)
20    for key, value in kwargs.items():
21        process_shrub(value, key)
22
23    if not found_valid_shrub or total_cost > 42.00:
24        return "Ni!"                    
25      
26    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд
27    if total_cost > 0:
28        int_cost = int(total_cost) 
29        if int_cost == 0 or len(unique_letters) % int_cost != 0:
30            return "Ni!"
31        
32    return f"{total_cost:.2f}лв"                            

....F....F
======================================================================
FAIL: test_invalid_strings (test.TestNi.test_invalid_strings)
Test with invalid strings that might be misinterpreted.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 69, in test_invalid_strings
self.assertEqual(function_that_says_ni({'name': 'shrub', ' cost': 1}), self.NI) # Space before cost
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: '0.00лв' != 'Ni!'
- 0.00лв
+ Ni!

======================================================================
FAIL: test_with_no_cost (test.TestNi.test_with_no_cost)
Test with a shrub without defined cost.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 30, in test_with_no_cost
self.assertEqual(function_that_says_ni({'name': 'shrub'}), self.NI)
AssertionError: '0.00лв' != 'Ni!'
- 0.00лв
+ Ni!

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

FAILED (failures=2)

Дискусия
Виктор Бечев
22.10.2024 15:40

Да, моя грешка, `or` е, правилно си го направила.
Камелия Михайлова
21.10.2024 19:49

аа всъщност не трябва ли да е if с or
Камелия Михайлова
21.10.2024 19:47

Прав си, тук не мога да се защитя вече
Виктор Бечев
21.10.2024 18:33

По един празен ред ще преживеем тук-таме, най-много Жорката да е бесен. Все пак, ето пример, в който дори и аз не мога да защитя наличието дори и на един празен ред: ``` if not found_valid_shrub: return "Ni!" if total_cost > 42.00: return "Ni!" ``` Оставяме настрана нещо, на което не обърнах внимание - че може да е един `if` с `and`. :stuck_out_tongue:
Камелия Михайлова
21.10.2024 14:15

Не съм сигурна дали ще мога да се преборя с оставянето на поне един ред между различните логически обособени части :/ искаш да кажеш, че този код се очаква да няма нито един празен ред в него, така ли?? 😯️
Виктор Бечев
21.10.2024 13:34

Отвъд дребните стилистични забележки, единственото по-забележително е повторението на код в двата цикъла. По пример на Жорката, ще направя дисклеймър - ако си смела, можеш да се опиташ да ги обединиш, ако ли не - когато решенията станат публични ще можеш да разгледаш примери, където това е направено. Стилът, имената и прочие са супер (и може би най-валидната употреба на "флагова" променлива (`found_valid_shrub`), до момента).
История

nn1 
12
23
3def function_that_says_ni(*args, **kwargs):    4def function_that_says_ni(*args, **kwargs):    
4    total_cost = 0.05    total_cost = 0.0
5    named_shrubs_names = []6    named_shrubs_names = []
6    found_valid_shrub = False7    found_valid_shrub = False
78
n8    for arg in args:n9    def process_shrub(value, key=None):
9        if isinstance(arg, dict) and 'name' in arg:
10            name = arg['name'].lower()
11            if name in ["храст", "shrub", "bush"]:
12                found_valid_shrub = True
13                cost = arg.get('cost', 0)
14                if isinstance(cost, (int, float)):
15                    total_cost += round(cost, 2)   
16    for key, value in kwargs.items():
17        if isinstance(value, dict) and 'name' in value:10        if isinstance(value, dict) and 'name' in value:
18            name = value['name'].lower()11            name = value['name'].lower()
n19            if name in ["храст", "shrub", "bush"]:n12            if name in ["храст", "shrub", "bush"]:  
13                nonlocal total_cost, found_valid_shrub 
20                found_valid_shrub = True14                found_valid_shrub = True
21                cost = value.get('cost', 0)15                cost = value.get('cost', 0)
22                if isinstance(cost, (int, float)):16                if isinstance(cost, (int, float)):
23                    total_cost += round(cost, 2)17                    total_cost += round(cost, 2)
nn18                    if key:
24                    named_shrubs_names.append(key)  19                        named_shrubs_names.append(key)
20 
21    for item in args:
22        process_shrub(item)
23    for key, value in kwargs.items():
24        process_shrub(value, key)
2525
26    if not found_valid_shrub or total_cost > 42.00:26    if not found_valid_shrub or total_cost > 42.00:
27        return "Ni!"                    27        return "Ni!"                    
28      28      
29    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд29    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд
30    if total_cost > 0:30    if total_cost > 0:
31        int_cost = int(total_cost) 31        int_cost = int(total_cost) 
32        if int_cost == 0 or len(unique_letters) % int_cost != 0:32        if int_cost == 0 or len(unique_letters) % int_cost != 0:
33            return "Ni!"33            return "Ni!"
34        34        
35    return f"{total_cost:.2f}лв"                            35    return f"{total_cost:.2f}лв"                            
3636
tt37 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1f1
22
n3def function_that_says_ni(*args, **kwargs):n3def function_that_says_ni(*args, **kwargs):    
4    
5    total_cost = 0.04    total_cost = 0.0
6    named_shrubs_names = []5    named_shrubs_names = []
7    found_valid_shrub = False6    found_valid_shrub = False
87
9    for arg in args:8    for arg in args:
10        if isinstance(arg, dict) and 'name' in arg:9        if isinstance(arg, dict) and 'name' in arg:
11            name = arg['name'].lower()10            name = arg['name'].lower()
12            if name in ["храст", "shrub", "bush"]:11            if name in ["храст", "shrub", "bush"]:
13                found_valid_shrub = True12                found_valid_shrub = True
14                cost = arg.get('cost', 0)13                cost = arg.get('cost', 0)
15                if isinstance(cost, (int, float)):14                if isinstance(cost, (int, float)):
n16                    total_cost += round(cost, 2)n15                    total_cost += round(cost, 2)   
17 
18   
19    for key, value in kwargs.items():16    for key, value in kwargs.items():
20        if isinstance(value, dict) and 'name' in value:17        if isinstance(value, dict) and 'name' in value:
21            name = value['name'].lower()18            name = value['name'].lower()
22            if name in ["храст", "shrub", "bush"]:19            if name in ["храст", "shrub", "bush"]:
23                found_valid_shrub = True20                found_valid_shrub = True
24                cost = value.get('cost', 0)21                cost = value.get('cost', 0)
25                if isinstance(cost, (int, float)):22                if isinstance(cost, (int, float)):
26                    total_cost += round(cost, 2)23                    total_cost += round(cost, 2)
27                    named_shrubs_names.append(key)  24                    named_shrubs_names.append(key)  
n28                    n
2925
n30    if not found_valid_shrub:n26    if not found_valid_shrub or total_cost > 42.00:
31        return "Ni!"                27        return "Ni!"                    
32 
33     28      
34    if total_cost > 42.00:
35        return "Ni!"    
36 
37    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд29    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд
n38 n
39    if total_cost > 0:30    if total_cost > 0:
40        int_cost = int(total_cost) 31        int_cost = int(total_cost) 
41        if int_cost == 0 or len(unique_letters) % int_cost != 0:32        if int_cost == 0 or len(unique_letters) % int_cost != 0:
42            return "Ni!"33            return "Ni!"
n43 n34        
44   
45    return f"{total_cost:.2f}лв"                            35    return f"{total_cost:.2f}лв"                            
4636
t47 t
48 
49 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1f1
22
3def function_that_says_ni(*args, **kwargs):3def function_that_says_ni(*args, **kwargs):
4    4    
5    total_cost = 0.05    total_cost = 0.0
6    named_shrubs_names = []6    named_shrubs_names = []
7    found_valid_shrub = False7    found_valid_shrub = False
88
9    for arg in args:9    for arg in args:
10        if isinstance(arg, dict) and 'name' in arg:10        if isinstance(arg, dict) and 'name' in arg:
11            name = arg['name'].lower()11            name = arg['name'].lower()
12            if name in ["храст", "shrub", "bush"]:12            if name in ["храст", "shrub", "bush"]:
13                found_valid_shrub = True13                found_valid_shrub = True
14                cost = arg.get('cost', 0)14                cost = arg.get('cost', 0)
15                if isinstance(cost, (int, float)):15                if isinstance(cost, (int, float)):
16                    total_cost += round(cost, 2)16                    total_cost += round(cost, 2)
1717
18   18   
19    for key, value in kwargs.items():19    for key, value in kwargs.items():
20        if isinstance(value, dict) and 'name' in value:20        if isinstance(value, dict) and 'name' in value:
21            name = value['name'].lower()21            name = value['name'].lower()
22            if name in ["храст", "shrub", "bush"]:22            if name in ["храст", "shrub", "bush"]:
23                found_valid_shrub = True23                found_valid_shrub = True
24                cost = value.get('cost', 0)24                cost = value.get('cost', 0)
25                if isinstance(cost, (int, float)):25                if isinstance(cost, (int, float)):
26                    total_cost += round(cost, 2)26                    total_cost += round(cost, 2)
27                    named_shrubs_names.append(key)  27                    named_shrubs_names.append(key)  
28                    28                    
2929
30    if not found_valid_shrub:30    if not found_valid_shrub:
31        return "Ni!"                31        return "Ni!"                
3232
33     33     
34    if total_cost > 42.00:34    if total_cost > 42.00:
35        return "Ni!"    35        return "Ni!"    
3636
37    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд37    unique_letters = {char for name in named_shrubs_names for char in name}  #това е специално за Георги хд
3838
39    if total_cost > 0:39    if total_cost > 0:
40        int_cost = int(total_cost) 40        int_cost = int(total_cost) 
41        if int_cost == 0 or len(unique_letters) % int_cost != 0:41        if int_cost == 0 or len(unique_letters) % int_cost != 0:
42            return "Ni!"42            return "Ni!"
4343
44   44   
45    return f"{total_cost:.2f}лв"                            45    return f"{total_cost:.2f}лв"                            
4646
4747
n48print(function_that_says_ni({"name": "храст", "cost": 120}))n
49print(function_that_says_ni({"name": "храст", "cost": 1}))
50print(function_that_says_ni({"name": "чегарак", "cost": 1.00}))
5148
tt49 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op