递归似乎多迭代了一次,我该如何修复这段代码?

huangapple go评论101阅读模式
英文:

Recursion seems to iterate one last time how can I fix this code?

问题

以下是您提供的Python代码的翻译部分:

  1. 我正在尝试检查字符串是否是回文正反都相同
  2. 我有困扰不明白为什么输出会抛出错误错误信息说在标记为已赋值的代码之后变量未被分配我有一个基本情况和一个递归情况
  3. 我还需要只使用一个返回语句
  1. def is_palindrome(s)
  2. if len(s) <= 1: # 如果已经到达字符串的末尾
  3. print("是回文")
  4. palindrome = True
  5. print("将回文设置为True")
  6. elif len(s) > 1:
  7. print("长度不为1,再次检查")
  8. if s[0] == s[-1]:
  9. print("最左边等于最右边")
  10. newstring = s[1:]
  11. newstring = newstring[:-1]
  12. s = newstring
  13. is_palindrome(s)
  14. else:
  15. print("不是回文")
  16. palindrome = False
  17. return palindrome

输出:

  1. 长度不为1,再次检查
  2. 最左边等于最右边
  3. 长度不为1,再次检查
  4. 最左边等于最右边
  5. 长度不为1,再次检查
  6. 最左边等于最右边
  7. 是回文
  8. 将回文设置为True

错误:

  1. Traceback (most recent call last):
  2. line 16, in <module>
  3. print(is_palindrome(s))
  4. line 134, in is_palindrome
  5. is_palindrome(s)
  6. line 134, in is_palindrome
  7. is_palindrome(s)
  8. line 139, in is_palindrome
  9. return palindrome
  10. UnboundLocalError: local variable 'palindrome' referenced before assignment

编辑:
现在我有这段代码,但似乎无论如何都返回True

  1. palindrome = True
  2. #基本情况
  3. if len(s) > 1:
  4. print("长度不为1,再次检查")
  5. if s[0] == s[-1]:
  6. print("最左边等于最右边")
  7. newstring = s[1:]
  8. newstring = newstring[:-1]
  9. s = newstring
  10. is_palindrome(s)
  11. else:
  12. print("不是回文")
  13. palindrome = False
  14. return palindrome

输出:

  1. 长度不为1,再次检查
  2. 最左边等于最右边
  3. 长度不为1,再次检查
  4. 最左边等于最右边
  5. 长度不为1,再次检查
  6. 不是回文
  7. True
英文:

I am attempting to check if a string is a palindrome or not( reads the same forwards and backwards )

I am having trouble understanding why the output is throwing the error that the variable has not been assigned after the code that says it has been assigned. I have a base case and a recursive case.

I also need to use only one return.

  1. def is_palindrome(s)
  2. if len(s)&lt;=1: # if we have reached the end of the string
  3. print(&quot;is palindrome&quot;)
  4. palindrome = True
  5. print(&quot;set palindrome to true&quot;)
  6. elif len(s)&gt;1:
  7. print(&quot;length not 1, checking again&quot;)
  8. if s[0] == s[-1]:
  9. print(&quot;leftmost = rightmost&quot;)
  10. newstring = s[1:]
  11. newstring = newstring[:-1]
  12. s = newstring
  13. is_palindrome(s)
  14. else:
  15. print(&quot;not palindrome&quot;)
  16. palindrome = False
  17. return palindrome

Output:

  1. length not 1, checking again
  2. leftmost = rightmost
  3. length not 1, checking again
  4. leftmost = rightmost
  5. length not 1, checking again
  6. leftmost = rightmost
  7. is palindrome
  8. set palindrome to true

Error:

  1. Traceback (most recent call last):
  2. line 16, in &lt;module&gt;
  3. print(is_palindrome(s))
  4. line 134, in is_palindrome
  5. is_palindrome(s)
  6. line 134, in is_palindrome
  7. is_palindrome(s)
  8. line 139, in is_palindrome
  9. return palindrome UnboundLocalError: local variable &#39;palindrome&#39; referenced before assignment

EDIT:
I now have this code however it seems as though it is returning true regardless

CODE:

  1. palindrome = True
  2. #BASE CASE
  3. if len(s)&gt;1:
  4. print(&quot;length not 1, checking again&quot;)
  5. if s[0] == s[-1]:
  6. print(&quot;leftmost = rightmost&quot;)
  7. newstring = s[1:]
  8. newstring = newstring[:-1]
  9. s = newstring
  10. is_palindrome(s)
  11. else:
  12. print(&quot;not palindrome&quot;)
  13. palindrome = False
  14. return palindrome

OUTPUT:

  1. length not 1, checking again
  2. leftmost = rightmost
  3. length not 1, checking again
  4. leftmost = rightmost
  5. length not 1, checking again
  6. not palindrome
  7. True

