Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
和前面的习题 Find The Parity Outlier 类似,只不过这次给的参数是一个字符串,返回值是特定的偶数或者是奇数的下标。
! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)
##Examples :
iq_test(“2 4 7 8 10”) => 3 // Third number is odd, while the rest of the numbers are even
iq_test(“1 2 1 1”) => 2 // Second number is even, while the rest of the numbers are odd
def iq_test(num):
numbers = num.split()
for i in range(len(numbers)-1):
if int(numbers[i])%2 != int(numbers[i+1])%2:
if int(numbers[i-1])%2 == int(numbers[i+1])%2:
return i+1
else:
return i+2
更简单的方法:
def iq_test(num):
numbers = [int(i)%2==0 for i in num.split()]
return numbers.index(True)+1 if numbers.count(True) == 1 else numbers.index(False)+1
本文介绍了一种帮助解决IQ测试中寻找奇偶性不同的数字的方法。通过编写程序,可以在一系列数字中快速定位到那个与众不同的数字,并返回其位置。此程序对于解决特定类型的IQ测试题目非常有效。
4万+

被折叠的 条评论
为什么被折叠?



