问题:
编写一个程序,搜索列表以查找第一个奇数.如果找到奇数,则找到奇数后面的第一个偶数.返回第一个奇数和第一个偶数之间的距离.如果没有找到奇数,或者在奇数后面没有偶数,则返回-1.
我的代码:
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]))
Run Code Online (Sandbox Code Playgroud)
我的输出:
6
2
3
1
1
4
5
4
1
Run Code Online (Sandbox Code Playgroud)
期望的输出:
6
2
3
1
-1
4
5
4
-1
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?有没有比我做的更好的解决这个问题的方法?
你可以用迭代器来解决这个问题.
迭代器是一个"记住"其在列表中的当前位置的对象.创建迭代器时,它指向列表中的第一个元素.然后,您可以使用该next函数向前移动迭代器.
所以这个想法是这样的:
在第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
Run Code Online (Sandbox Code Playgroud)