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

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

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

问题

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

我正在尝试检查字符串是否是回文正反都相同

我有困扰不明白为什么输出会抛出错误错误信息说在标记为已赋值的代码之后变量未被分配我有一个基本情况和一个递归情况

我还需要只使用一个返回语句
def is_palindrome(s)
    if len(s) <= 1:  # 如果已经到达字符串的末尾
        print("是回文")
        palindrome = True
        print("将回文设置为True")
        
    elif len(s) > 1:
        print("长度不为1,再次检查")
        if s[0] == s[-1]:
            print("最左边等于最右边")
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)
        else:
            print("不是回文")
            palindrome = False
        
    return palindrome

输出:

长度不为1,再次检查
最左边等于最右边
长度不为1,再次检查
最左边等于最右边
长度不为1,再次检查
最左边等于最右边
是回文
将回文设置为True

错误:

Traceback (most recent call last):
    line 16, in <module>
        print(is_palindrome(s))
    line 134, in is_palindrome
        is_palindrome(s)
    line 134, in is_palindrome
        is_palindrome(s)
    line 139, in is_palindrome
        return palindrome
UnboundLocalError: local variable 'palindrome' referenced before assignment

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

palindrome = True
#基本情况
if len(s) > 1:
    print("长度不为1,再次检查")
    if s[0] == s[-1]:
        print("最左边等于最右边")
        newstring = s[1:]
        newstring = newstring[:-1]
        s = newstring
        is_palindrome(s)
    else:
        print("不是回文")
        palindrome = False

return palindrome

输出:

长度不为1,再次检查
最左边等于最右边
长度不为1,再次检查
最左边等于最右边
长度不为1,再次检查
不是回文
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.

def is_palindrome(s)
    if len(s)&lt;=1: # if we have reached the end of the string
        print(&quot;is palindrome&quot;)
        palindrome = True
        print(&quot;set palindrome to true&quot;)
        
    elif len(s)&gt;1:
        print(&quot;length not 1, checking again&quot;)
        if s[0] == s[-1]:
            print(&quot;leftmost = rightmost&quot;)
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)
        else: 
            print(&quot;not palindrome&quot;)
            palindrome = False
        
    return palindrome

Output:

length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
is palindrome
set palindrome to true

Error:

   Traceback (most recent call last):   
    line 16, in &lt;module&gt;
            print(is_palindrome(s))   
    line 134, in is_palindrome
            is_palindrome(s)   
    line 134, in is_palindrome
            is_palindrome(s)   
    line 139, in is_palindrome
            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:

palindrome = True
#BASE CASE
if len(s)&gt;1:
    print(&quot;length not 1, checking again&quot;)
    if s[0] == s[-1]:
        print(&quot;leftmost = rightmost&quot;)
        newstring = s[1:]
        newstring = newstring[:-1]
        s = newstring
        is_palindrome(s)
    else: 
        print(&quot;not palindrome&quot;)
        palindrome = False
    
return palindrome

OUTPUT:

length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
length not 1, checking again
not palindrome
True

答案1

得分: 2

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

def is_palindrome(s):
    if len(s) <= 1: # 如果我们已经到达字符串的末尾
    #    print("is palindrome")
    #    palindrome = True
    #    print("set palindrome to true")
        
    elif len(s) > 1:
        print("length not 1, checking again")
        if s[0] == s[-1]:
            print("leftmost = rightmost")
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)
    #    else: 
    #        print("not palindrome")
    #        palindrome = False
        
    return palindrome

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

        if s[0] == s[-1]:
            print("leftmost = rightmost")
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)

写成这样:

        if s[0] == s[-1]:
            print("leftmost = rightmost")
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            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:

def is_palindrome(s)
    if len(s)&lt;=1: # if we have reached the end of the string
    #    print(&quot;is palindrome&quot;)
    #    palindrome = True
    #    print(&quot;set palindrome to true&quot;)
        
    elif len(s)&gt;1:
        print(&quot;length not 1, checking again&quot;)
        if s[0] == s[-1]:
            print(&quot;leftmost = rightmost&quot;)
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)
    #    else: 
    #        print(&quot;not palindrome&quot;)
    #        palindrome = False
        
    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:

        if s[0] == s[-1]:
            print(&quot;leftmost = rightmost&quot;)
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            is_palindrome(s)

and write it like this:

        if s[0] == s[-1]:
            print(&quot;leftmost = rightmost&quot;)
            newstring = s[1:]
            newstring = newstring[:-1]
            s = newstring
            palindrome = is_palindrome(s)

答案2

得分: 0

以下是已翻译好的部分:

关键问题在于这行代码:

is_palindrome(s)

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

def is_palindrome(s):
    palindrome = False  # 假设不是回文

    if len(s) <= 1:  # 我们已经到达最小字符串
        palindrome = True  # 它是回文
    elif s[0] == s[-1]:  # 如果最左边等于最右边
        palindrome = is_palindrome(s[1:-1])  # 递归处理“内部”字符串

    return palindrome

if is_palindrome("9609457639843489367549069"):
    print("是回文")

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

英文:

A key problem is this line:

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:

def is_palindrome(s):
	palindrome = False  # assume not a palindrome

	if len(s) &lt;= 1:  # we have reached a minimal string
		palindrome = True  # it&#39;s palindrome
	elif s[0] == s[-1]:  # if leftmost == rightmost
		palindrome = is_palindrome(s[1:-1])  # recurse on &quot;inner&quot; string

	return palindrome

if is_palindrome(&quot;9609457639843489367549069&quot;):
	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:

确定