what is the precedence of a ternary operator in this example? - python

>>> count = 0
>>> for c in "##.#.":
... count = count + 1 if c == '.' else 0
...
>>> print(count)
1
>>> count = 0
>>> for c in "##.#.":
... count = count + (1 if c == '.' else 0)
...
>>> print(count)
2
Why doesn't the first example print out a counter of 2?

Conditional expressions have a very low precedence.
So the first expression is actually parsed as:
count = (count + 1) if c == '.' else 0
That will set count to 0 every time c != '.'.

In the first case, count value gets replaced
>>> for c in "##.#.":
... count = count + 1 if c == '.' else 0
... print (count)
...
0
0
1
0
1
Here count gets append
>>> count=0
>>> for c in "##.#.":
... count = count + (1 if c == '.' else 0)
... print (count)
...
0
0
1
1
2
>>>

Because this corresponds to the True state of if.
(True) if (Condition) else (Else)
count = count + 1 if c == '.' else 0 True status for this (count + 1)
count + (1 if c == '.' else 0) True status for this (1)
Did I tell you a little bit complicated?

Related

Python arithmetic function with recurssion

This might be done with a rolling function in pandas probably, not sure but I would like to apply the following function for a list, the current state S in position x is defined as
S[x] = if S[x-1] > 0 S[x-1] -1 + S[x] else S[x] -1 for x > 1
It can be understood as the current state -1 and the current state... This is because I need to do a kind of cumulative sum of all the previous positions -1 + the current positon.
An example for the list
[1,1,2,0,0,2]
returns this values
[0,0,1,0,-1,1]
because:
S[0] = 1 - 1 = 0
S[1] = S[1] - 1 + S[0] = 1 - 1 + 0 = 0
S[2] = S[2] - 1 + S[1] = 2 - 1 + 0 = 1
S[3] = S[3] - 1 + S[2] = 0 - 1 + 1 = 0
S[4] = S[4] - 1 + S[3] = 0 - 1 + 0 = -1
S[5] = S[5] - 1 (no S[4] because the else rule being smaller than 0) = 2 - 1 = 1
I am pretty sure this can probably be done in pandas but I am also open to a standard python function I send a list to (prefer pandas though).
Have been trying recursion and failed miserably.
subtract 1 then use cumsum
(s-1).cumsum()
0 0
1 0
2 1
3 0
4 -1
5 0
here you go, revised solution to accommodate of condition in calculating cumulative sum
np.where(((s.shift(1) - 1).cumsum()) > 0,
(s-1).cumsum(),
s-1)
[ 0, 0, 1, 0, -1, 1]

printing maximum number of consecutive 1's in python

