为什么递归程序在运行时不显示任何内容。

2024-04-24 05:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

def ispalindrome(s):
  """Assumes s is a str 
  returns true if s is a ispalindrome
  punctuation marks, blanks, and capitals are igored """
#s=raw_input("Please enter a word to check if it is a palindrome")
  def tochars(s):
   s=s.lower()
   letters=''
   for c in s :
     if c in 'abcdefghijklmnopqrstuvwxyz':
      letters=letters+c
   return letters

  def ispal(s):
   print ' ispalindrome called with' , s
   if len(s)<=1 :
    print "about to return to from base case"
    return True
   else :
      answer = s[0] == s[-1 ] and ispal (s[1:-1])
      print "about to return ",answer,"for" ,s
      return answer
   return ispal(tochars(s))



def testpal():
  print 'try doggod'
  print ispalindrome('doggod')

当我运行上面的代码时,它会被编译,但不会返回任何信息。没有错误消息,但程序不会打印任何内容。请给些建议


Tags: andtoanswerinforreturnifis
1条回答
网友
1楼 · 发布于 2024-04-24 05:48:47

线路

return ispal(tochars(s))

缩进太远

这使它成为ispal(s)函数的一部分,因此从不调用它

你的缩进通常是非常不一致的(有时一个,有时两个,有时三个空格)。如果你不解决这个问题,你会不断遇到这样的错误

而且,您永远不会调用testpal()函数

如果您解决了所有这些问题,它运行良好:

def ispalindrome(s):
  def tochars(s):
    s = s.lower()
    letters = ''
    for c in s:
      if c in 'abcdefghijklmnopqrstuvwxyz':
        letters = letters + c
    return letters

  def ispal(s):
    print 'ispalindrome called with', s

    if len(s) <= 1:
      print "about to return to from base case"
      return True
    else:
      answer = s[0] == s[-1 ] and ispal (s[1:-1])
      print "about to return ", answer, "for", s
      return answer

  return ispal(tochars(s))

def testpal():
  print 'try doggod'
  print ispalindrome('doggod')

testpal()

相关问题 更多 >