Python中的快乐数算法

Python中的快乐数算法,python,algorithm,Python,Algorithm,我在解决快乐数算法问题 这是我的密码 class Solution: def isHappy(self, n): nums = str(n) while len(nums)!=1: result = 0 for num in nums: result += int(num) * int(num) nums = str(result) if (nums == '1'): print("True")

我在解决快乐数算法问题

这是我的密码

class Solution:
def isHappy(self, n):
    nums = str(n)
    while len(nums)!=1:
        result = 0
        for num in nums:
            result += int(num) * int(num)
        nums = str(result)
    if (nums == '1'): print("True")
    else: print("False")
如果输入中1的总数为7,则有错误。 类似于[11111111111111111101111111011111]

这些数字必须是真的,但结果是假的

我知道它需要在while循环中再重复一次,但每次我试图修复代码时,都会出现更多错误


我不知道如何修复这个代码。你能给我一个提示吗?

试试这样的。如果我做对了,停止循环的主要条件是得到相同的数和。您可以将它们存储在listtuple中进行检查

class Solution:
    def isHappy(self, n: int) -> bool:
        nums = str(n)
        checked = []
        current_sum = 0
        while current_sum != 1:
            current_sum = sum(int(item)**2 for item in nums)
            if current_sum not in checked:
                checked.append(current_sum)
            else:
                return False
            nums = str(current_sum)
        return True

试试这样的。如果我做对了,停止循环的主要条件是得到相同的数和。您可以将它们存储在listtuple中进行检查

class Solution:
    def isHappy(self, n: int) -> bool:
        nums = str(n)
        checked = []
        current_sum = 0
        while current_sum != 1:
            current_sum = sum(int(item)**2 for item in nums)
            if current_sum not in checked:
                checked.append(current_sum)
            else:
                return False
            nums = str(current_sum)
        return True

你需要使用一个列表来保存你已经通过的号码,如果你碰巧再次落入其中一个,你就会知道你处于一个循环中

要停止您遇到的问题,您应该在以下情况之一发生时退出while:

1-结果正好是1

2-您在已检查的结果列表中找到您的结果

鉴于此,以下是修复代码的方法,但我建议您在检查解决方案之前尝试:

def isHappy(self, n):
    checked = []
    nums = str(n)
    while nums != '1' and not (nums in checked):
        checked.append(nums)
        result = 0
        for num in nums:
            result += int(num) * int(num)
        nums = str(result)
    if (nums == '1'): print("True")
    else: print("False")

你需要使用一个列表来保存你已经通过的号码,如果你碰巧再次落入其中一个,你就会知道你处于一个循环中

要停止您遇到的问题,您应该在以下情况之一发生时退出while:

1-结果正好是1

2-您在已检查的结果列表中找到您的结果

鉴于此,以下是修复代码的方法,但我建议您在检查解决方案之前尝试:

def isHappy(self, n):
    checked = []
    nums = str(n)
    while nums != '1' and not (nums in checked):
        checked.append(nums)
        result = 0
        for num in nums:
            result += int(num) * int(num)
        nums = str(result)
    if (nums == '1'): print("True")
    else: print("False")

问题是在循环为“1”之前终止循环。 您需要检查nums!='1'处于循环状态

class Solution:
    def is_happy(self, n):
        checked_values = set()
        nums = str(n)
        while nums!='1':
            result = 0
            for num in nums:
                result += int(num) * int(num)
            nums = str(result)
            if nums in checked_values:
                print("False")
                return
            else:
                checked_values.add(nums)
        print("True")           

问题是在循环为“1”之前终止循环。 您需要检查nums!='1'处于循环状态

class Solution:
    def is_happy(self, n):
        checked_values = set()
        nums = str(n)
        while nums!='1':
            result = 0
            for num in nums:
                result += int(num) * int(num)
            nums = str(result)
            if nums in checked_values:
                print("False")
                return
            else:
                checked_values.add(nums)
        print("True")           

这些语句告诉您存在无限循环-您需要记住已检查的数字以避免循环:

投入2:

2 => 4 => 16 => 37 => 58 => 89 => 145 => 42 => 20 ===> 2 ===>  Cycle
递归方法:

class Solution:
    # remember all things we already saw - avoid endless loops
    seen = set()

    def isHappy(self, n: int) -> bool:
        if n in Solution.seen:
            # clear the cache for next try
            Solution.seen.clear()
            return False
        Solution.seen.add(n)

        s = sum(l*l for l in map(int,str(n)))

        if s == 1:
            # clear the cache for next try
            Solution.seen.clear()
            return True

        return self.isHappy(s)

s = Solution()
测试:

输出:

Happy 1
Happy 7
Happy 10
Happy 13
Happy 19
Happy 23
Happy 28

这些语句告诉您存在无限循环-您需要记住已检查的数字以避免循环:

投入2:

2 => 4 => 16 => 37 => 58 => 89 => 145 => 42 => 20 ===> 2 ===>  Cycle
递归方法:

class Solution:
    # remember all things we already saw - avoid endless loops
    seen = set()

    def isHappy(self, n: int) -> bool:
        if n in Solution.seen:
            # clear the cache for next try
            Solution.seen.clear()
            return False
        Solution.seen.add(n)

        s = sum(l*l for l in map(int,str(n)))

        if s == 1:
            # clear the cache for next try
            Solution.seen.clear()
            return True

        return self.isHappy(s)

s = Solution()
测试:

输出:

Happy 1
Happy 7
Happy 10
Happy 13
Happy 19
Happy 23
Happy 28

对早期元素重复使用周期检测的简单非优化方法。把它们放在禁忌里

def isHappy(n):
    tabu = []

    # initial calculations
    nums = list(map(int, str(n))) # 123 -> [1,2,3]
    sum = 0
    for x in nums:
        sum += x ** 2

    while True:
        # check return conditions
        if sum in tabu:
            return False
        elif sum == 1:
            return True

        nums = list(map(int, str(sum)))  # 123 -> [1,2,3]
        if sum not in nums:
            tabu.append(sum)
        sum = 0
        for x in nums:
            sum += x ** 2


assert isHappy(19) is True
assert isHappy(20) is False
assert isHappy(16) is False
assert isHappy(79) is True
assert isHappy(947) is False
assert isHappy(123) is False
assert isHappy(1233) is True
assert isHappy(16679) is True
assert isHappy(111319) is True

对早期元素重复使用周期检测的简单非优化方法。把它们放在禁忌里

def isHappy(n):
    tabu = []

    # initial calculations
    nums = list(map(int, str(n))) # 123 -> [1,2,3]
    sum = 0
    for x in nums:
        sum += x ** 2

    while True:
        # check return conditions
        if sum in tabu:
            return False
        elif sum == 1:
            return True

        nums = list(map(int, str(sum)))  # 123 -> [1,2,3]
        if sum not in nums:
            tabu.append(sum)
        sum = 0
        for x in nums:
            sum += x ** 2


assert isHappy(19) is True
assert isHappy(20) is False
assert isHappy(16) is False
assert isHappy(79) is True
assert isHappy(947) is False
assert isHappy(123) is False
assert isHappy(1233) is True
assert isHappy(16679) is True
assert isHappy(111319) is True

您的输入数据中缺少两个“”。如问题中所述,如果进程处于不包含1的循环中,您的代码将无法检测到它,并将永远循环。此外,您的代码将为从2到9的每一个数字返回false,而无需检查…您的输入数据中缺少两个“”。如问题中所述,该过程落入一个不包含1的循环中,您的代码将不会检测到它,并将永远循环。此外,您的代码将在不检查的情况下,为从2到9的每个数字返回false。。。