有没有办法进一步减少此python代码中的“ for循环”?

时间:2019-06-10 06:25:50

标签: python list for-loop time-complexity big-o

我想从现有列表中创建一个新列表,以使新列表中的每个元素都是现有列表中所有数字的乘积,除了位于新列表元素相同位置的元素。

例如[2,4,5]-> [20,10,8]

我想出了一个解决方案,其中一个for循环,j遍历第i个(当前)元素的右侧,而在另一个for循环中,k覆盖元素的左侧-相乘并给出结果。

def mulList():
    oldList = [2,4,5]
    newList = []
    for i in range(len(oldList)):
        a = 1
        for j in range(i+1,len(oldList)):
            a *= oldList[j] 
        for j in range(i-1,-1,-1):
            a *= oldList[j] 
        newList.append(a)
    print(newList)
mulList()

后来我知道我们可以用两个for循环来解决它,如果我等于j,我什么也不做

def mulList():
    oldList = [2,4,5]
    newList = []
    for i in range(len(oldList)):
        a = 1
        for j in range(len(oldList)):
            if j == i:
                a += 0
            else:
                a *= oldList[j] 
        newList.append(a)
    print(newList)
mulList()

我想知道是否有更好的方法来解决一个仅for循环。

4 个答案:

答案 0 :(得分:4)

您可以将所有内容相乘一次,然后再次遍历元素并将总乘积除以当前元素:

def mulList():
    oldList = [2,4,5]
    newList = []
    total = 1
    for x in oldList:
        total *= x  # total = total * x
    for x in oldList:
        # Use // to get int (4) instead of float (4.0)
        newList.append(total // x)
    print(newList)

答案 1 :(得分:2)

您可以通过functools.reduce获取列表中所有元素的乘积,然后使用整数除法//将列表中的每个元素与乘积相除

from functools import reduce
from operator import mul

li = [2,4,5]
#Take product of all elements via reduce operation on the list 
mult = reduce(mul, li)
#40

#Divide the product found in the step above by each item via integer division
res = [mult//item for item in li]

print(res)

如果不想使用functools.reduce

,也可以在for循环中将元素相乘。
#Or loop over the element to multiply
mult = 1
for item in li:
    mult *= item

输出将为

[20, 10, 8]

答案 2 :(得分:1)

我在我认为的leetcode中看到了这个问题,并且存在不使用除法的约束,并且仍然在O(n)中使用此算法。基本上,我一次正向遍历两次数组,一次反向遍历遍历数组,并且在第三次迭代中乘以对应的元素以获得您看到的输出。

oldlist = [2,4,5]
forwardlist=[1]*len(oldlist)
backwardlist=[1]*len(oldlist)
mul = oldlist[0]
for i in range(1,len(oldlist)):
    forwardlist[i] = mul
    mul*= oldlist[i]
mul = oldlist[len(oldlist) - 1]
for i in range(len(oldlist) - 2, -1, -1):
    backwardlist[i] = mul
    mul*= oldlist[i]
newlist = []
for i in range(len(oldlist)):
    newlist.append(forwardlist[i]*backwardlist[i])
print(newlist)

输出

[20, 10, 8]

希望是有帮助的。 :)

答案 3 :(得分:0)

这个呢

c = 1
for i in oldList:
    c *= i
newList = [c//e for e in oldList]

现在您的功能将会

def mulList():
    oldList = [2,4,5]
    c = 1
    for i in oldList:
        c *= i
    newList = [c//e for e in oldList]
    print(newList)