++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)
++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer += operator to do what you want to do:
count += 1
I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
- Simpler parsing. Technically, parsing
++countis ambiguous, as it could be+,+,count(two unary+operators) just as easily as it could be++,count(one unary++operator). It's not a significant syntactic ambiguity, but it does exist. - Simpler language.
++is nothing more than a synonym for+= 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimizea += 1into theincinstruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable. - Confusing side-effects. One common newbie error in languages with
++operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)
++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer += operator to do what you want to do:
count += 1
I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
- Simpler parsing. Technically, parsing
++countis ambiguous, as it could be+,+,count(two unary+operators) just as easily as it could be++,count(one unary++operator). It's not a significant syntactic ambiguity, but it does exist. - Simpler language.
++is nothing more than a synonym for+= 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimizea += 1into theincinstruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable. - Confusing side-effects. One common newbie error in languages with
++operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
Python does not have pre and post increment operators.
In Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:
>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True
a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:
b = b + 1
Many C programmers who used python wanted an increment operator, but that operator would look like it incremented the object, while it actually reassigns it. Therefore the -= and += operators where added, to be shorter than the b = b + 1, while being clearer and more flexible than b++, so most people will increment with:
b += 1
Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.
In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.
Its because you've re-defined the count variable or reset it to 1 for each loop again. I'm not into python but your code doesn't make sense since everytime the count variable is first set to 1 and then incremented. I'd simply suggest the following.
import os
cur = dir(os)
count = 1
for i in cur:
count += 1
print(count,i)
The pythonic way to do this is enumerate. If we pass the keyword argument start=1, the count will begin at 1 instead of the default 0.
import os
cur = dir(os)
for i, f in enumerate(cur, start=1):
print("%d: %s" % (i, f))
Videos
Python doesn't support ++, but you can do:
number += 1
Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.
Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().
Floating point numbers are not precise. The more you handle them, the more error they can accumulate. To have numbers you want, the best way is to keep things integral for as long as possible:
def number():
b = 1
while True:
yield b / 10.0
b += 1
You can pass the number as an argument:
def number(start=0.1,num=0.1):
b = start
while True:
yield round(b,1)
b += num
b = number(0,0.2)
It yields:
0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
If I understand correctly, you could just create a helper dataframe of the rows you want duplicated, then increment the Week number on that helper dataframe, then concatenate to your original:
helper = pd.concat([df.loc[df.Course == 'Prison']]*2)
helper['Week'] += helper.reset_index().index+1
df = pd.concat((df,helper)).sort_values('ID')
>>> df
ID Name Week Course Hours
0 1 John A 1922 Bike Tech 5.5
1 2 John B 1922 Auto Tech 3.2
2 3 John C 1922 Prison 3.5
2 3 John C 1923 Prison 3.5
2 3 John C 1924 Prison 3.5
3 4 John D 1922 Comp 6.5
4 5 John E 1922 Awareness 7.0
5 6 John F 1922 First Aid 7.2
6 7 John G 1922 BasketBall 2.5
7 8 John H 1922 Tech 5.4
Can pass a row, which is a pd.Series with values compatible with your df. For example, take
>>> row = df.loc[df.Course.eq('Prison'), :].iloc[0,:].copy()
ID 3
Name John C
Week 1922
Course Prison
Hours 3.5
Name: 2, dtype: object
Then
def duplicate(n, row, df):
week = row['Week']
for i in range(1, n+1):
row['Week'] = week + i
df.loc[-i, :] = row
return df.sort_values('ID').reset_index(drop=True)
>>> duplicate(3, row, df )
ID Name Week Course Hours
0 1.0 John A 1922.0 Bike Tech 5.5
1 2.0 John B 1922.0 Auto Tech 3.2
2 3.0 John C 1922.0 Prison 3.5
3 3.0 John C 1923.0 Prison 3.5
4 3.0 John C 1924.0 Prison 3.5
5 3.0 John C 1925.0 Prison 3.5
6 4.0 John D 1922.0 Comp 6.5
7 5.0 John E 1922.0 Awareness 7.0
8 6.0 John F 1922.0 First Aid 7.2
9 7.0 John G 1922.0 BasketBall 2.5
10 8.0 John H 1922.0 Tech 5.4
Untested, but some variation of this will work ;-)
n = len(card_task_e)
for i in range(1, n, 2):
base = card_task_e[i]
for j in range(i+1, n, 2):
if base > card_task_e[j]:
counte += 1
ol_task_e.append(base)
You're going to want nested loops for this.
for a in range(1,12,2):
for b in range(a+1,13,2):
if card_task_e[a] > card_task_e[b]:
ol_task_e.append(card_task_e[a])
counte += 1
for the code,
for i in range(0,10):
if i == 3:
i = i + 1
continue
print(i)
the output is going to be,
0
1
2
4
5
6
7
8
9
Breaking down the code,
for i in range(0, 10)
for loop runs for i=0 to i=9, each time initializing i with the value 0 to 9.
if i == 3:
i = i + 1
continue
print(i)
when i = 3, above condition executes, does the operation i=i+1 and then continue, which looks to be confusing you, so what continue does is it will jump the execution to start the next iteration without executing the code after it in the loop, i.e. print(i) would not be executed.
This means that for every iteration of i the loop will print i, but when i = 3 the if condition executes and continue is executed, leading to start the loop for next iteration i.e. i=4, hence the 3 is not printed.
In the provided code when you try to use i in a for loop with range, it always changes to the number provided by range in the function without bothering to look at the increment made to i. so basically if you try list(range(0, 10)) this will give you [0, 2, 3, 4, 5, 6, 7, 8, 9]. so for goes through that list one by one without thinking if any changes were made to i or not.
which if seen
loop_1: i=0
loop_2: i=1
loop_3: i=2
loop_4: i=3 (here now you increment value by 1), i=4
loop_5: i=4 (but the for loop was going though the list from range function so the change didn't do anything)
loop_6: i=5 (and so on until 9)
Use emumerate instead .
for counter,line in enumerate(train_instances):
a,b = line.split(":")
Don't increment anything in the loop or reset counter at all
You need to move the initial declaration of the counter outside the for loop. Since it's inside, each time you loop through, the counter is getting reset to 54 each time.
You need to define the negative variable before stepping into the loop:
negative = 0
for line in neg_file:
# no changes
The way you are proceeding, it is "created" every single loop.
I was re-setting positive and negative back to zero pre-maturely. They should be reset after the for word in words: loop.
A list comprehension will do the trick:
>>> t = [(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
>>> print([tuple((a, b+1) for a, b in group) for group in t])
[[('d', 1), ('g', 1)], [('d', 1), ('d', 2)], [('i', 1), ('g', 1)]]
You can't change the values in tuples, tuples are immutable. You would need to make them be lists or create a new tuple with the value you you want and store that.
Here is a possible solution (s is your string):
for j in range(len(s) - 1):
print(s[j:j + 2])
Another one:
for c1, c2 in zip(s[:-1], s[1:]):
print(c1 + c2)
By using list comprehension you can do this in a one-liner
s = 'teststring'
r = ' '.join([s[i:i+2] for i in range(len(s)-1)])
print(r)
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.
str1 = "ababa"
str2 = "aba"
i = 0
while i < len(str1):
j = 0
while j < len(str2):
if not str1[i+j] == str1[j]:
break
if j == (len(str2) -1):
i += len(str2)
j+=1
i+=1
Maybe loop it a bit different like this?
for item in pritunlServResponse:
srv_id = item['id']
name = item['name']
This way you wouldn't have to create these in the first place
Name = [y['name'] for y in pritunlServResponse]
Server_id = [x['id'] for x in pritunlServResponse]
Use:
for srv_name, srv_id in zip(Name, Server_id):
...
Better yet, replace:
pritunlServResponse = json.loads(response1.data)
Name = [y['name'] for y in pritunlServResponse]
Server_id = [x['id'] for x in pritunlServResponse]
for srv_name in Name:
for srv_id in Server_id:
...
with:
for srv_name, srv_id in [(resp['name'], resp['id']) for resp in json.loads(response1.data)]:
...
for i in [float(j) / 100 for j in range(0, 100, 1)]:
print i
Avoid compounding floating point errors with this approach. The number of steps is as expected, while the value is calculated for each step.
def drange2(start, stop, step):
numelements = int((stop-start)/float(step))
for i in range(numelements+1):
yield start + i*step
Usage:
for i in drange2(0, 1, 0.01):
print i
i is reassigned at every iteration; that's how the for loop works. If you want to skip every second number (i.e. iterate in steps of 2), you'll need to do this:
for i in range(0, 10, 2):
print(i, end="")
That third parameter of the range function, called step, just determines what i is incremented by in each iteration.
Just use step argument in range function :
>>> for i in range(0,10,2):
... print(i, end="")
...
>>> 02468
Note that after each iteration the for loop change the value of i so you shouldn't change it after print!
If you do it before printing you'll get the following result :
>>> for i in range(0,10,2):
... i += 2
... print(i, end="")
...
>>> 246810
You could convert the string to an int and use something like
self.seq = '%010d' % (int(self.seq) + 1)
return self.seq
If you didn't need self.seq to be a string you could do
def __init__(self) :
self.seq = 0
def getNextSeqNo(self) :
self.seq += 1
return '%010d' % self.seq
Quickest and easiest, although certainly not clearest:
str(int('9' + self.seq) + 1)[1:]
It works by adding a leading digit before converting to integer, to retain all the leading zeros, then stripping off that leading digit after converting back to string. It has the advantage of not requiring you to know in advance how many digits are required.