如何获取给定数字的所有因子?

1 投票
2 回答
1014 浏览
提问于 2025-04-16 11:46

这个函数的输入是一个列表和一个数字。然后它应该返回这个列表中可以被这个数字整除的元素的索引。如果列表中没有任何数字可以被整除,那么它就应该返回一个空列表。

举个例子,

div([5,10,15,2,34],10)
[0,1,3]

这是我的代码:

def div(nlst, n):
    nlst = []
    for div in nlst:
        if n % nlst == 0:
        return nlst.index(div)
        else: []

我的代码有什么问题吗?

2 个回答

1

列表推导式来帮忙了:

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]
1

你的代码里有几个问题:

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

这段代码可以解决这个问题:

def div(nlst, n):
    result = []
    for i, e in enumerate(nlst):
        if n % e == 0:
            result.append(i)
    return result

还有一个更简洁的版本:

def div(nlst, n):
    return [i for i, e in enumerate(nlst) if n % e == 0]

撰写回答