Reputation: 251
So the function inputs a list, and a number. Then it should return the index of the list that the number is able to be divided by. If there is no numbers in the list it can be divided by, then it should just return a blank list.
For example,
div([5,10,15,2,34],10)
[0,1,3]
Here is my coding:
def div(nlst, n):
nlst = []
for div in nlst:
if n % nlst == 0:
return nlst.index(div)
else: []
What is wrong with my code?
Upvotes: 1
Views: 1045
Reputation: 31013
List comprehensions to the rescue:
def div(nlst, n):
return [i for i,v in enumerate(nlst) if n % v == 0]
>>> div([5,10,15,2,34], 10)
[0, 1, 3]
Upvotes: 1
Reputation: 32923
There are a few issues in your code:
def div(nlst, n):
nlst = [] # You are deleting the original list here!
for div in nlst: # The list nlst is empty
if n % nlst == 0: # Cannot use a list 'nlst' as an operand of the % operation.
return nlst.index(div) # You are returning a single element here
else: [] # This does nothing
This code will do the job:
def div(nlst, n):
result = []
for i, e in enumerate(nlst):
if n % e == 0:
result.append(i)
return result
A more compact version:
def div(nlst, n):
return [i for i, e in enumerate(nlst) if n % e == 0]
Upvotes: 1