gpt4 book ai didi

Python - 列表操作练习

转载 作者:行者123 更新时间:2023-12-01 08:47:37 25 4
gpt4 key购买 nike

问题:

Write a program that will search a list to find the first odd number. If an odd number is found, then find the first even number following the odd number. Return the distance between the first odd number and the first even number. Return -1 if no odd numbers are found or there are no even numbers following an odd number.

我的代码:

def go(list1):
dist = 0
odd = 0
even = 0
for i in range(0,len(list1)):
if list1[i] % 2 == 1:
odd = list1[i]
break
else:
odd = list1[0]
list2 = list1[list1.index(odd)+1:]
for i in range(0,len(list2)):
if list2[i] % 2 == 0:
even = list2[i]
break
else:
even = list2[0]
return list2.index(even) + list1.index(odd) + 1 - list1.index(odd)

print(go([7,1,5,3,11,5,6,7,8,9,10,12345,11]))
print(go([11,9,8,7,6,5,4,3,2,1,-99,7]))
print(go([10,20,30,40,5,41,31,20,11,7]))
print(go([32767,70,4,5,6,7]))
print(go([2,7,11,21,5,7]))
print(go([7,255,11,255,100,3,2]))
print(go([9,11,11,11,7,1000,3]))
print(go([7,7,7,11,2,7,7,11,11,2]))
print(go([2,4,6,8,8]))

我的输出:

6
2
3
1
1
4
5
4
1

期望的输出:

6
2
3
1
-1
4
5
4
-1

我做错了什么?有没有比我做的更好的方法来解决这个问题?

最佳答案

您可以使用 iterator 来解决此问题.

迭代器是一个对象,它“记住”它在列表中的当前位置。创建迭代器时,它指向列表中的第一个元素。然后,您可以使用 next 将迭代器向前移动。功能。

所以想法是这样的:

  1. 创建一个迭代器
  2. 向前移动迭代器,直到找到第一个奇数
  3. 向前移动,直到找到偶数,数步数

在第 3 步中,enumerate函数对于计算迭代器跳过了多少元素非常有用。

def go(iterable):
# step 1: get an iterator for this iterable
itr = iter(iterable)
try:
# step 2: advance the iterator to the first odd number
next(num for num in itr if num % 2 == 1)

# step 3: count the elements up to the next even number
return next(i for i, num in enumerate(itr, 1) if num % 2 == 0)
except StopIteration:
# StopIteration is raised if the iterator reaches the end without
# finding a suitable number
return -1

关于Python - 列表操作练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50218908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com