+ 1

Python/list comprehensions and multiples

Hi all, Could someone give me a steer as to where I’m going wrong here. Trying to find all the multiples of both 3 & 5 up to and input interger; x = int(input()) #your code goes here numbers = list(range(0, x) mutiples = [number for number in numbers if number % 3 == 0 and number % 5 == 0] print(multiples)

3rd Apr 2021, 8:07 AM
Sean Kelly
Sean Kelly - avatar
7 Respuestas
+ 9
You forgot a parenthesis. It should be: numbers = list(range(0, x)) Also notice that the list multiples will include 0 too (since 0 % *any number* is equal to 0) and that number will be included only if it is divisible both by 5 and 3. You could write: multiples = [number for number in numbers if number != 0 if number % 3 == 0 or number % 5 == 0] Edit: I thought it should have included numbers divisible either by 3 or 5. I just noticed my mistake
3rd Apr 2021, 8:21 AM
Ciro Manuel Penna
Ciro Manuel Penna - avatar
+ 3
Any number fully divisible by both 3 and 5 are multiples of 15. So it might be considerable to utilize the stepping parameter of `range()` function, and start the range from 15. multiples = [ number for number in range( 15, x, 15 ) ]
3rd Apr 2021, 9:32 AM
Ipang
+ 1
Thanks Ciro Manuel Penna ! 2 hours pickle for a forgotten parenthesis grrrrr
3rd Apr 2021, 9:12 AM
Sean Kelly
Sean Kelly - avatar
+ 1
Mirielle[ Exams ] for divisibility "x % y == 0" is more expressive / clearer than "not x % y" imo. Just an opinion, but I read the first variant way more often. And including the "not" they differ in length only by a single space. [x for x in y if x > 0 and x % 3 and x % 5] return numbers not divisible by 3 or 5, so that may serve as example; mistakes are not as easy to spot. range starts at 0 by default, so range(0, x) can be shortened to range(x)
3rd Apr 2021, 9:51 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
num = input("enter a number: ") l = [number for number in range(0,int(num)+1) if number % 3 == 0 and number % 5 == 0] print(l) # no need to declare range as list!
3rd Apr 2021, 11:31 AM
iTech
iTech - avatar
- 1
This get you all cases green: x = int(input()) #your code goes here1 l = [number for number in range(0,int(x)+1) if number % 3 == 0 and number % 5 == 0] print(l) Ask if u have some questions!
17th Nov 2021, 4:46 PM
Stefan Bartl
Stefan Bartl - avatar