英文:
Delete Starting Even Numbers
问题
这个函数会重复地删除列表的第一个元素,直到找到一个奇数或元素用尽。它将接受一个数字列表作为输入参数,并返回修改后的列表,其中任何在列表开头的偶数都被删除。为此,我们需要以下步骤:
-
定义我们的函数,接受一个名为
my_list
的单一输入参数,该参数是一个数字列表。 -
遍历列表中的每个数字,如果列表中仍然有数字并且我们还没有遇到奇数,则执行以下操作:
-
在循环内,如果列表中的第一个数字是偶数,则删除列表的第一个数字。
-
一旦找到奇数或元素用尽,返回修改后的列表。
我编写了一个名为delete_starting_evens()
的函数,它有一个名为my_list
的参数。
该函数应该从my_list
的前面删除元素,直到列表的前面不再是偶数。然后函数应返回my_list
。
例如,如果my_list
起始为[4, 8, 10, 11, 12, 15]
,那么delete_starting_evens(my_list)
应返回[11, 12, 15]
。
我的代码:
def delete_starting_evens(my_list):
for i in my_list:
if i % 2 == 0:
my_list.remove(i)
else:
break
return my_list
a=[4,8,10,12,14,15,16,17,19,20]
print(delete_starting_evens(a))
问题在于函数在移除偶数索引而不是偶数数字。我期望函数应删除偶数数字,直到找到奇数数字或元素用尽。如何解决这个问题?
英文:
This function will repeatedly remove the first element of a list until it finds an odd number or runs out of elements. It will accept a list of numbers as an input parameter and return the modified list where any even numbers at the beginning of the list are removed. To do this, we will need the following steps:
-
Define our function to accept a single input parameter
my_list
which is a list of numbers -
Loop through every number in the list if there are still numbers in the list and if we haven’t hit an odd number yet
-
Within the loop, if the first number in the list is even, then remove the first number of the list
-
Once we hit an odd number or we run out of numbers, return the modified list
I wrote a function called delete_starting_evens()
that has a parameter named my_list
.
The function should remove elements from the front of my_list
until the front of the list is not even. The function should then return my_list
.
For example, if my_list
started as [4, 8, 10, 11, 12, 15]
, then delete_starting_evens(my_list)
should return [11, 12, 15]
.
My code:
def delete_starting_evens(my_list):
for i in my_list:
if i % 2 == 0:
my_list.remove(i)
else:
break
return my_list
a=[4,8,10,12,14,15,16,17,19,20]
print(delete_starting_evens(a))
The problem is that the function was removing the even indexes. I was expecting that the function should delete the even numbers until it finds the odd number or runs out of elements. How to solve it?
答案1
得分: -1
def delete_starting_evens(my_list):
idx = -1
for i in my_list:
if i % 2 == 1:
idx = my_list.index(i)
break
if idx == -1:
return []
else:
second_list = my_list[idx:]
return second_list
a = [4, 5, 8, 10, 12]
print(delete_starting_evens(a))
英文:
def delete_starting_evens(my_list):
idx=-1
for i in my_list:
if i % 2 == 1:
idx = my_list.index(i)
break
if(idx==-1):
return []
else:
second_list = my_list[idx:]
return second_list
a=[4,5,8,10,12]
print(delete_starting_evens(a))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论