0

I have a nested for loop which is not running after the first iteration

N, M = map(int, input().split())
numbers = map(int, input().split())

dic = {}
for m in range(N):
  dic.setdefault(m,[])
  for n in numbers:
      if n % N == m:
      dic[m].append(n)
print(dic)

The above code is generating the following result {0: [3, 42], 1: [], 2: []} for the sample data down bellow:

3 5
1 3 8 10 42

However I would like to get {0: [3, 42], 1: [1, 10], 2: [8]} What am I doing wrong?

lucasbbs
  • 349
  • 4
  • 14

2 Answers2

3

The problem is that map returns an iterator, and you are consuming the iterator completely in the first outer loop. You need:

numbers = [int(k) for k in input().split()]

instead of using map.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Or `numbers = list(map(int, input().split()))`, where the `list` builtin transforms the iterator into a list (although Tim's answer is more pythonic). – larsks Aug 11 '21 at 03:33
  • Just for the sake of giving alternatives, ```numbers = [*map(int, input().split())]``` works too. – sj95126 Aug 11 '21 at 03:33
  • It's an interesting debate. I prefer the way the `map` call looks, but I've been burned just as the OP has, so I generally avoid it in favor of a list comprehension. – Tim Roberts Aug 11 '21 at 03:38
0

try this:

N, M = map(int, input().split())
numbers = [int(x) for x in input().split()]

dic = {}
for m in range(N):
    dic.setdefault(m,[])
    for n in numbers:
        print(n % N)
        if n % N == m:
            dic[m].append(n)
print(dic)