Python的作用域问题,变量重置循环的每次迭代

2024-09-29 02:25:06 发布

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

下面的python块应该添加两个二进制数字字符串。变量res_strcarry在循环的每次迭代中都被重置为它们的初始值。你知道吗

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if len(a) < len(b):
            a.zfill(len(b))
        elif len(a) > len(b):
            b.zfill(len(a))

        res_str = ''
        carry = '0'
        for asub, bsub in reversed(list(zip(a, b))):
            print(res_str, carry)
            if asub == '1' and bsub == '1':
                res_str = '0' + res_str
                carry = '1' + carry
            elif asub == '1' or bsub == '1':
                res_str = '1' + res_str
                carry = '0' + carry
            else:
                res_str = '0' + res_str
                carry = '0' + carry
            print(res_str, carry)

        if '1' in carry:
            return self.addBinary(res_str, carry)
        else:
            return res_str

s = Solution()
s.addBinary('1', '11')
#   0
# 0 10
#   0
# 1 00
# 1

在循环的每次迭代开始时,它们的值分别是''0。它们的值在循环块期间被改变,但它们被重置。你知道吗

我试着用同样的结果将它们改为类变量(self.res_strself.carry)。你知道吗

是什么导致这些变量被重置?你知道吗

编辑:忘记使用zfill的输出


Tags: inselfleniftyperes重置solution