答案1

得分: 2

问题在于你假设palindrome变量在整个递归过程中保持不变,但实际上它在每次递归开始时都是不同的数据片段。所以如果你只关注第一层递归:

  1. def is_palindrome(s):
  2. if len(s) <= 1: # 如果我们已经到达字符串的末尾
  3. # print("is palindrome")
  4. # palindrome = True
  5. # print("set palindrome to true")
  6. elif len(s) > 1:
  7. print("length not 1, checking again")
  8. if s[0] == s[-1]:
  9. print("leftmost = rightmost")
  10. newstring = s[1:]
  11. newstring = newstring[:-1]
  12. s = newstring
  13. is_palindrome(s)
  14. # else:
  15. # print("not palindrome")
  16. # palindrome = False
  17. return palindrome

你会得到这个结果。我已经注释掉了那些在第一层递归中不运行的部分,正如你所看到的,palindrome 从未被设置。为了实现你想要的效果,我会将这一行:

  1. if s[0] == s[-1]:
  2. print("leftmost = rightmost")
  3. newstring = s[1:]
  4. newstring = newstring[:-1]
  5. s = newstring
  6. is_palindrome(s)

写成这样:

  1. if s[0] == s[-1]:
  2. print("leftmost = rightmost")
  3. newstring = s[1:]
  4. newstring = newstring[:-1]
  5. s = newstring
  6. palindrome = is_palindrome(s)
英文:

The issue is that you're assuming the palindrome variable is carried throughout the recursion, but it is a different piece of data each time recursion starts. So if you only follow the very first layer:

  1. def is_palindrome(s)
  2. if len(s)&lt;=1: # if we have reached the end of the string
  3. # print(&quot;is palindrome&quot;)
  4. # palindrome = True
  5. # print(&quot;set palindrome to true&quot;)
  6. elif len(s)&gt;1:
  7. print(&quot;length not 1, checking again&quot;)
  8. if s[0] == s[-1]:
  9. print(&quot;leftmost = rightmost&quot;)
  10. newstring = s[1:]
  11. newstring = newstring[:-1]
  12. s = newstring
  13. is_palindrome(s)
  14. # else:
  15. # print(&quot;not palindrome&quot;)
  16. # palindrome = False
  17. return palindrome

you get this. I commented out everything that doesn't run on the first layer, as you can see palindrome is never set. To accomplish what you want, I would take the line:

  1. if s[0] == s[-1]:
  2. print(&quot;leftmost = rightmost&quot;)
  3. newstring = s[1:]
  4. newstring = newstring[:-1]
  5. s = newstring
  6. is_palindrome(s)

and write it like this:

  1. if s[0] == s[-1]:
  2. print(&quot;leftmost = rightmost&quot;)
  3. newstring = s[1:]
  4. newstring = newstring[:-1]
  5. s = newstring
  6. palindrome = is_palindrome(s)

答案2

得分: 0

以下是已翻译好的部分:

关键问题在于这行代码:

  1. is_palindrome(s)

知道 is_palindrome() 返回一个值,但你忽略了它。你忽略的返回值是解决问题的关键。这里是问题的简化逻辑:

  1. def is_palindrome(s):
  2. palindrome = False # 假设不是回文
  3. if len(s) <= 1: # 我们已经到达最小字符串
  4. palindrome = True # 它是回文
  5. elif s[0] == s[-1]: # 如果最左边等于最右边
  6. palindrome = is_palindrome(s[1:-1]) # 递归处理“内部”字符串
  7. return palindrome
  8. if is_palindrome("9609457639843489367549069"):
  9. print("是回文")

由于这段代码不处理大小写、空格和标点符号,对于语言回文来说并不像对数字回文那么有用。

英文:

A key problem is this line:

  1. is_palindrome(s)

You know is_palindrome() returns a value, but you've ignored it. That returned value you ignored is key to solving the problem. Here's a simplified logic for the problem:

  1. def is_palindrome(s):
  2. palindrome = False # assume not a palindrome
  3. if len(s) &lt;= 1: # we have reached a minimal string
  4. palindrome = True # it&#39;s palindrome
  5. elif s[0] == s[-1]: # if leftmost == rightmost
  6. palindrome = is_palindrome(s[1:-1]) # recurse on &quot;inner&quot; string
  7. return palindrome
  8. if is_palindrome(&quot;9609457639843489367549069&quot;):
  9. print(&quot;is palindrome&quot;)

Since this code doesn't handle case, white space and punctuation, it's not as useful for language palindromes as it is for things like numeric palindromes.

huangapple
  • 本文由 发表于 2023年6月15日 01:20:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定