Search code examples
pythonlogic

IQ test function in Python not working as intended


I'm having trouble with this code below.

My task is to create a function, that among the given numbers finds one that is different in evenness, and returns a position of that number. The numbers are given as a string. So far I have managed to convert the string into an integer list, then using for loop to iterate through each number.

The problem I'm encountering is that I've managed to return only the position of an odd number among the even numbers, and I can't continue on with the code for vice versa action, because it only returns the position of the odd number.

Here is the code:

def iq_test(numbers):
    # Splitting the "numbers" string
    num_split = numbers.split()
    # converting the splitted strings into int
    num_map = map(int, num_split)
    # converting the object into list
    list_num = list(num_map)
    for n in list_num:
        if not n%2 == 0:
            return list_num.index(n) + 1

Solution

  • Your problem is, that you are assuming, that you are searching for the first even number. What you have to do, is to first decide, what you are searching for. You could for example simply first count the number of even numbers. If it is one, then you are looking for an even number, otherwise, you are looking for an odd. As you don't care for the actual numbers, I would map all of them to their value mod 2 as so:

    num_map = list(map(lambda x: int(x) % 2, num_split))
    

    Then, the rest is simple. For example like this:

    def iq_test(numbers):
        # Splitting the "numbers" string
        num_split = numbers.split()
        # converting the splitted strings into even (0) or odd (1)
        num_map = list(map(lambda x: int(x) % 2, num_split))
        # return the correct position based on if even or odd is in search
        evens = num_map.count(0)
        if evens == 1:
            return num_map.index(0) + 1
        else:
            return num_map.index(1) + 1