0
i am running into a problem with multiples of 3 and 5
The Question: "You are given a task to find all of the whole numbers below 100 that are multiples of both 3 and 5. Create an array of numbers below 100 that are multiples of both 3 and 5, and output it." in python i have made the following code: import numpy as np data = np.array([]) for x in range(1,101): if x%5 ==0 and x%3 ==0: data = np.append(data, x) print(data) Which prints the array (15, 30, 45, 60, 75, 90) Am i being incredibly dumb here? I cannot understand why this is not the correct solution.
7 Answers
+ 2
#try this
if x%5 == 0 or x%3 == 0:
+ 1
your code return:
[15. 30. 45. 60. 75. 90.]
mine return:
[15, 30, 45, 60, 75, 90]
why did u use numpy?
list = []
for i in range(1,100):
if i % 3 == 0 and i % 5 == 0:
list.append(i)
print(list)
+ 1
Note that (x%3==0 and x%5==0) is the same as (x%(3*5)==0), or (x%15==0).
Is there a requirement to use modulo? If not, then how about just using range with a step of 15?
print(list(range(15, 101, 15)))
+ 1
The problem is here that np.array([]) create an empty array with floats and added by np.append will append a decimal point to the end of each number. To prevent this behavior do:
data=np.array([],dtype='int16')
I had the same problem and I found the solution here: https://stackoverflow.com/questions/59328037/numpy-adds-a-dot-after-each-element-of-an-array-which-i-can-t-strip
A list with comma's is also not accepted, but here we see that an array is created, so I expect that we see comma's due to a localisation, where some country, as mine use a comma, as decimal point. Here is my complete code thats get accepted:
import numpy as np
x = np.arange(1, 100)
y = np.array([],dtype='int16')
for i in x:
if i%3==0 and i%5==0:
y = np.append(y,i)
print (y)
0
Used Numpy as it was part of the Numpy module in Python for Data Science, and it asked me to use the modulo operators to check if it was a multiple of both 3 and 5.
0
number = int(input())
sum = 0
for num in range(number):
if num % 3 == 0 or num % 5 == 0:
sum += num
print(sum)