Home > Software engineering >  Dictionary with list values to store the divisors of all the numbers code doesn't work?
Dictionary with list values to store the divisors of all the numbers code doesn't work?

Time:10-25

The task says 'Write a program that reads N, then reads N integer numbers. The program should use a dictionary with list values to store the divisors of all the numbers. The list of divisors will be printed for each number, in ascending order of the numbers. If the number does not have divisors it should not appear in the dictionary.' for which I wrote the following code:

from collections import defaultdict


n = int(input())

ls = []

for i in range(2, n 1):
    if n % i == 0 and n / i != 1:  
        ls.append(i)


a = defaultdict(list)

for divisor in ls:
    a[n].append(divisor)


for key,value in a.items():
    print(key, ':', value)



Sample Input:

3
12
6
13

Sample Output:

6: [2, 3]
12: [2, 3, 4, 6]

Now, they didn't specify the exclude prime divisors but that is what I concluded from their sample output. When I run the code on their platform, it says 'empty'. Is it something wrong with my code? Edit: I think the issue is that it takes only the first input which is 3 runs the code and it outputs empty becuase it has no divisors but it doesn't take the second input and run the code again.

CodePudding user response:

I think the issue is that it takes only the first input which is 3 runs the code and it outputs

Yes, you are correct. You're almost there!

That is how input() works: It will stop reading the input when you press "enter" on your keyboard. More info on the docs or on this GeeksForGeeks article.

I'm pretty sure that's why the task says "a program that reads N, then reads N integer numbers" They're telling you that you're gonna need to prompt for "how many numbers do you want to find divisors for?" first, and after that, prompt as many times as indicated in that first integer.

So, basically, it all boils down to run your "divisor finder" as many times as indicated in that initial integer. You'll need some sort of loop for that (a for or a while)

For instance, with a for, you could do something like:

from collections import defaultdict

a = defaultdict(list)
tries = int(input("Input how many numbers you want to find divisors for? -> "))
for i in range(tries):
    n = int(input(f"Enter number {i   1}: "))
    ls = []
    for i in range(2, n 1):
    #
    # SAME AS BEFORE ...
    # ...

Or, with a while:

from collections import defaultdict

a = defaultdict(list)
tries = int(input("Input how many numbers you want to find divisors for? -> "))
while tries:
    tries -= 1
    n = int(input(f"Enter number to find divisors for: "))
    ls = []
    for i in range(2, n 1):
    #
    # SAME AS BEFORE ...
    # ...
  • Related