954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Quiz of the day: slicing

I thought to post some not quite so trivial as it looks quiz for Python, to test if your brain has Python installed OK ;)

Try to figure out what interpreter answers (#? lines), then check with your Python interpreter of choice:

>>> a = list(range(10))
>>> a[1:1]
#?
>>> a[1:1] = a[-2::-1]
>>> a
#?
>>>
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Hmmn, the results were quite different from what I'd expected, for the first line in particular (I suspect my old Lisp biases are showing through on that one). I may need to go back to review certain aspects of the language.

Schol-R-LEA
Posting Pro
556 posts since Oct 2010
Reputation Points: 254
Solved Threads: 85
 

Hmm ...

a = list(range(10))
print a[::-----1]
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

hmmm.

a = list(range(10))
a[::-2] = "ZYXWV"
print (a)

I had completely forgotten about the step option for slices.

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

Welcome to Daniweb Python Forum newbies ;). Even somebody could think that you do half decent code.

Actually the idea of exercise was something like this (thoughts of solver):

"""Hmmm, this is not really slice at all beginning is same as end, of course it is this first element. Tsk, Tsk, Tony trying to mislead me: In Python indexes start with zero, so it is then the second element 1 in list as list: [1] (WRONG)

And then the second one, OK I know this -1 step, it is one of favourite tricks here in Daniweb, it reverse this sequence, hey what this means... OK, starting from second last until the end, of course, so these two last ones are reversed, and then put them in... where? Oh this is the first slice, I saw this in documentation, where they explain insert function. So we insert at begining [10, 9], no ups, [9, 8], but are they going as one element like append or inside like with extend? The left side is slice, so they go like extend. So it will be [9, 8,.. I mean [0, 9, 8, 1, 2, 3, 4, 5, 6, 7] , no it continues, we did not move them but copy them:
[0, 9, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9] (WRONG)"""

But tsk, tsk Vegaseat: that is obfuscating, I was not doing that. Even maybe PEP8 does not disallow that. Counting even odd is job for computer not for reader of your code:

print(list(reversed(a)) if len('-----') & 1 else a)


Griswolf: The infuriating thing is that you must have exactly correct number of elements in right hand side, Python does not drop extra ones or evaluate only the needed ones lazyly or give you access to expected number of lhs sequence elements to slice rhs accordingly. This however works with both odd and even number of elements.

a= list(range(11))
>>> a[1::2], a[::2] = a[:len(a)//2], a[len(a)//2:]
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Just a note,maybe meant to give more brainwork to call a list on range()
that is returning a list.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

No the list is necessary for Python 3, so used that and also try to use one argument print with one argument and format in () instead of multiargument print for Python 2.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Yes of course didn't think of python 3.
xrange() in python 2.x,same as range() in python 3.
An python 3 has only range() that is returing an iteator.

snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

Mildly more complex, but very practical ...

s = "threestoryhomesdrainpipes"
size = 5
print([s[k:k+size] for k in range(0, len(s), size)])
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

One more potential teaser ...

military_time = '0100'

print(int(military_time[:-2]))
print(int(military_time[-2:]))

military_time = '100'

print(int(military_time[:-2]))
print(int(military_time[-2:]))
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Mildly more complex, but very practical ...

s = "threestoryhomesdrainpipes"
size = 5
print([s[k:k+size] for k in range(0, len(s), size)])


If you like iterators, you can do it like this (from my Quest for most stupid Sudoku solver , based on documentation izip recipe):

def grouper(n, iterable): return zip(*((iter(iterable),) * n))

s =  "threestoryhomesdrainpipes"
size = 5
# map
print(list(map(''.join, grouper(size, s))))
# list comprehension
print([''.join(group) for group in grouper(size, s)])
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 
s = 'abcdefg'

print(s[-2:])
print(s[:-2])
print(s[::-2])
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

Now enough time has passed that I can give some explanation for the questions:a[1:1]
Slice has length of difference of the start and end index, places are not in letter positions but between letters: [a[1]] == a[1:2]. When beginning and end indexes are same the length is 0 so value is empty list [].
a[1:1] = a[-2::-1]
means put between value 0 and 1, going one be one behind until the beginning (negative direction end) values from second last value including that. Result is therefore: [0, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

What is then value of these basic expressions:

>>> a[-2:-1]
#?
>>> a[-1:-2]
#?
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: