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 value 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:
Here is the result with the data you gave:
Alternatively, you can do this without the
sum()call by keeping the previous result and just adding/subtracting the next value fromalistandblist, which may be more efficient: