I have a question, I want to make a counter for myself but I have a problem with the code.
# Counter Next button
self.index = 2 # clicked picture (index number in the list)
self.counterUp += 1 # counter
# index images to display: link_to_photo[self.counterSum], e.g. for 0 is self.counterUp =
# self.counterSum but for a value other than 0 then the values are different
self.counterSum = self.counterUp + self.index
if self.counterUp < 5:
print('click, index of photo: ', self.index, 'counter: ', self.counterUp, 'sum: ', self.counterSum)
else:
self.counterUp = 0
self.index = 0
print('click, index of photo: ', self.index, 'counter: ', self.counterUp, 'sum: ', self.counterSum)
results:
for example index = 2 and I have got 5 photos in the dir:
click, index of photo: 2 counter: 1 sum: 2 # 1
click, index of photo: 2 counter: 2 sum: 3 # 2
click, index of photo: 2 counter: 3 sum: 4 # 3
click, index of photo: 2 counter: 4 sum: 5 # 4
click, index of photo: 0 counter: 0 sum: 6 # 5
click, index of photo: 2 counter: 1 sum: 2 # 6
click, index of photo: 2 counter: 2 sum: 3 # 7
click, index of photo: 2 counter: 3 sum: 4 # 8
click, index of photo: 2 counter: 4 sum: 5 # 9
index detection works well "click, index of photo"
I add a counter to the index for each click on "next", "counter". I have 5 pictures so from 0 to 4, ok.
the problem I have with the "sum".
line 5 index = 0 counter = 0 gives 6? should be 0 and give from 1 to 4 .
Can ask for help to solve this problem. Thank you very much :D
The 'print' code is just a test to see what happens
You don't recalculate counterSum, it has still the old value.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I did an Algorithm to print a triangle in the upper half of the matrix (without recursive function) but now i want to do it recursively can anyone Help?
Thanks
CLICK HERE TO SEE AN EXAMPLE
My python code:
def T(row,column):
print("Row: ",row)
print("Column", column)
if row != column and row%2 == 0:
print("Please enter valid number")
else:
matrix = []
start = 1
cteRow = row
cteColumn = column
for i in range(0,column):
matrix.append(list(range(start,row + 1)))
start = start + cteRow
row = row + cteColumn
print("The Matrix: \n")
for i in range(len(matrix)):
for j in range(len(matrix)):
print(matrix[i][j], end= " ")
print()
print()
length = len(matrix)
middle = int(length/2)
for i in range(length):
for j in range(length):
matrix[i][j] = 0
if (middle + i)<= length and (middle - i)>= 0:
matrix[i][middle] = 1
myRangeList=list(range(middle-i,middle+i+1))
for n in myRangeList:
matrix[i][n] = 1
print(matrix[i][j], end = " ")
print()
T(5,5)
To make it recursive, you have to come up with a method to convert the result of a smaller matrix into a larger one.
for example:
From T(3,5) --> T(4,7)
0 0 1 0 0 0 0 0 1 0 0 0
0 1 1 1 0 0 0 1 1 1 0 0
1 1 1 1 1 0 1 1 1 1 1 0
1 1 1 1 1 1 1
The transformation could be adding zeros on each side and a line of 1s at the bottom:
0 0 1 0 0 0 x x x x x 0 0 0 0 1 0 0 0
0 1 1 1 0 0 x x x x x 0 0 0 1 1 1 0 0
1 1 1 1 1 0 x x x x x 0 0 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1
This will be easy if the parameters provided fit the triangle size exactly: rows = (columns+1)/2. You can handle the disproportionate dimensions by padding the result from an appropriate size ratio with zeros so that the function only needs to handle proper proportions:
def R(rows,cols):
if not cols%2: # must have odd number of columns (pad trailing zero)
return [ row+[0] for row in R(rows,cols-1)]
height = (cols+1)//2
if rows>height: # too high, pad with lines of zeros
return R(height,cols)+[[0]*cols for _ in range(rows-height)]
if rows<height: # not high enough
return R(height,cols)[:rows] # truncate bottom
if cols == 1: # base case (1,1)
return [[1]]
result = R(rows-1,cols-2) # Smaller solution
result = [[0]+row+[0] for row in result] # pad with zeros
result += [[1]*cols] # add line of 1s
return result
The function only generates the matrix. User input and printing should always be separate from data manipulation (especially for recursion)
output:
for row in R(5,5): print(*row)
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 0 0 0 0
0 0 0 0 0
Note that this will work for any combination of row & column sizes but, if you always provide the function with a square matrix, only the "upper half" will contain the triangle because triangle height = (columns+1)/2. It would also be unnecessary to ask the user for both a number of rows and a number of columns if the two are required to be equal.
For only square matrices with an odd number of columns, the process can be separated in a recursive part and a padding function that uses it:
def R(cols):
if cols == 1: return [[1]] # base case (1,1)
result = R(cols-2) # Smaller solution
result = [[0]+row+[0] for row in result] # pad with zeros
result += [[1]*cols] # add line of 1s
return result
def T(n):
return R(n)+[[0]*n]*((n-1)//2) # square matrix with padding
for row in T(7): print(*row)
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
I have a daraframe as below:
Datetime Data Fn
0 18747.385417 11275.0 0
1 18747.388889 8872.0 1
2 18747.392361 7050.0 0
3 18747.395833 8240.0 1
4 18747.399306 5158.0 1
5 18747.402778 3926.0 0
6 18747.406250 4043.0 0
7 18747.409722 2752.0 1
8 18747.420139 3502.0 1
9 18747.423611 4026.0 1
I want to calculate the sum of continious non zero values of Column (Fn)
I want my result dataframe as below:
Datetime Data Fn Sum
0 18747.385417 11275.0 0 0
1 18747.388889 8872.0 1 1
2 18747.392361 7050.0 0 0
3 18747.395833 8240.0 1 1
4 18747.399306 5158.0 1 2 <<<
5 18747.402778 3926.0 0 0
6 18747.406250 4043.0 0 0
7 18747.409722 2752.0 1 1
8 18747.420139 3502.0 1 2
9 18747.423611 4026.0 1 3
You can use groupby() and cumsum():
groups = df.Fn.eq(0).cumsum()
df['Sum'] = df.Fn.ne(0).groupby(groups).cumsum()
Details
First use df.Fn.eq(0).cumsum() to create pseudo-groups of consecutive non-zeros. Each zero will get a new id while consecutive non-zeros will keep the same id:
groups = df.Fn.eq(0).cumsum()
# groups Fn (Fn added just for comparison)
# 0 1 0
# 1 1 1
# 2 2 0
# 3 2 1
# 4 2 1
# 5 3 0
# 6 4 0
# 7 4 1
# 8 4 1
# 9 4 1
Then group df.Fn.ne(0) on these pseudo-groups and cumsum() to generate the within-group sequences:
df['Sum'] = df.Fn.ne(0).groupby(groups).cumsum()
# Datetime Data Fn Sum
# 0 18747.385417 11275.0 0 0
# 1 18747.388889 8872.0 1 1
# 2 18747.392361 7050.0 0 0
# 3 18747.395833 8240.0 1 1
# 4 18747.399306 5158.0 1 2
# 5 18747.402778 3926.0 0 0
# 6 18747.406250 4043.0 0 0
# 7 18747.409722 2752.0 1 1
# 8 18747.420139 3502.0 1 2
# 9 18747.423611 4026.0 1 3
How about using cumsum and reset when value is 0
df['Fn2'] = df['Fn'].replace({0: False, 1: True})
df['Fn2'] = df['Fn2'].cumsum() - df['Fn2'].cumsum().where(df['Fn2'] == False).ffill().astype(int)
df
You can store the fn column in a list and then create a new list and iterate over the stored fn column and check the previous index value if it is greater than zero then add it to current index else do not update it and after this u can make a dataframe for the list and concat column wise to existing dataframe
fn=df[Fn]
sum_list[0]=fn first value
for i in range(1,lenghtofthe column):
if fn[i-1]>0:
sum_list.append(fn[i-1]+fn[i])
else:
sum_list.append(fn[i])
dfsum=pd.Dataframe(sum_list)
df=pd.concat([df,dfsum],axis=1)
Hope this will help you.there may me syntax errors that you can refer google.But the idea is this
try this:
sum_arr = [0]
for val in df['Fn']:
if val > 0:
sum_arr.append(sum_arr[-1] + 1)
else:
sum_arr.append(0)
df['sum'] = sum_arr[1:]
df
I want to find the count for the number of previous rows that have the a greater value than the current row in a column and store it in a new column. It would be like a rolling countif that goes back to the beginning of the column. The desired example output below shows the value column given and the count column I want to create.
Desired Output:
Value Count
5 0
7 0
4 2
12 0
3 4
4 3
1 6
I plan on using this code with a large dataframe so the fastest way possible is appreciated.
We can do subtract.outer from numpy , then get lower tri and find the value is less than 0, and sum the value per row
a = np.sum(np.tril(np.subtract.outer(df.Value.values,df.Value.values), k=0)<0, axis=1)
# results in array([0, 0, 2, 0, 4, 3, 6])
df['Count'] = a
IMPORTANT: this only works with pandas < 1.0.0 and the error seems to be a pandas bug. An issue is already created at https://github.com/pandas-dev/pandas/issues/35203
We can do this with expanding and applying a function which checks for values that are higher than the last element in the expanding array.
import pandas as pd
import numpy as np
# setup
df = pd.DataFrame([5,7,4,12,3,4,1], columns=['Value'])
# calculate countif
df['Count'] = df.Value.expanding(1).apply(lambda x: np.sum(np.where(x > x[-1], 1, 0))).astype('int')
Input
Value
0 5
1 7
2 4
3 12
4 3
5 4
6 1
Output
Value Count
0 5 0
1 7 0
2 4 2
3 12 0
4 3 4
5 4 3
6 1 6
count = []
for i in range(len(values)):
count = 0
for j in values[:i]:
if values[i] < j:
count += 1
count.append(count)
The below generator will do what you need. You may be able to further optimize this if needed.
def generator (data) :
i=0
count_dict ={}
while i<len(data) :
m=max(data)
v=data[i]
count_dict[v] =count_dict[v] +1 if v in count_dict else 1
t=sum([(count_dict[j] if j in count_dict else 0) for j in range(v+1,m)])
i +=1
yield t
d=[1, 5,7,3,5,8]
foo=generator (d)
result =[b for b in foo]
print(result)
I want to know how can I make the source code of the following problem based on Python.
I have a dataframe that contain this column:
Column X
1
0
0
0
1
1
0
0
1
I want to create a list b counting the sum of successive 0 value for getting something like that :
List X
1
3
3
3
1
1
2
2
1
If I understand your question correctly, you want to replace all the zeros with the number of consecutive zeros in the current streak, but leave non-zero numbers untouched. So
1 0 0 0 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0
becomes
1 4 4 4 4 1 1 1 1 2 2 1 1 1 5 5 5 5 5
To do that, this should work, assuming your input column (a pandas Series) is called x.
result = []
i = 0
while i < len(x):
if x[i] != 0:
result.append(x[i])
i += 1
else:
# See how many times zero occurs in a row
j = i
n_zeros = 0
while j < len(x) and x[j] == 0:
n_zeros += 1
j += 1
result.extend([n_zeros] * n_zeros)
i += n_zeros
result
Adding screenshot below to make usage clearer
This question already has answers here:
Making a shift function in 2048
(3 answers)
Closed 4 years ago.
So I have some code to shift up a board of numbers in a 2048 game:
data = [0, 2, 4, 8, 0, 2, 8, 0, 0, 0, 0, 2, 4, 2, 2, 0]
def drawBoard(): # Making the board into a 2d array
count = 0
for i in range(16):
print(data[i], end = ' ')
count += 1
if count == 4:
print("")
count = 0
print(drawBoard())
for col in range(4): #Loop to shift numbers up
count = 0
for row in range(4): # read loop
if data[row*4+col] != 0:
data[count*4+col] = data[row*4+col]
count += 1
for row in range(count, 4):
data[row*4+col] = 0
print(drawBoard())
This basically takes data, makes it into a 4 x 4 board and shifts all the non zero numbers up.
Non Shifted Board:
2 2 4 8
0 2 8 0
0 0 0 2
4 2 2 0
Shifted Board:
2 2 4 8
4 2 8 2
0 2 2 0
0 0 0 0
Is there a way using the same format as what I commented "loop to shift numbers up" and make this shift up function into a shift left function?
So the board shifted left looks like:
2 2 4 8
2 8 0 0
2 0 0 0
4 2 2 0
I suggest you to rotate the row/col reference, and the code will be the same. Immagine that you turn the grid counter clockwise so your first column is the last row and your first row is the first column