Я полагаю, что смогу выполнить следующее в 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
В коде задания нет else:
. Вам нужно увеличивать current_number
каждую итерацию, а не только когда число нечетное. В противном случае вы застрянете на одном и том же номере, когда он будет четным. Поэтому вам не следует добавлять блок else:
.
Кроме того, результаты должны учитываться n
, если они четные, поэтому условие должно быть current_number <= n
.
def even_numbers(n):
count = 0
current_number = 0
while current_number <= n: # Complete the while loop condition
if current_number % 2 == 0::
count += 1 # Increment the appropriate variable
current_number += 1 # Increment the appropriate variable
return count
Мне нравится твоя последняя попытка. Вам нужно начать current_number
с 0 и обязательно использовать знак больше или равно:
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
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
Вы считаете четные числа от current_number == 0
до current_number == n
, поэтому вы должны инициализировать current_number
до 0
, а условие цикла должно быть current_number <= n
.
Изменив вашу третью попытку, код должен быть:
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
current_number = current_number + 1
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
Наконец, строка current_number = current_number + 1
находится как в ветви if
, так и в ветви else
, поэтому вы можете извлечь ее и удалить else
:
def even_numbers(n):
count = 0
current_number = 0
while current_number <= n: # Complete the while loop condition
if current_number % 2 == 0:
count += 1 # Increment the appropriate variable
current_number += 1 # Increment the appropriate variable
return count
Всем спасибо! Эти ответы очень помогли, и я записал их для дальнейшего использования (надеюсь, чтобы не рвать на себе волосы неделю...)
Это дало мне правильный ответ
def even_numbers(n):
count = 0
current_number = 0
while current_number <= n:
if current_number % 2 == 0:
count += 1
current_number += 1
return count
print(even_numbers(25))
print(even_numbers(144))
print(even_numbers(1000))
print(even_numbers(0))
Как сейчас написано, ваш ответ неясен. Пожалуйста, отредактируйте , чтобы добавить дополнительные сведения, которые помогут другим понять, как это отвечает на заданный вопрос. Вы можете найти больше информации о том, как писать хорошие ответы в справочном центре.
Это тоже работает, и я бы абсолютно согласен с этим.
def even_numbers(n):
count = 0
current_number = 0
while not current_number: # Complete the while loop condition
if current_number % 2 == 0:
count += n // 2 + 1 # Increment the appropriate variable
current_number = 1 # Increment the appropriate variable
return count
где 0 считается четным числом" - я в ужасе от того, что они это сказали. Может ли кто-нибудь найти определение «четного числа», где 0 не является четным?