我希望我能用Python完成以下内容...
填写空格完成函数“even_numbers(n)"。该函数应该计算从0到给定的“n”数的序列中存在多少个偶数,其中0计数为偶数。例如,even_numbers(25)应该返回13,even_numbers(6)应该返回4。
def even_numbers(n):
count = 0
current_number = 0
while ___ # Complete the while loop condition
if current_number % 2 == 0::
___ # Increment the appropriate variable
___ # Increment the appropriate variable
return count
print(even_numbers(25)) # Should print 13
print(even_numbers(144)) # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0)) # Should print 1
我已经尝试了我能想到的每一种变化来改变我能想到的每一个变量。我参考了课程作业(我已经在这个问题上坚持了一个星期,而且还在继续计算),我已经搜索了堆栈溢出,并发现多个变体引用不完全是我需要做的(而且从我现在学习的地方来看,最先进的是……即使他们解决了问题,他们也没有……我还是试了试,希望灯泡会熄灭,但它没有)。
我一直在尝试让print(even_numbers(#))部分匹配起来...使脚本工作。
有没有人可以向我解释这一点而不直接给出答案?我真的很想知道我错在哪里,为什么。我是一个完全的新手,大部分是自学的书籍。
尝试(其中一些)
def even_numbers(n):
count = 0
current_numbers = 0
while n > current_numbers: # Complete the while loop condition
if current_numbers % 2 == 0:
count = count + 1 # Increment the appropriate variable
else:
current_numbers = current_numbers + 1 # Increment the appropriate variable
return count
print(even_numbers(25)) # Should print 13
print(even_numbers(144)) # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0)) # Should print 1
Evaluation took more than 5 seconds to complete.
Please try again with a simpler expression.
def even_numbers(n):
count = 0
current_number = 0
while n > current_number: # Complete the while loop condition
if current_number % 2 == 0:
count = count + 1 # Increment the appropriate variable
else:
current_number = current_number + 1 # Increment the appropriate variable
return count
print(even_numbers(25)) # Should print 13
print(even_numbers(144)) # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0)) # Should print 1
Evaluation took more than 5 seconds to complete.
Please try again with a simpler expression.
def even_numbers(n):
count = 0
current_numbers = 1
while n > current_numbers: # Complete the while loop condition
if current_numbers % 2 == 0:
count = count + 1 # Increment the appropriate variable
current_numbers = current_numbers + 1
else:
current_numbers = current_numbers + 1 # Increment the appropriate variable
return count
print(even_numbers(25)) # Should print 13
print(even_numbers(144)) # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0)) # Should print 1
12
71
499
0
5条答案
按热度按时间1qczuiv01#
在赋值的代码中没有
else:
。你需要在每次迭代中递增current_number
,而不仅仅是当数字是奇数时。否则当数字是偶数时,你会卡在同一个数字上。所以你不应该添加else:
块。此外,如果
n
是偶数,则结果应该计数n
,因此条件应该是current_number <= n
。nafvub8i2#
您正在计算从
current_number == 0
到current_number == n
的偶数,因此应该将current_number
初始化为0
,循环条件应该是current_number <= n
。修改您的第三次尝试,代码应该是:
最后,
current_number = current_number + 1
行在if
和else
分支中,因此可以将其提取出来并消除else
:ergxz8rk3#
我喜欢你的最后一次尝试。你需要从0开始
current_number
,并确保使用大于或等于符号:ki1q1bka4#
这让我得到了正确的答案
dgsult0t5#
这也是可行的,我绝对会提交这个。