Home > Back-end >  How to group the list based on count of previous list odd integer?
How to group the list based on count of previous list odd integer?

Time:02-10

I need to group the list based based on (N -count of previous list odd integer)

Example:

Input

n=5
l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the input has nested list at 0th index at the size of n.We need to group the other elements based on this condition

n - count of odd integers

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the nested loop has 1 odd integer: Therefore n - count of odd integers = 5-1= 4 so i need to group next four elements.

>>[[45, 20, 40, 26, 32], [10, 20, 13, 16], 5, 10, 8, 5, 4, 2, 1]

then the second nested loop has 1 odd integer:

Therefore n - count of odd integers = 4-1= 3 so I need to group next three elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], 5, 4, 2, 1]

then the third nested loop has 1 odd integer:

Therefore n - count of odd integers = 3-1= 2 so I need to group next 2 elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], 2, 1]

...like that I need to do

the final output to be

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], 1]

My code:

l1=[l[i:(i n)] for i in range(0,len(l),n)]

my output:

[[45, 20, 40, 26, 32], [10, 20, 13, 16, 5], [10, 8, 5, 4, 2], [1]]

What changes I need to do???

CodePudding user response:

I'm sure there are many ways to do this:

l = [[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
n = len(l[0])
r = [l[0]]
k = 1

while k < len(l):
    n -= sum(x % 2 for x in r[-1])
    r.append(l[k:k n])
    k  = n

print(r)

CodePudding user response:

Code commented inline:

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
n = 5
a = l[0]
b = l[1:]
result = [a]
while len(b) > 0:
  # find the n-count of odd
  k = n-sum([1 for i in a if i %2 != 0])  
  # get next sublist and the remainig elements
  a, b = b[:k], b[k:]
  result.append(a)  
  n -= 1

print (result)

output:

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], [1]]
  • Related