Python挑战级别3.为什么我的代码不起作用?

时间:2012-11-30 04:35:41

标签: python

所以我知道这是非常脏的,可能效率低下的代码,但我只是想看看能否让它工作。我只是不明白为什么它不起作用...我正在访问的文件中的文本是http://www.pythonchallenge.com/pc/def/equality.html的来源。有什么帮助吗?

#! /usr/bin/python

# This program searches a string for a lowercase letter that has 3, and only 3,
# uppercase letters to the left of it, and 3, and only 3, uppercase letters to
# the right of it. It then returns that lowercase letter.

from string import lowercase
from string import uppercase

# Open the text file containing the string and set it to variable str
fileHandle = open ( 'bodyguards.txt', 'r' )
str = fileHandle.read()
fileHandle.close()
#str = 'BIGaBIGaBIGaBIG'

# Search for a lowercase letter.
def isitlower(str):
    for a in str :
        if a in lowercase:
            letterposition = str.index(a) 
            r =threebgright(letterposition)
            l =threebgleft(letterposition)
            if r !=None and l !=None:
                print l,":",a,":", r

def threebgright(letterposition):
    if str[letterposition + 1] in uppercase and str[letterposition +2] in uppercase and         str[letterposition + 3] in uppercase and str[letterposition + 4] not in uppercase:
        return str[letterposition+1], str[letterposition+2], str[letterposition+3]
    else:
        return None

def threebgleft(letterposition):
    if str[letterposition - 1] in uppercase and str[letterposition -2] in uppercase and     str[letterposition - 3] in uppercase and str[letterposition - 4] not in uppercase:
        return str[letterposition-1], str[letterposition-2], str[letterposition-3]
    else:
        return None

isitlower(str)

2 个答案:

答案 0 :(得分:0)

这将在str:

中找到a的第一次出现的索引
letterposition = str.index(a)

可能不是你想要的。正确的方法是使用enumerate

def isitlower(my_str):
    for a, letter_position in enumerate(my_str):
        if a in lowercase:
            r =threebgright(letterposition)
            l =threebgleft(letterposition)
            if r !=None and l !=None:
                print l,":",a,":", r

最好不要将str用作变量名称,因为它是内置type / function

答案 1 :(得分:0)

python的许多好处之一是正则表达式。可以通过导入re模块来访问python中的正则表达式。你的答案太复杂,累人而且效率低。最好遵循KISS(保持简单和小巧)。一个更简单的解决方案是:

data = " All that huge text "

bodyguarded = re.findall('[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]')
print "".join(bodyguared)

解释

[^A-Z]

请记住,小的那个应该有完全 3个大字母。如果我们删除它,“SJDHjHDG”之类的东西就会变得正确。这基本上做的是在[A-Z] {3}定义的三个上限出现之前不需要任何上限。

接下来是([a-z])。这是您在中间定义单个小写字母的方法。注意它旁边没有{x}。这是因为我们只想要一个出现。例如:'ABCjjKLM'不正确,因为中间的小写字符不止一个。

我们希望小写字母为 sourrounded ,因此我们希望 右侧 侧([A-Z]{3})再出现3次,但不再,这就是我们添加[^A-Z]的原因。正如我之前解释的那样,'AJDkKLKM' 'JHKHjLKKK'这样的案例不正确,因为我们只需要出现3次大写字母。这就是说,在3个上限([A-Z]{3})之后,除了A到Z范围内的任何字符都是有效的。

最后有print "".join(bodyguard)

我这样做只是为了便于阅读。

re模块的findall函数在列表中返回其结果。 如果我们print bodyguard我们会得到这样的结果:[x,y,z,r,q,i] 相反,我们得到'xyzrqi',因为列表中的所有元素都以""的字符串连接在一起,这是空的。

希望我帮助过。

相关问题