Reputation: 109
Write a function that receives a list of numbers and a list of terms and returns only the elements that are divisible by all of those terms. You must use two nested list comprehensions to solve it.
divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # returns [12, 6]
def divisible_numbers(a_list, a_list_of_terms):
I have a vague pseudo code so far, that consists of check list, check if divisible if it is append to a new list, check new list check if divisible by next term and repeat until, you have gone through all terms, I don't want anyone to do this for me but maybe a hint in the correct direction?
Upvotes: 3
Views: 9026
Reputation: 1
if you want to get input from the user using this type of way.
enter code hereprint("numbers which are divisible by 5")
user_input=eval(input("enter the value in list type [1,2,3]: "))**
print(type(user_input)) if type(user_input)==list: for i in
user_input: if(i%5==0): print(i,end=",") else:
print("none")
numbers that are divisible by 5 enter the value in list type [1,2,3]:
[15,10,20,45,69] <class 'list'> 15,10,20,45,
Upvotes: 0
Reputation: 117866
The inner expression should check if for a particular number, that number is evenly divisible by all of the terms in the second list
all(i%j==0 for j in a_list_of_terms)
Then an outer list comprehension to iterate through the items of the first list
[i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
All together
def divisible_numbers(a_list, a_list_of_terms):
return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
Testing
>>> divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3])
[12, 6]
Upvotes: 9