what does this python statement mean?
dp[i] = dp[i] or dp[i-num]
Assume that there is no for loop or if statement associated with it. please let me know of you want any more information.
what does this python statement mean?
dp[i] = dp[i] or dp[i-num]
Assume that there is no for loop or if statement associated with it. please let me know of you want any more information.
'or' returns the first true or last false answer.
It seems that either the first or the most true value is assigned to your variable. See these interactive experiments.
>>> foo = 0 or True
>>> foo
True
>>> foo = "" or type
>>> foo
<class 'type'>
>>> bar = 2 or "two"
>>> bar
2
>>> bar = "two" or 2
>>> bar
'two'
>>> bar = [None, False, True, "something"]
>>> foo = bar[0] or bar[1]
>>> foo
False
>>> foo = bar[1] or bar[2]
>>> foo
True
# but look at this last one....
>>> foo = None or False
>>> foo
False
Nothing shows up. What struck me is this last one...
>>> foo = False or None
>>> foo
>>> print(foo)
None
Does this mean "None" is more True than False? But False is False enough to be printed by the console.. I think I'm missing somewhere here but I thought I'd share.
If dp
is any list and i
is greater than num
so that the index doesn't go out of the allowed range, this is equivalent to dp[i] = dp[i] if dp[i] else (dp[i-num] if dp[i-num] else False
.
dp[i]
and dp[i-num]
will be set to true if the value at the given index is different from None or False.
Example:
> dp = ['a', True, 5, None]
> i, num = 3, 1
> dp[i] = dp[i] or dp[i-num]
> dp
['a', True, 5, 5]
In this case, it's the same thing to do:
dp[i] = None or 5
So the return will be 5
.
This changes the value of dp at index i
(so 3) to the return value(5).