Jenifer J
Jenifer J

Reputation: 15

How to use groupby? using groupby to find odd or even number by getting inputs from a function

Below is my task

  1. Define a function even_or_odd, which takes an integer as input and returns the string even and odd, if the given number is even and odd respectively.
  2. Categorise the numbers of list n = [10, 14, 16, 22, 9, 3 , 37] into two groups namely even and odd based on above defined function. Hint : Use groupby method of itertools module.
  3. Iterate over the obtained groupby object and print it's group name and list of elements associated with a group.

I have written the below code : I am getting the error 'str' object is not callable. Actually I am not sure how to use itertool groupby() by getting values from a function. Can someone guide me ?

from itertools import groupby

def even_or_odd(r):
    for i in r:
        if i%2 == 0:
            return "even"
        else:
            return "odd"


n = [10, 14, 16, 22, 9, 3 , 37]


for key, group in groupby(n, even_or_odd(n)):
    if key == even:
        print(key, list(group))
    else:
        print(key, list(group))

Upvotes: 0

Views: 1001

Answers (2)

Dinkar Jaiswar
Dinkar Jaiswar

Reputation: 9

groupby is a method calculates the keys for each element present in iterable which means one element from iterable object get evaluate at a time.

as grouping of all the even and odd numbers will not work this way. for every element it will return "even": value or "odd": value so it might return new key every time.

Upvotes: 0

Beny Gj
Beny Gj

Reputation: 615

here the solution according to the doc https://docs.python.org/3.8/library/itertools.html#itertools.groupby

The key is a function computing a key value for each element

from itertools import groupby

n = [10, 14, 16, 22, 9, 3 , 37]

def even_or_odd(val):
     if val%2 == 0:
       return "even"
     else:  
       return "odd"


for key, group in groupby(n, even_or_odd):
    print(key, list(group)) 

output :

even [10, 14, 16, 22]
odd [9, 3, 37]



Upvotes: 0

Related Questions