2013-11-27 51 views
0

len(line.strip()) == d得到None时,我将不会打印。Python Palindrome尝试和除非不打印

def isPalindrome(word): 
    if len(word) < 1: 
     return True 
    else: 
     if word[0] == word[-1]: 
      return isPalindrome(word[1:-1]) 
     else: 
      return False 

def fileInput(filename): 
    palindromes = False 
    fh = open(filename, "r") 
    length = input("Enter length of palindromes:") 
    d = int(length) 
    try: 
     for line in fh: 
      for s in str(len(line)): 
       if isPalindrome(line.strip()): 
        palindromes = True 
        if (len(line.strip()) == d): 
         print(line.strip()) 
    except: 
     print("No palindromes found for length entered.") 
    finally: 
     fh.close() 
+0

你可以编辑你的代码,使其更具可读性吗?尝试使用文本编辑器中的“代码”按钮 – duhaime

+0

您能显示文件输入的外观吗? – aIKid

+0

http://pastebin.com/MMnBErDB – user3040301

回答

2

您的代码失败了,因为您的例外不是输入文件中不存在d长度回文的唯一地方。
您还需要检查palindromes的值。

所以,在你尝试块结束时,添加打印"no palindromes found"一条线,像这样:

def fileInput(filename): 
    palindromes = False 
    # more code 
    try: 
    # more code 
    if not palindromes: 
     print("No palindromes found for length entered.") 
    except: 
    print("No palindromes found for length entered.") 
    finally: 
    # more code 

顺便说一句,我就如下清理功能:

def isPalindrome(word): 
    if not len(word): # is the same as len(word) == 0 
    return True 
    elif word[0] == word[-1]: # no need for overly nested if-else-blocks 
    return isPalindrome(word[1:-1]) 
    else: 
    return False 

def fileInput(filename): 
    palindromes = False 
    d = int(input("Enter length of palindromes:")) 
    with open(filename) as fh: # defaults to "r" mode. Also, takes care of closing the file for you 
    for line in fh: 
     word = line.strip() 
     if isPalindrome(word) and len(word) == d: # note that you didn't have the len(word)==d check before. Without that, you don't check for the length of the palindrome 
     palindromes = True 
     print(word) 
    if not palindromes: 
     print("No palindromes found for length entered.") 
+0

这工作得很好,除了我得到一个“没有找到长度输入回文列表”的无止境的列表。当我只是想要它打印一次 – user3040301

+0

@ user3040301:我怀疑你可能混合标签和空格。尝试修复代码的缩进并再次运行。此代码不应该多次打印 – inspectorG4dget