Reputation: 11
Given a list of numbers, you have to print those numbers which are not multiples of 3 in python 3
Input Format:
The first line contains the list of numbers separated by a space.
Output Format:
Print the numbers in a single line separated by a space which are not multiples of 3.
Example:
Input:
1 2 3 4 5 6
Output:
1 2 4 5
Explanation:
Here the elements are 1,2,3,4,5,6 and since 3,6 are multiples of 3, removing them the list leaves 1,2,4,5.
Upvotes: 0
Views: 15412
Reputation: 1
n=(input("How many number you want to insert in a list"))
list=[ ]
for i in range(0,n):
a=int(input("enter elements"))
list.append(a)
for i in(list):
if(i%3!=0):
print(i,"are not multiply of 3")
else:
print("multiply of 3")
Upvotes: 0
Reputation: 1
a=list(map(int,input().split()))
b=list()
for i in range(len(a)):
if a[i]%3!=0:
b.append(a[i])
print(*b,sep=" ")
In the above code using two list namely a and b.The numbers which are not multiples of 3 from list a are appended to the list b and list b is printed
Upvotes: 0
Reputation: 1141
@Souvikavi's answer looks good. But the for loop can be simplified as:
numbers = input()
list = numbers.split()
newList = [item for item in list if int(item)%3!=0]
print(' '.join(newList))
or:
numbers = input()
newList = [item for item in numbers.split() if int(item)%3!=0]
print(' '.join(newList))
or even:
numbers = input()
print(' '.join([item for item in numbers.split() if int(item)%3!=0]))
Upvotes: 0
Reputation: 41903
There are any number of one-liner solutions. How about:
print(*(item for item in map(int, input().split()) if item % 3))
Upvotes: 1
Reputation: 108
Please don't ask by just copying your nptel assignment questions and ask for a solution, first try to solve and find where the bug is, how the input is given and what is the desired output. I also got stuck on this assignments before. Anyways here's the solution that should work fine, if it gets the job done, don't forget to accept the solution by clicking the tick on the left of this post.
x = input()
num = list(map(int, x.split()))
l =[]
for i in num:
if i%3 != 0:
l.append(i)
print(*l, sep = " ")
Upvotes: 1
Reputation: 1
The Logic is really simple, You need to remove all the number from the list that is divisible by 3.
Since list is used list.remove(item) method can be used.
and the output should be space separated so the list of the item can be joined together using space in between them,
Following code does the trick
numbers = input()
list = numbers.split()
for item in list:
if int(item)%3==0:
list.remove(item)
print(' '.join(list))
Input: 1 2 3 4 5 6
Output: 1 2 4 5
Upvotes: 0
Reputation: 1
Use the modulo operator. (%) This operator will yield the remainder from the division of the first argument with the second. So when you are wanting numbers that are not multiples of 3, another way to say that is you are looking for numbers whose remainder is not 0 when divided by 3.
x % 3 != 0.
Upvotes: 0