Tuesday, January 29, 2019

codingdirectional: Return odd or even position from a list of numbers

Hello and welcome back to one day one answer series. In this chapter, we will need to return the position of either an odd or even number from a list of numbers following the below condition.

If there is only one odd number in a list of odd-even numbers then return the position of that odd number or else return the position of the even number. The solution for this question is very straight forward, after seeing the below solution do leave your own solution below this post.

def iq_test(numbers):

    num_dict = dict()
    num_dict['even'] = 0
    num_dict['odd'] = 0
    number_list = numbers.split(' ')
    index = 1
    even_index = 0
    odd_index = 0

    for num in number_list:
        if(int(num) % 2 == 0):
            num_dict['even'] += 1
            even_index = index
        else:
            num_dict['odd'] += 1
            odd_index = index
            
        index += 1

    if(num_dict['even'] > num_dict['odd']):
        return odd_index
    elif(num_dict['odd'] > num_dict['even']):
        return even_index
        

As you can see we do not need to worry about the position which will be returned by the program because there is only a single odd number or a single even number so there will be only one position that program needs to worry about.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...