-2

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.

Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
  • Please format the code - select it and type `ctrl-k`. .. [Formatting help](https://stackoverflow.com/editing-help#code) ... [more Formatting](https://stackoverflow.com/editing-help) ... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii May 27 '20 at 19:10
  • Welcome. [Read](https://docs.python.org/3/tutorial/introduction.html#an-informal-introduction-to-python) this tutorial before starting to code, it will be really helpful. – Olvin Roght May 27 '20 at 19:12
  • 4
    What about this statement *do* you understand? – Scott Hunter May 27 '20 at 19:12
  • https://docs.python.org/3/reference/expressions.html#boolean-operations – wwii May 27 '20 at 19:12
  • You'll find this helpful I believe: https://stackoverflow.com/questions/49658308/how-does-the-logical-and-operator-work-with-integers-in-python – Yaron Grushka May 27 '20 at 19:16

2 Answers2

0

edit: as explained here:

'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.

Queuebee
  • 651
  • 1
  • 6
  • 24
0

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).