Im trying to print the maximum number of consecutive 1's in python...but im getting stuck here....IDK why im getting a syntax error...strange...can anyone help me out
li2 = []
t = int(input())
for i in range(0, t): //testcases
n = int(input())
for i in range(n): //length of list(binary array)
li = list(map(int, input().strip().split())
count = 0
max_count=0
for i in range(len(li)):
if (li[i] == 0):
count = 0
else:
count += 1
max_count = max(max_count,count)
li2.append(max_count)
for i in range(len(li2)):
print(li2[i])
File "<ipython-input-2-f159cb61e247>", line 7
count = 0
^
SyntaxError: invalid syntax
Corrections:
li2 = []
t = int(input())
for i in range(0, t): #testcases
n = int(input())
li = list(map(int, input().strip().split())) #<--- before that loop is removed.
count = 0
max_count=0
for i in range(len(li)):
if (li[i] != 1): #<------- Here
count = 0
else:
count += 1
max_count = max(max_count,count) #<--- here
li2.append(max_count)
print()
for i in range(len(li2)):
print(li2[i])
3
5
2 1 1 1 1
3
2 3 4
7
1 2 3 1 1 1 1
4
0
4
Improve the above answer using inline function
li2 = []
t = int(input())
for i in range(0, t): #testcases
n = int(input())
li = ''.join(input().split())
li = [n if n == '1' else '0' for n in li] # replace the numbers not '1' to '0'
max_count = max(map(len, ''.join(li).split('0'))) # split by '0' and get max length from each 1's
li2.append(max_count)
print()
for i in range(len(li2)):
print(li2[i])

I am not able to understand how the output of the program is 3

num = 0
for i in range(5,0,-1):
num+= i > num
print(num)
When I ran the program it was displaying the output as 3. I am not able to understand how 3 is the output
num = 0
for i in range(5,0,-1): #Loop 5 to 1
num+= i > num # for first 3 steps ( i > num) = True = 1, i.e add 1 to num
# for remaining steps (i > num) = False = 0, i.e add 0 to num
print(i,num)
print(num)
output
5 1
4 2
3 3
2 3
1 3
3
Look at what happens inside the loop:
num = 0
for i in range(5,0,-1):
print(f'num:{num}, i:{i}, i>num:{i>num} >>> num+(i>num):{num}+{i>num}', end='=')
num+= i > num
print(f'{num}')
#print(num)
Output:
num:0, i:5, i>num:True >>> num+(i>num):0+True=1
num:1, i:4, i>num:True >>> num+(i>num):1+True=2
num:2, i:3, i>num:True >>> num+(i>num):2+True=3
num:3, i:2, i>num:False >>> num+(i>num):3+False=3
num:3, i:1, i>num:False >>> num+(i>num):3+False=3
you are checking the condition if i > num every time you increment. Here, you are not incrementing i, instead the condition i>num , which return True when i> num and increment 1 each time the condition is True.
you add to num the boolean value of i > num. in python, True is 1 and False is 0.
if you follow this logic you will see that the expression returns 1 3 times
num = 0
for i in range(5,0,-1):
num+= i > num # this line similar to num = num + (i > num)
print(num)
if i > num yeilds to True then it is equal to 1 so, thennum = num + 1
else i > num yeilds to False then it is equal to 0 so, then num = num + 0
The result of the relation (i > num) evaluated to 0/1 (True/False). Adding print to the body of the loop it may be clearer for you:
num = 0
for i in range(5,0,-1):
num+= i > num
print("i: {}, num: {}".format(i, num))
print(num)
And the output:
i: 5, num: 1
i: 4, num: 2
i: 3, num: 3
i: 2, num: 3
i: 1, num: 3
3
This loop will execute for 5 times .And i 's value will be "5 4 3 2 1"
i > num will producre , boolean values. when True it will be treated as 1 and when False 0.
So you will get 3 "True" values and 2 "False" values .Hence result is 3, which is outputed.

For loop to get iterate value python

Please help
Below is the code
start = 3
end = 5
for x in range(start, end + 1):
print x
#and
#print iterate from 0
I am looking here, x will print 3 4 5
and I also need to print 0 1 2 that first time enter to loop print 0 and second time enter to loop print 1 and so on.
Please help
python has enumerate for just this:
start = 3
end = 5
for i, x in enumerate(range(start, end + 1)):
print(i, x)
which prints:
0 3
1 4
2 5
start = 3
end = 5
counter = 0
for x in range(start, end + 1):
print x
#and
#print iterate from 0
print counter
counter += 1

Loop not functioning correctly

Working with data frames and this is the code I have for it.
numbers = 3
count=0
A = 0
B = 0
C = 0
for x in range(numbers):
if str(data.iloc[count])== 'A':
A += 1
elif str(data.iloc[count])== 'B':
B += 1
elif str(data.iloc[count])== 'C':
C += 1
count +=1
#this is to return the count to check if it works
print A
print B
print C
but for some reason when I run this code only the count for A increases.
i.e. if the data in the index had a 'A', 'B', 'B' its still returning A = 3 and B = 0 where it should be returning A = 1, B = 2, and C = 0
what am I doing wrong? thanks again.
Since your count += 1 is not within the for loop, count += 1 only runs once, after the for loop is complete. It needs to be indented. Alternatively, you do not need to use a count variable since x is already going through the range 0 to 3:
numbers = 3
A = 0
B = 0
C = 0
for x in range(numbers):
if str(data.iloc[x])== 'A':
A += 1
elif str(data.iloc[x])== 'B':
B += 1
elif str(data.iloc[x])== 'C':
C += 1
#this is to return the count to check if it works
print A
print B
print C
This also worked
count=0
numbers = 3
A = 0
B = 0
C = 0
for x in range(numbers):
count +=1
if str(data.iloc[x])== 'A':
A += 1
elif str(data.iloc[x])== 'B':
B += 1
elif str(data.iloc[x])== 'C':
C += 1
#this is to return the count to check if it works
print A
print B
print C

Categories