2

Question that asks:

"Create a function that returns the characters from a list or string r on odd or even positions, depending on the specifier s. The specifier will be "odd" for items on odd positions (1, 3, 5, ...) and "even" for items on even positions (2, 4, 6, ...)."

E.g. char_at_pos([2, 4, 6, 8, 10], "even") ➞ [4, 8]

Have managed to solve, but saw a quicker way to solve would be to use:

def char_at_pos(r, s):
    return r[s == 'even'::2]

am wondering how to interpret r[s == 'even'::2], is that adding a condition inside the index bracket before we pick the even index numbers in the list? How does it then also pick the odd numbers?

M Z
  • 4,571
  • 2
  • 13
  • 27
aatang17
  • 47
  • 1
  • 5
  • I answered a similar [question](https://stackoverflow.com/q/63713092/6692898) earlier today... is it a dupe? – RichieV Sep 03 '20 at 04:23

2 Answers2

4

r[s == 'even'::2]

s == 'even' evaluates to 1 (which is the numerical equivalent for True) if s is 'even', otherwise it evaluates to zero (which is the numerical equivalent for False). Now lets break it down based on examples:

  • r[1:10] takes all items startig at 1 till item 10 (excluded).

  • r[1:] takes all items starting at 1 till the end.

  • r[1:10:2] takes every second item starting at 1 till item 10, and

  • r[1::2] correspondingly takes every second item starting at 1 till the end.

Jim
  • 1,579
  • 1
  • 11
  • 18
1

Adding to the @jim answer,

Booleans in Python are implemented as a subclass of integers.

>>> int(True)
1
>>> int(False)
0
>>> issubclass(type(True), int)
True
>>> issubclass(type(False), int)
True

When you call r[s == 'even'::2] python calls the __getitem__ method of the list object with the slice object slice(True, None, None) or slice(False, None, None)[Depends upon the result of s == 'even']. The PySlice_Unpack C API call will extract the start, stop, step data members from a slice object as C integers. So this is where the start(boolean object) argument is actually is converting to an int object making the expression to be evaluated as same as r[1::2] or r[0::2]

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • Interesting, is this the same in other languages? I had the idea that boolean in VisualBasic was just one bit of memory 1/0... any idea why this was not done in Python to save memory? – RichieV Sep 03 '20 at 04:33
  • Nevermind, here is an alternative https://stackoverflow.com/q/142812/6692898 – RichieV Sep 03 '20 at 04:36
  • Interesting. It seems like you can indeed add True and False in python, True + True gives 2! – Jim Sep 03 '20 at 04:50