Micks Ketches Micks Ketches - 2 months ago 13
Python Question

Dissecting a python puzzle forloop solution

For a specific puzzle online I had to grab (using python) every lowercase letter surrounded by three uppercase letters on both sides. So for example in

'WExWQPoKLGnnNMOkPPOQ'
, the letters
ok
should be printed out. Despite finding a haphazard solution myself, a specific solution by another participant grabbed my attention:


import string
word = ""
for i in range(len(code) - 8):
if [c for c in code[i:i+9] if c in string.lowercase] == [code[i], code[i+4], code[i+8]]:
word += code[i+4]


I was wondering if someone could break down this code for me. I have some specific questions but a rundown would be great too:


  • why does
    code[i:i+9]
    not produce a
    TypeError: Can't convert 'int' object to str implicitly
    ?

  • what does
    string.lowercase
    do in this instance?

  • why does
    code[i:i+9]
    grab nine characters instead of seven(six uppercase and the lowercase in the middle)?

  • why bother checking if
    code[i+8]
    evaluates to true if
    [i+4]
    (the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?



The puzzle itself can be found here: http://www.pythonchallenge.com/pc/def/equality.html (inspect the source code)

Answer

why does code[i:i+9] not produce a TypeError: Can't convert 'int' object to str implicitly?

Why would it? It is simply a slice notation, i is an int, code is a string.

what does string.lowercase do in this instance?

It is a constant that contains all lower case letters. (It does not exist any longer in Python 3, as it is locale dependant.)

why does code[i:i+9] grab nine characters instead of seven(six uppercase and the lowercase in the middle)?

According to the actual description of the problem, the lowercase must be "surrounded by EXACTLY three" uppercase letters. So you can't just check the 7, you need all the 9.

why bother checking if code[i+8] evaluates to true if [i+4](the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?

Likewise, it is not only the 3 characters that are relevant, it is the 4. The fourth needs to be a lowercase.

What this code does it that it filters the 9-letter slice to keep only the lowercase, and checks if that is exactly the 1st, 5th and last letters.

Comments