Home > Mobile >  How to plot the quantity of all divisiors of numbers of a specific range in a bar chart with a count
How to plot the quantity of all divisiors of numbers of a specific range in a bar chart with a count

Time:11-19

I have a question regarding the following exercise. My exercise is to plot the amount/quantity of divisors in a bar chart for the numbers 1 to 10000. The x-axis needs to be filled with the divisors and the y-axis has to be the amount of each specivic divisor, using a counter method. I have created a method called divisor(), which is able to determine the divisors of numbers. In the following part is my written code so far:

from collections import Counter
import matplotlib.pyplot as plt
import numpy as np

x = [divisor(i) for i in np.arange(1,1001)]
y = Counter(x)

plt.bar(x,y)

I thought that the counter method would count each divisor and display it in the bar chart, but it is not working. I am thinking that the list is the problem and that i need to put everything in a dictionary, but I am really not sure. I would appreciate any clue. Thank you for your time!

The divisor method is:

import numpy as np

def divisor(n):
    n = [i for i in np.arange(1, n 1) if n%i == 0]
    return n

divisor(45)

---->[1, 3, 5, 9, 15, 45]

CodePudding user response:

If, as I suspect, your divisor function takes an integer as input and returns a list (iterable) of its divisors, you need a nested loop.

counting the number of times a given integer is a divisor of the first 1000 integers

Using a nested list comprehension:

counts = Counter(d for i in np.arange(1,1001) for d in divisor(i))

x,y = zip(*counts.items())

plt.bar(x, y)

Output:

number of times an integer is divisor for the first 1000 numbers

counting the number of divisors of each of the first 1000 integers

counts = [len(divisor(i)) for i in range(1, 1001)]

plt.bar(range(1, 1001), counts)

Output:

enter image description here

CodePudding user response:

I also have another question for another divisor task, which I completed but I think it could be more compact. I needed to return the Number of a range from 1 to 1000, which has the greatest amount of divisors. It has to be in a list comprehension and only one sentence. This is my code:

[len(divisor(i)) for i in np.arange(1,1001)].index(max([len(divisor(i)) for i in np.arange(1,1001)])) 1

The problem is that the index value 0 is the first element, so i had to add 1. I don´t think this is ideal:(

  • Related