Problem:
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.
My Code:
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]))
My Output:
6
2
3
1
1
4
5
4
1
Desired Output:
6
2
3
1
-1
4
5
4
-1
What am I doing wrong? Is there a better approach to this problem than what I have done?
-1. Do you think you wrote any handling for the cases where you're supposed to return-1?oddwould get set to the value of the last item instead of some value to indicate that it was not found.oddvariable to an even value in the array? In my opinion, it makes more sense to setodd = -1initially, then check if it is still-1after that loop.return list2.index(even) + list1.index(odd) + 1 - list1.index(odd), through algebra we can simplify this toreturn list2.index(even) + 1, which does not make sense w.r.t. the goal condition of the distance between the first odd number and the first even number.