Trouble comprehending expression [duplicate] - python

This question already has answers here:
Python Bool and int comparison and indexing on list with boolean values
(4 answers)
Closed 1 year ago.
I was doing a leetcode problem and while reviewing a solution I was quite dumbfounded by a certain line in the solution. The leetcode problem in particular is https://leetcode.com/problems/binary-subarrays-with-sum/
The solution:
class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
res = 0
sm = 0
sums = collections.defaultdict(int)
for a in A:
sm += a
res += sums[sm - S] + (sm == S)
sums[sm] += 1
return res
I understand everything that is going on besides this line:
res += sums[sm - S] + (sm == S)
I have never seen a conditional in an addition operation before.

Conditional expressions evaluate to booleans, which in Python are just subtypes of int. False is 0, True is 1, so adding sm == S is the same as adding 1 if sm equals S or adding 0 otherwise.

Related

Python react differently based on how I declare loop conditions [duplicate]

This question already has answers here:
Python boolean evaluation order
(2 answers)
Does Python support short-circuiting?
(3 answers)
Closed 2 years ago.
please see comments, two different while loop conditions have different outcomes, is this because of and operator? I couldn't figure out why.
def longestPalindrome(s: str) -> str:
output = ""
for i in range(len(s)):
temp = check(s,i,i)
if len(output) < len(temp):
output = temp
temp = check(s,i,i+1)
if len(output) < len(temp):
output = temp
return output
def check(s: str, l: int, r: int) -> str:
while (l >= 0 and r < len(s) and s[l] == s[r]):
# while (s[l] == s[r] and l >= 0 and r < len(s)):
# above will result in 'string index out of range' error which I couldnt figure out why
l-=1;r+=1
return s[l+1:r]
print(longestPalindrome("adaa")) # this will return "ada"
Your while statement checks left to right. So when it goes to s[l] == s[r], if any of the index value is out of range, it will error out. By checking for l and r first, you are exiting before it reaches the s[l] == s[r] condition
This is because the and operator is a short-circuit operator. This means that the second argument of the and operator is only evaluated if the first one is true.
In your case, at some point during the loop, r is equal to the length of s, so s[r] doesn't exist. The first while loop works because r < len(s) is false and thus short-circuits the last part of the condition.
In the second loop, Python, tries to evaluate s[l] == s[r] first. As s[r] doesn't exist, an IndexError is raised.
You can check out the documentation here

Find element with maximum value recursively in python [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I would write a recursive function that take a list of number as argument and return maximum element of the list. I don't want to use max() function.
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
f(a[1:])
print(f(a))
but it returns None! how can I fix it?
You should define m in your else statement and add a return in it:
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
m = f(a[1:], m)
return m
print(f(a))

Why does this function not return anything? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 years ago.
I have the following function written in python 3
def nullstelle(f,a,b,counter=0,TOL=10 ** -4):
counter = counter + 1
if counter <= 100:
g = f((a + b)/2)
if f(a) * g <= 0:
b = (a + b)/2
else:
a = (a + b)/2
if abs(a-b) <= 2*TOL:
return (a,b)
else:
nullstelle(f,a,b,counter,TOL)
else:
return (a,b)
my problem is, that for the input
def f(x):
return x ** 3 -2
nullstelle(f,0,3)
it does not return anything. I really do not understand how this is possibly.
Im sorry if this looks like a trivial question to you guys, but programming is absolutely not my main field of interest and I know nearly nothing about it (yet).
I feel like this is a duplicate, but couldn't find one quickly. The problem is that you're not returning the result of your recursive call, so you get None if you have to recurse. Change that line to:
return nullstelle(f,a,b,counter,TOL)

I am learning python. I am seeking insights for this program. Given an int array length 2, return True if it contains a 2 or a 3 [duplicate]

This question already has answers here:
Return True if array contains a 2 or a 3
(5 answers)
Closed 7 years ago.
def has23(nums):
if (2 or 3) in nums:
return True
else:
return False
result is coming out right for majority part.
but for has23[3,3] or [3,9] it is coming false.
I have 'or' argument in the code, shouldn't it mean that it will look for 2 and 3 more and n will give true if it finds any of it.
please tell me, what concept, I am missing over here?
def has23(nums):
return (2 in nums) or (3 in nums)
the expression (2 or 3) returns the value 2 so the list [3,3] would not pass.
2 or 3 evaluates to 2, so you're checking if 2 is in nums. Instead, say if 2 in nums or 3 in nums:. You don't really need the if statement, however, because you can just return the results of the expression:
return 2 in nums or 3 in nums
You can check each element explicitly if it is 2 or 3:
def has23(nums):
for i in nums:
if i in (2, 3):
return True
return False
Another way would be using generators:
def has23(nums):
return any(i in (2,3) for i in nums)
you should do this instead, it'll do the logic you want.
def has23(nums):
if 2 in nums or 3 in nums:
return True
else:
return False

Putting a simple if-then-else statement on one line [duplicate]

This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line?
For example:
if count == N:
count = 0
else:
count = N + 1
Is there a simpler way of writing this? I mean, in Objective-C I would write this as:
count = count == N ? 0 : count + 1;
Is there something similar for Python?
Update
I know that in this instance I can use count == (count + 1) % N.
I'm asking about the general syntax.
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1

Categories

Resources