For and If Loop together  keeping count
How do I keep a count while executing a IF statement within a for loop? I want to execute different code based on the counter. Here is a simplified version of what I'm trying to do:
li = [1,2,3,4,5]
for l in li:
counter = 1
if counter == 1:
counter +=1
print(l)
else:
print('this worked')
Results:
1
2
3
4
5
1 answer

If you want the number of times the
if
condition was hit. Declare thecounter
variable before thefor
loop
See also questions close to this topic

first element to become the key each row
I have a csv file that contains 2 columns. Here is an glimpse of how he looks:
A:john, robert, simon,peter B: robert, isiah, elephant C: james, bond, jack, chuck
What I want is to be able to make every element of the first row a the key of the dictionary and make the rest of the row the value. basically I want it to look this:
A B C john robert james robert isiah bond peter elephant jack chuck

How to make all fields readonly in form view odoo?
I was trying to make all fields in a form view readonly in odoov10. Is there any python method through I can get all the form view fields and change its attribute to readonly="True"?

Calculate new column as the mean of other columns pandas
I have a this data frame:
and I would like to calculate a new columns as de the mean of
salary_1
,salary_2
andsalary_3
.df = pd.DataFrame({'salary_1':[230,345,222],'salary_2':[235,375,292],'salary_3':[210,385,260]}) salary_1 salary_2 salary_3 0 230 235 210 1 345 375 385 2 222 292 260
How can I do it in pandas in the most efficient way? Actually I have many more columns and I don't want to write this one by one.
Something like this:
salary_1 salary_2 salary_3 salary_mean 0 230 235 210 (230+235+210)/3 1 345 375 385 ... 2 222 292 260 ...
Thank you!

How to save statistics value output from Python nested loop for
I have program to compute statistical values from several file datasets. I have created program using nested loop for. The output is nicely printed on screen but can't saved in on file.
import numpy as np from scipy.stats.stats import pearsonr list = ['01', '02','03','04','05','06','07','08','09','10'] month='NOV2016' for date in list: path='D:/MatchNov2016/24matchgroundimsra0.25/' data=np.loadtxt(path+'3DIMG_'+date+month+'_DAILY.dat') lats=data[:,0] lons=data[:,1] ground=data[:,2] model=data[:,5] bias=np.mean(modelground) rms=np.sqrt(np.mean((groundmodel)**2)) std=np.std(groundmodel) corr=pearsonr(ground,model) corr=corr[0] bias=np.round(bias,2) rms=np.round(rms,2) std=np.round(std,2) corr=np.round(corr,2) stat=np.zeros((np.size(bias),4)) stat[:,0]=np.reshape(bias,(np.size(bias))) stat[:,1]=np.reshape(rms,(np.size(rms))) stat[:,2]=np.reshape(std,(np.size(std))) stat[:,3]=np.reshape(corr,(np.size(corr))) print stat np.savetxt('result.dat',stat,fmt='%9.2f') RESULT: The result shown on screen is as follows: [[ 12.27 25.48 22.33 0.26]] [[ 18.39 26.47 19.04 0.3 ]] [[ 22.96 33.12 23.87 0.38]] [[ 14.31 38.9 36.17 0.08]] [[ 19.73 26.75 18.07 0.46]] [[ 3.53 24.77 24.51 0. ]] [[ 9.68 21.91 19.66 0.11]] [[ 4.94 17.96 17.27 0.02]] [[ 3.76 15.88 15.43 0.5 ]] [[ 2.07 18.1 17.98 0.31]] However, the result printed on output file "result.dat" is only the last line. 2.07 18.10 17.98 0.31
I could not figure out whats the problem with that!..

is there any simple way for this case in R, using sapply or another way but not using loop?
i have 3 matrix, first :
> QualiVars Qlvar1 Qlvar2 1 A Q 2 B Q 3 A R 4 C Q
second matrix is :
> cat.centroid [[1]] Values V1 1 A 0.4164760 2 B 0.3112128 3 C 0.2723112 [[2]] Values V1 1 Q 0.7665904 2 R 0.2334096
the third matrix:
> distForAll VarIndex xVal yVal DistBetPair 1 1 A B 0.5000000 2 1 A C 0.5000000 3 1 B C 0.6666667 4 2 Q R 0.6666667
maybe its kinda complicated, i will start from "A" (first data from first Matrix). it will compare to second matrix cat.centroid[[1]] because A from first column and it will compare to the first list of second matrix[[1]]. the condition is take the Values first list from second matrix except "A", so we will get
Values V1 2 B 0.3112128 3 C 0.2723112
then from the matrix above, it will corresponding to the third matrix. remember the first data from first matrix is "A". and from the above matrix i got "B" and "C" so i will take
VarIndex xVal yVal DistBetPair 1 1 A B 0.5000000 2 1 A C 0.5000000
from the third matrix, so the final result will be
Values V1 xVal yVal DistBetPair 2 B 0.3112128 A B 0.5000000 3 C 0.2723112 A C 0.5000000
then calculate 0.3112128*0.5 + 0.2723112*0.5 = 0.29. do this step for all data from first matrix.
0.29 ... ... ... ... ... ... ... ... ... ... ...
im thinking about using sapply, but i have no idea.

