英文:
ZeroDivisionError: division by zero. What needs to be changed
问题
def get_success_rate(statistics: str) -> int:
count = 0
for i in statistics:
if statistics == '':
return 0
if i == '1':
count += 1
res = count / len(statistics) * 100
return round(res)
print(get_success_rate("11100")) # 60
print(get_success_rate("1100")) # 50
print(get_success_rate("000000")) # 0
print(get_success_rate("11111")) # 100
print(get_success_rate("")) # 0
60
50
0
100
Traceback (most recent call last):
File "D:\Program Files\Python\CHERHOBNK\Folder - 1\draft.py", line 807, in <module>
print(get_success_rate("")) # 0
File "D:\Program Files\Python\CHERHOBNK\Folder - 1\draft.py", line 799, in get_success_rate
res = count / len(statistics) * 100
ZeroDivisionError: division by zero
<details>
<summary>英文:</summary>
def get_success_rate(statistics: str) -> int:
count = 0
for i in statistics:
if statistics == '':
return 0
if i == '1':
count += 1
res = count / len(statistics) * 100
return round(res)
print(get_success_rate("11100")) # 60
print(get_success_rate("1100")) # 50
print(get_success_rate("000000")) # 0
print(get_success_rate("11111")) # 100
print(get_success_rate("")) # 0
60
50
0
100
Traceback (most recent call last):
File "D:\Program Files\Python\CHERHOBNK\Folder - 1\draft.py", line 807, in <module>
print(get_success_rate("")) # 0
File "D:\Program Files\Python\CHERHOBNK\Folder - 1\draft.py", line 799, in get_success_rate
res = count / len(statistics) * 100
ZeroDivisionError: division by zero
</details>
# 答案1
**得分**: 2
将空字符串检查移到循环外:
```python
def get_success_rate(statistics: str) -> int:
if statistics == '':
return 0
count = 0
for i in statistics:
if i == '1':
count += 1
res = count / len(statistics) * 100
return round(res)
如果字符串为空,循环将不会执行,因此检查实际上将被跳过。
英文:
Move the empty string check outside the loop:
def get_success_rate(statistics: str) -> int:
if statistics == '':
return 0
count = 0
for i in statistics:
if i == '1':
count += 1
res = count / len(statistics) * 100
return round(res)
If string is empty the loop will not be executed so the check will actually be skipped.
答案2
得分: 1
你函数的逻辑不够严谨。从代码看,你可能希望在迭代for i in statistics
之前,先处理if statistics == ''
这个条件判断。这样,你的函数就不会再出现除以零的错误。
你当前代码的问题在于,当statistics == ''
时,迭代根本不会发生,没有东西可以进行迭代。然后,程序调用res = count / len(statistics) * 100
,由于len("")
等于零,就会导致除以零的错误。
英文:
The logic of your function is not sound. Guessing from the code, you probably want to do the if statistics == ''
clause before your iteration, for i in statistics
. Then you'll no longer have the division by zero error of your function.
the problem with your current code, is that the iteration doesn't happen when statistics == '', there's nothing to iterate over. And then the call is made to res = count / len(statistics) * 100
, and as len("")
equals zero, that's giving you the division by zero error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论