Rohitjojo09
Rohitjojo09

Reputation: 49

python question print the number of elements which are divisible by a

my code is :-

list_1 = [i for i in range(1, 51)]
a=int(input())
list_1.remove(a)
count=0
for i in list_1:
    if(i%a==0):
      count=count+1
      print(count)

but output come is this way when input is 12 then output come is

1
2
3

but i need output 3 only so how to do this please help

Upvotes: 0

Views: 1257

Answers (3)

Olivier Melançon
Olivier Melançon

Reputation: 22324

You can use sum.

sum(x % a == 0 for x in list_1)

Since True == 1 and False == 0, this sums to how many times the predicate is true.

Upvotes: 1

pkpatill
pkpatill

Reputation: 1

Break the if statement and use the ending condition i.e.i=50 e.g.

    l=list(range(1,51))
    a=int(input())
    count=-1
    for i in l:
        if(i%a==0):
            count=count+1
    print(count)

Upvotes: 0

Jonas Wolff
Jonas Wolff

Reputation: 2244

print(len([i for i in list_1 if i%a == 0]))

this creats a list with the divisible numbers, and gets the length of the list. I will also point out that len() is a function of O(1) timecomplexity, meaning only one loop takes place - because of the list comprehension - , and list comprehension tents to be quite fast :)

Upvotes: 0

Related Questions