简体   繁体   中英

Python Challenge - #3 *spoilers*

After doing some hint searching i have found that i had to import re and use regular expressions. The answer is "linkedlist". http://www.pythonchallenge.com/pc/def/equality.html

But I am curious what have I done wrong i my previous attempt to solve it?

tekstas = "the string that i need to decode"

possible_solution = []

for i in range(0, len(tekstas)):
    if ((ord(tekstas[i]) < 123) and (ord(tekstas[i]) > 96)) and ((ord(tekstas[i-1])) > 64) and ((ord(tekstas[i-1])) < 90) \
    and ((ord(tekstas[i-2])) > 64) and ((ord(tekstas[i-2])) < 90) and ((ord(tekstas[i-3])) > 64) and ((ord(tekstas[i-3])) \
    < 90) and ((ord(tekstas[i+1])) > 64) and ((ord(tekstas[i+1])) < 90) and ((ord(tekstas[i+2])) > 64) and \
    ((ord(tekstas[i+2])) < 90) and ((ord(tekstas[i+3])) > 64) and ((ord(tekstas[i+3])) < 90):
         possible_solution.append(tekstas[i-4]+tekstas[i-3]+tekstas[i-2]+tekstas[i-1]+tekstas[i]+tekstas[i+1]+tekstas[i+2]+\
            tekstas[i+3]+tekstas[i+4])

for i in range (0, len(possible_solution)):
    candidate = possible_solution[i]
    if (ord(candidate[0]) < 123) and (ord(candidate[0]) > 96) and (ord(candidate[8]) < 123) and (ord(candidate[8]) > 96):
        print(candidate[1:8])

Answers that i get: IQNlQSL OEKiVEY CNDeHSB OIXdKBF CJAsACF KWGtIDC

small letters that i get from this:liedst Why am I missing few letters??

You are excluding Z , because you are testing your uppercase letters with (ord(tekstas[i-2])) < 90 rather than (ord(tekstas[i-2])) < 91 .

Note that you don't need to use ord() here at all, you can compare directly to letters:

tekstas[i-2] < '['

or perhaps more directly recognisable:

tekstas[i-2] <= 'Z'

You don't need separate tekstas[i-2] >= 'A' and tekstas[i-2] <= 'Z' tests either; you could use chain the comparisons:

'A' <= tekstas[i-2] <= 'Z'

The easiest method, however, is to use the str.isupper() method :

tekstas[i-2].isupper()

which for the default locale is only true if all characters in the string are uppercase ASCII letters.

That means you can test more than one letter at a time; together with str.islower() your first if test could be reduced to:

tekstas[i].islower() and (tekstas[i - 3:i] + tekstas[i + 1:i + 4]).isupper()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM