提问人:Marwan Rabi 提问时间:8/15/2023 最后编辑:BarmarMarwan Rabi 更新时间:8/15/2023 访问量:74
返回 不要像打印一样转动 [关闭]
Return Don't turn like print [closed]
问:
我在codewars kata https://www.codewars.com/kata/58cbfe2516341cce1e000001/train/python 中有问题
def count_zeros_n_double_fact(n):
res = []
oddeven = []
revers = []
result = 1
c = 0
for i in range(n+1):
if i % 2 == 0 and i != 0:
oddeven.append(i)
for x in oddeven:
result = result * x
for z in reversed(str(result)):
if z == '0':
c+=1
else:
break
return c
我通过了测试,但在尝试中,任何大数字都会返回零
返回的测试:
返回的尝试:
但是,当我使用打印时,所有答案都是正确的
def count_zeros_n_double_fact(n):
res = []
oddeven = []
revers = []
result = 1
c = 0
for i in range(n+1):
if i % 2 == 0 and i != 0:
oddeven.append(i)
for x in oddeven:
result = result * x
for z in reversed(str(result)):
if z == '0':
c+=1
else:
break
print (c)
尝试打印
请帮帮我!
答:
0赞
azro
8/15/2023
#1
问题
你的逻辑是错误的,你总是使用奇数,但据说
- 如果为奇数,则将奇数相乘,直到
n
n
- 如果为偶数,则将偶数相乘,直到
n
n
修复
将所需的值作为 exercice 状态
def count_zeros_n_double_fact(n):
res = []
oddeven = []
revers = []
result = 1
c = 0
for i in range(1, n+1):
if (i % 2 == 0 and n % 2 == 0) or (i % 2 == 1 and n % 2 == 1):
oddeven.append(i)
for x in oddeven:
result = result * x
for z in reversed(str(result)):
if z == '0':
c+=1
else:
break
return c
提高
只循环每两个值并直接乘以它们,不要将它们存储在列表中
def count_zeros_n_double_fact(n):
result = 1
c = 0
for i in range((n + 1) % 2 + 1, n + 1, 2):
result *= i
for z in reversed(str(result)):
if z == '0':
c += 1
else:
break
return c
其他方式
from functools import reduce
from operator import mul
def count_zeros_n_double_fact(n):
result = str(reduce(mul, range((n + 1) % 2 + 1, n + 1, 2)))
return len(result) - len(result.rstrip("0"))
评论
0赞
Marwan Rabi
8/15/2023
非常感谢您的精彩回答,感谢您的努力
评论
9
oddeven
print
return
return
return c