3

I found one code that used A[i][j] += min(A[i - 1][j and j - 1:j + 2]) I tried similar implementation as shown below which gave me unexpected results.Can anyone explain me? I am not able to understand how 'and' is interpreted in such situations.

a = [1,2,3,4,5,6,7,8,9,10,11,12]

print(a[0 and 3:4]) #[1, 2, 3, 4]

print(a[1 and 3:4]) #[4]

print(a[1 and 3:6]) #[4, 5, 6] 

print(a[0 and 3:6]) #[1, 2, 3, 4, 5, 6]

print(a[2 and 3:6]) #[4, 5, 6]

edit : in a[0 and 3:4] it includes elements from 0 to 3 but if I use a[1 and 3:4] it gives only 3rd element whereas I expect elements from 1 to 3

Karan Shah
  • 111
  • 11
  • 1
    What do you mean by _unexpected results_? – toti08 Oct 30 '18 at 08:57
  • edited. Please check – Karan Shah Oct 30 '18 at 09:00
  • 1
    `0 and 3` is `0` because `0` is falsey. `1 and 3` is `3` because `1` is truthy. See dupe target. – khelwood Oct 30 '18 at 09:03
  • 1
    Fun fact: In case you don't know: True is also an integer, i.e, 1 . [bool inherits int](https://stackoverflow.com/questions/8169001/why-is-bool-a-subclass-of-int). But be careful about [this](https://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante). – Vinay W Oct 30 '18 at 09:23

2 Answers2

3

AND has higher precedence than slice : operator.

Your expressions works as,

a[0 and 3:4] --> a[(0 and 3):4] --> a[0:4] --> [1, 2, 3, 4]
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
1

You are simply comparing integer values by "and" in your case - not the values behind the index values. If you compare anything with 0, you get 0. In all the other cases, you get the value of the second integer (Maybe not for every python interpreter).