Update a variable in a for loop? - python

I have a series of data and would like to perform the following opperation:
AA = [2, 4, 6, 8]
a = []
a = AA[0]
b = AA[1]
sum_1 = a+b
c = AA[2]
sum_2 = sum_1 + c
d = AA[3]
sum_3 = sum_2 + d
To make it more concise, I'd like to put it in a for loop, but I can't figure out how.
The desired output for me will be the updated sum_3

That will do it for you:
AA = [2, 4, 6, 8]
s = 0
for a in AA:
s += a
print(s)
20
Cheers

Related

N by N spiral matrix (1 to square(N)) - Unexpected Output

While trying to create a N by N spiral matrix for number 1 to square(N) , using the usual algorithm for spiral matrix , there is an unexpected output in one of the rows which cannot be found even on rechecking.
def getSpiralOrder(N):
matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
c = 1
rS = 0
rE = len(matrix)
cS = 0
cE = len(matrix[0])
while(rS < rE and cS < cE):
for i in range(cS , cE ):
matrix[rS][i]=c
c = c + 1
rS += 1
for i in range(rS , rE):
matrix[i][cE - 1]=c
c = c + 1
cE -= 1
for i in range(cS , cE):
matrix[rE - 1][cE - i - 1]=c
c =c + 1
rE -= 1
for i in range(rS,rE):
matrix[rE - i ][cS]=c
c = c + 1
cS += 1
return(matrix)
n = int(input())
print(getSpiralOrder(n))
Output should be: [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16 , 15, 6], [10, 9, 8, 7]]
But output coming is: [[1, 2, 3, 4], [12, 13, 14, 5], [16, 0, 15, 6], [10, 9, 8, 7]]
Turns out all rows are correct except the third one.
Your last two for loops are wrong:
def getSpiralOrder(N):
matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
c = 1
rS = 0
rE = len(matrix)
cS = 0
cE = len(matrix[0])
while(rS < rE and cS < cE):
for i in range(cS , cE ):
matrix[rS][i]=c
c = c + 1
rS += 1
for i in range(rS , rE):
matrix[i][cE - 1]=c
c = c + 1
cE -= 1
# should go from cE - 1 not cE - cS - 1
for i in range(cE-cS):
matrix[rE - 1][cE - i - 1]=c
c =c + 1
rE -= 1
# similar here
for i in range(rE-rS):
matrix[rE - i -1][cS]=c
c = c + 1
cS += 1
return(matrix)

How to iterate in python using for i in range loop?

I wonder how can I run the code below 4 times in which, in each run the variables in z (which are a and b) takes the new number while c stays the same?
a = [1,2,3,4]
print (a)
b = [4,5,6,7]
print (b)
c = [5]
print (c)
for i in range(4):
z = (a**2)*b+c
print (z)
The output I am looking for is:
9 ---> z = (1**4)*4+5
25---> z = (2**5)*4+5
59---> z = (3**6)*4+5
117---> z = (4**7)*4+5
for i, j in zip(a, b):
z = (i**2)*j+c[0]
print (z)
I'm not sure how you get the results on the left side from the calculations on the right. Based on your descriptions, I think what you meant is:
a = [1, 2, 3, 4]
print(a)
b = [4, 5, 6, 7]
print(b)
c = [5]
print(c)
for i in range(4):
z = (a[i] ** b[i]) * 4 + c[0]
print(z)
which gives:
9 ---> z = (1**4)*4+5
133 ---> z = (2**5)*4+5
2921 ---> z = (3**6)*4+5
65541 ---> z = (4**7)*4+5

Select next N rows in pandas dataframe using iterrows

