开发者

How can I solve this without list comprehensions

I´m new in python and I´m trying to find the best way to approach this problem , I need to understand if this can be made only with loops and functions (whithout lists comprehensions). I also need to find the more elegant way to solve this kind or problems, simple functions? recursivity? lists comprehensions? Generator functions? At the end of this text is my attempt. Thank you.

I have this lists:

base=[1,2]

alist=[1,2,3]

blist=[3,2,1]

and i need to find this for each "time step" :

result(j)=base(j-1)+alist(j)-blist(j)

this is result I need to find:

[1+1-3 2+1-3]

[1+1-3+2-2 2+1-3+2-2] 

[1+1-3+2-2+3-1 2+1-3+2-2+3-1]

This is my attempt: It doesn´t work because at each iteration I have to consider the previous va开发者_Go百科lue of base. I have tried...

def calc(base,alist,blist):
    lineNum=0
    while lineNum < 3:
        result=[]
        for i in range(len(base)):
           result.append(base[i]+alist[lineNum]-blist[lineNum]) 
        print To
        lineNum+=1


Try the following:

def calc(base, alist, blist):
    for num in range(1, 4):
        result = []
        for b in base:
            result.append(b + sum(alist[:num]) - sum(blist[:num]))
        print result

Here is the result with the data you gave:

>>> calc(base, alist, blist)
[-1, 0]
[-1, 0]
[1, 2]

Alternatively, you can do this without the sum() call by keeping the previous result and just adding/subtracting the next value from alist and blist, which may be more efficient:

def calc(base, alist, blist):
    result = base[:]
    for num in range(3):
        for i, v in enumerate(result):
            result[i] = v + alist[num] - blist[num]
        print result


You simply want to add the next element of alist and blist in each iteration, so store the previous value and add this element to it.

base=[1,2]
alist=[1,2,3]
blist=[3,2,1]

""" [1+1-3 2+1-3]

[1+1-3+2-2 2+1-3+2-2]

[1+1-3+2-2+3-1 2+1-3+2-2+3-1] """

this_step = "" for ctr in range(len(alist)): this_step += "+%d -%d " % (alist[ctr], blist[ctr]) for num in base: print "%d %s " % (num, this_step), print "\n"


You can also use numpy:

import numpy as np

def calc(bas, a, b):
    r = bas.copy()
    for i in range(a.size):
        r += a.item(i)
        r -= b.item(i)
        yield r

base = np.array([1,2])
alist = np.array([1,2,3])
blist = np.array([3,2,1])

for result in calc(base, alist, blist):
    print result

Output:

[-1  0]
[-1  0]
[1 2]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