In: Computer Science
Using the Python program:
a/ Write a program that adds all numbers from 1 to 100 to a list (in order). Then remove the multiples of 3 from the list. Print the remaining values.
b/ Write a program that initializes a list with ten random integers from 1 to 100. Then remove the multiples of 3 and 5 from the list. Print the remaining values.
Please show your work and explain. Thanks
SOLUTION
a)
list =[i for i in range(1,101)] #creating a list containing numbers from 1 to 100
print(list) #printing the created list
#for loop to traverse the list and remove multiples of 3
for i in list:
if(i%3 == 0): #condition to check if the element in the list is a multiple of 3 or not
list.remove(i) #if yes we remove that element
print("\nList after removing multiples of 3:")
print(list)
OUTPUT
b)
import random #importing random package
list = [] #declaring empty list
for i in range(0,10): #for loop to fill list with random numbers between 1 and 100
n = random.randint(1,100)
list.append(n)
print(list)
for i in list: #for loop to remove multiples of 3 and 5 from the list
if(i%3 == 0 or i%5 == 0):
list.remove(i)
print("\nList after removing multiples of 3 and 5:")
print(list)
OUTPUT