I need to select each time N rows in a pandas Dataframe using iterrows.
Something like this:
def func():
selected = []
for i in range(N):
selected.append(next(dataframe.iterrows()))
yield selected
But doing this selected has N equal elements. And each time I call func I have always the same result (the first element of the dataframe).
If the dataframe is:
A B C
0 5 8 2
1 1 2 3
2 4 5 6
3 7 8 9
4 0 1 2
5 3 4 5
6 7 8 6
7 1 2 3
What I want to obtain is:
N = 3
selected = [ [5,8,2], [1,2,3], [4,5,6] ]
then, calling again the function,
selected = [ [7,8,9], [0,1,2], [3,4,5] ]
then,
selected = [ [7,8,6], [1,2,3], [5,8,2] ]
No need for .iterrows(), rather use slicing:
def flow_from_df(dataframe: pd.DataFrame, chunk_size: int = 10):
for start_row in range(0, dataframe.shape[0], chunk_size):
end_row = min(start_row + chunk_size, dataframe.shape[0])
yield dataframe.iloc[start_row:end_row, :]
To use it:
get_chunk = flow_from_df(dataframe)
chunk1 = next(get_chunk)
chunk2 = next(get_chunk)
Or not using a generator:
def get_chunk(dataframe: pd.DataFrame, chunk_size: int, start_row: int = 0) -> pd.DataFrame:
end_row = min(start_row + chunk_size, dataframe.shape[0])
return dataframe.iloc[start_row:end_row, :]
I am assuming you are calling the function in a loop. You can try this.
def select_in_df(start, end):
selected = data_frame[start:end]
selected = select.values.tolist()
return selected
print(select_in_df(0, 4)) #to update the start and end values, you can use any loop or whatever is your convenience
#here is an example
start = 0
end = 3
for i in range(10): #instead of range you can use data_frame.iterrows()
select_in_df(start, end+1) #0:4 which gives you 3 rows
start = end+1
end = i
return should be used instead of yield. if you want plain data in selected as list of list you can do this:
def func():
selected = []
for index, row in df.iterrows():
if(index<N):
rowData =[]
rowData.append(row['A'])
rowData.append(row['B'])
rowData.append(row['C'])
selected.append(rowData)
else:
break
return selected
I think I found an answer, doing this
def func(rowws = df.iterrows(), N=3):
selected = []
for i in range(N):
selected.append(next(rowws))
yield selected
selected = next(func())
Try using:
def func(dataframe, N=3):
return np.array_split(dataframe.values, N)
print(func(dataframe))
Output:
[array([[5, 8, 2],
[1, 2, 3],
[4, 5, 6]]), array([[7, 8, 9],
[0, 1, 2],
[3, 4, 5]]), array([[7, 8, 6],
[1, 2, 3]])]

Python : What is the purpose of a colon in an if statement?

I have this piece of python code below.
def m(list):
v = list[0]
for e in list:
if v < e: v = e
return v
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for row in values:
print(m(row), end = " ")
The result is 5, 33.
Can somebody explain me that following if statement if v < e: v = e?
if v < e: v = e
can be read: "If v is less than e, make v the value of e."
As above you should put a new line to make it read easier:
if v < e:
v = e
In [8]: v = 1
In [9]: e = 2
In [10]: if v < e: v = e
In [11]: v
Out[11]: 2
In [12]: e
Out[12]: 2
is same as:
In [13]: v = 1
In [14]: e = 2
In [15]: if v < e: # if True execute next statement
....: v = e
....:
In [16]: v
Out[16]: 2
In [17]: e
Out[17]: 2
It's called a colon in english, not a double colon or double comma.
I urge you to read a basic Python introduction.
if v < e: v = e
Is the same as:
if v < e:
v = e
Another way to write that code is like this, just for learning purposes:
def max_nest_list(lst):
max_numbers = []
for sub_list in lst:
max_num = sub_list[0]
for num in sub_list[1:]:
if num > max_num:
max_num = num
max_numbers.append(max_num)
return max_numbers
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for item in max_nest_list(values):
print(item, end = " ")
#Output
5 33
Or even more concise:
def max_nest_list2(lst):
return [max(i) for i in lst]
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for item in max_nest_list(values):
print(item, end = " ")

How to call a function to process list

i have created a function to find the column sums of a hard coded 2d lists so im trying to have it print out only the values of the hard coded column sums. I basically added column indexes and added their sums to an emptylist. then i returned that empty list. when i try to print the values of the empty list i get an error, any help?
#Function that returns column sums for list1
def columnsumsfunction(a) :
rowsize = len(list1)
columnsize = len(list1[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = list1[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
for a in list1 :
csum = columnsumsfunction(a)
print csum
#main
list1 = [[1, 2, 3],
[4, 5, 6] ]
Im just not really sure on how to call on the function to process list1. li
im just trying to call on the function to print
5 7 9
The code in your question is a little out of order, but if you fix that and change all the instances of list to a within the function you'll be set:
#Function that returns column sums for list1
def columnsumsfunction(a) :
rowsize = len(a)
columnsize = len(a[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = a[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
list1 = [[1, 2, 3],
[4, 5, 6] ]
csum = columnsumsfunction(list1)
print csum
def columnsumsfunction():
index = 0
rowsize = len(list1)
columnsize = len(list1[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = list1[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
#main
list1 = [[1, 2, 3],
[4, 5, 6] ]
csum = columnsumsfunction()
print csum
If you are trying to print 5 7 9 this code works fine.
You don't need list2 at all. Call the columnsfunction() after list1 has been defined.
The for loop is also not required.

Categories

Resources