本文共 1539 字,大约阅读时间需要 5 分钟。
在解答卡拉兹猜想的问题时,需要如何有效地收集被覆盖的数字,并从原始列表中剔除这些数字呢?以下是详细步骤说明:
该方法首先遍历原始列表中的每个数字,使用eval
函数将其转换为浮点数,然后添加到一个新的列表c
中。同时,使用另一个列表d
来跟踪每个数字在卡拉兹过程中的转换。通过定义的judge
函数,对于每个数字进行处理,生成转换后的数字并添加到d
中。随后,收集所有转换后的数字,去重后与原始列表比较,筛选出未被覆盖的数字:
n = eval(input())ls = input().split()c = []d = []def judge(num, d): while num != 1: if num % 2 == 1: num = (3 * num + 1) // 2 d.append(num) if num % 2 == 0: num = num // 2 d.append(num) return dfor s in ls: c.append(eval(s))k = []for s in ls: k.append(eval(s)) k += judge(eval(s), d)k = list(set(k)) # 去重# 筛选出未被覆盖的数字for num in k: if num in c: c.remove(num)c.sort()# 按照需要的格式输出结果for num in c[::-1]: if num != c[0]: print(num, end=' ') else: print(num)
这种方法通过使用字典来标记覆盖情况,避免在处理过程中修改原始列表,确保所有数字都被处理:
n = eval(input())nums = list(map(int, input().split()))d = dict()d = dict.fromkeys(nums, 0) # 用字典标记被覆盖的元素for temp in nums: while temp != 1: if temp % 2 == 0: temp = temp // 2 else: temp = (3 * temp + 1) // 2 if temp in nums: d[temp] = 1# 按照字典结果进行排序和输出results = sorted(d.items(), key=lambda item: -item[0], reverse=True)flag = Falsefor result in results: if result[-1] == 0: print((' ' if flag == True else '') + str(result[0]), end='') flag = True
在验证过程中,直接使用remove
方法对原始列表进行修改会导致遍历顺序错误,无法正确处理所有数字。因此,使用字典的方法更加稳妥,能够确保所有数字被正确处理且标记累计过程不受影响。
运行上述代码,假设输入以下数字:63 5 6 7 8 11
输出应为:63 5 6 7 8 11
说明所有数字均未被卡拉兹过程覆盖。
转载地址:http://lbjaz.baihongyu.com/