2016-04-23 65 views
0

编写一个接受单词作为输入的程序,并确定它是否有连续的三个字母,这些字母在字母表中也是连续的字母。三个连续字符也是按字母顺序排列

这个对我来说很难。我的过程是使用ord()并得到一个平均值,如果mean =第二个字符是正确的。

word = input("Please enter a word:") 

n = len(word) 

for i in range(n-2): 
i = 0 
if ord (word [i+1]) - ord (word [i]) == 1: 
    print("This works!") 

elif ord (word [i+2] - ord (word [i+1] - ord (word [i]) == 1: 
    print ("This also works. 

else: 
    print("This doesn't work.") 
+1

有你的程序中几个语法/缩进错误,因此它赢得了”即使通过编译阶段 - 请提供一个实际运行的程序。关于我认为你想写的一些评论:1.为什么第一个只检查两个字母的“if”条件? 2.三个字母的意思应该如何帮助?它会确定'ace'是连续的... –

回答

1

使用均值不是一个好主意。 8,9,10的平均值为9,但平均值为5,9,13

如何做的问题指出:

def consec(s, n=3): 
    l = len(s) 
    if l < n: 
     raise ValueError("String too short to contain repetition of length {}".format(n)) 
    for i in range(l-2): 
     # Check if you get the same letter by adding 1 or 2 to the next ones 
     # or by substracting 1 or 2... 
     if ord(s[i]) == ord(s[i+1])+1 == ord(s[i+2])+2 or \ 
      ord(s[i]) == ord(s[i+1])-1 == ord(s[i+2])-2: 
      return s[i:i+3] 
    return "" 

这是区分大小写的,顺便说一句:

In [11]: consec("cba") 
Out[11]: 'cba' 

In [12]: consec("Abc") 
Out[12]: '' 

In [13]: consec("cdskj sdoifsdjflkduf sdfjstudfu0gnfgsba") 
Out[13]: 'stu'