Doing the initialization of two variable in a single for loop: JAVA
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { boolean flag = false; int row = matrix.length; int column = matrix[0].length; int j, k, p, i; for(p = 0; p < column  1; ++p) { for(i = 0; i < row  1; ++i) { for(j = i, k = p; j < row, k < column; ++j, ++k) { if((j < row  1)  (k < column  1)) { if(matrix[j][k] != matrix[j + 1][k + 1]) { flag = true; return False; } } } } } if(flag == false) return True; } }
Error: Line 9 (for(j = i, k = p; j < row, k < column; ++j, ++k))error: ';' expected I don't know what am i doing wrong everything seems to be correct and i cann't find where to put the ; Please tell me the correction of this error and actually this is snippet of code from my submission from Leetcode.

AND and OR operator c
Hey i am working on a code and i stuck inside this if condition which is (Not a actual Code simplified for better understanding)
if(18&2==2) do something;
this if condition not executing but if i write like this
if(182==18) do something;
it executed normal
also when I,
printf("%d",18&2);
it gives 2 now i am so confused why the above if statement not executing, is it because of precedence ,please explain thanks.

Excel nested IF  multiple conditions in a single formula
I am trying to assign levels of recommendation based on certain values in cell C.
However, I am not sure why this IFS statement is returning with errors.
=IFS(C2< =2.00, “Do Not Recommend”, C2 <=3.33, “Do Not Recommend/Borderline”, C2 <=3.34, “Recommend”, C2=>3.78, “Strongly Recommend”)
Lastly: If I wanted to assign the cell above TWO possible final recommendations, would it be an IF OR statement. For example... IF a candidate is "Do not Recommend" (Cell C3), they can be rejected or placed on hold. How would I reflect that in the code.

Python else if statement invalid syntex error
I am working on a program to calculate one of three types of averages. The code initially worked until I called the Geometric function. Now I'm getting an invalid syntex error on the else statement.
a = int(input("Please enter an integer:")) b = int(input("Please enter a second integer:")) option = (input('Please choose your desired type of average \n Arithmetic, Geometric, or Rootmeansquare: ')) def means(option): if option == 'Arithmetic': return((a+b)/2) elif option == 'Geometric': return(sqrt(ab)) else option == 'Rootmeansquare': return(sqrt((a+b)/2)) print(means(option))

Python print first 3 items in counter
Below is my counter, how do I only print the first 3
Counter({'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45, 'New York': 297.8, 'Stockton': 248.18, 'Omaha': 236.63, 'San Jose': 215.05, 'San Diego': 67.08, 'Corpus Christi': 26.38})
I have tried doing that however it becomes an error
print(Counter[0,1,2])
I just want to print
{'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45}

Python: re.findall returns chars with .docx, but words with .txt
I'm trying to read a docx file and count the top ten words, in this case Hamlet. I'm leveraging the re and counter packages with the code below.
In the first example I'm reading a .docx version, and in the second a .txt version. Identical content and identical code, but the first returns a counter of chars, and the second a counter of words. What am I missing?
.docx version:
import re from collections import Counter words = re.findall(r'\w+', open('HAMLET.docx').read().lower()) print(Counter(words).most_common(10)) #returns: [('p', 1404), ('o', 1303), ('k', 1214), ('x', 1137), ('u', 1134), ('m', 1128), ('f', 1115), ('i', 1110), ('g', 1076), ('z', 1072)]
.txt version:
import re from collections import Counter words = re.findall(r'\w+', open('HAMLET.txt').read().lower()) print(Counter(words).most_common(10)) #returns: [('the', 1142), ('and', 966), ('to', 762), ('of', 667), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 470), ('in', 451)]
Hamlet file here: http://shakespeare.mit.edu/hamlet/full.html

How to add all numbers in a list using Counter?
I have a list like this:
[1, 1, 78, 7701], [1, 2, 78, 7527], [1, 3, 78, 8825], [1, 4, 78, 8859], [1, 5, 78, 9043], [1, 6, 78, 9208], [1, 7, 78, 8084], [1, 8, 78, 7611], [1, 9, 78, 9172], [1, 10, 78, 9089], [1, 11, 78, 9210], [1, 12, 78, 9259], [1, 13, 78, 9138], [1, 14, 78, 8299], [1, 15, 78, 7771], [1, 16, 78, 9458], [1, 17, 78, 9339], [1, 18, 78, 9120], [1, 19, 78, 9226]
The first column is the month. I want to use
Counter
to add all the numbers in the last column (within the same month).