gpt4 book ai didi

python - 康托集代码没有给出预期的输出

转载 作者:行者123 更新时间:2023-12-01 08:10:10 24 4
gpt4 key购买 nike

我在康托集代码中有一些我无法找到的错误。这个想法是,给定的数字数组,您递归地删除 1/3 的中间元素,并在两侧递归并重复直到某个阈值。

这是代码

import math

full = list(range(80))
l = list(range(80))

threshold = 2

def printl():
for i in full:
if i in l:
print("*", end='')
else:
print(" ", end='')
print()

def cantor(lo, hi):
lowi = math.ceil( (hi-lo) * 1/3 + lo)
highi = int( (hi-lo) * 2/3 + lo)

if len(l[lo:hi]) < threshold:
return

printl()
del l[lowi:highi]
cantor(lo, lowi)
cantor(lowi+1, hi)

康托尔(0, len(l)-1)

我得到了 super 奇怪的结果,不知道为什么......

enter image description here

最佳答案

一个棘手的问题 - 我计算了各个部分并递归地将它们压缩到一个数组中,然后将其转储到终端:

from math import log

def cantor(length, threshold):
if length >= threshold:
sequence = cantor(length // 3, threshold)
blanks = [" " * (length // 3)] * int(log(length, 3) + 1) # estimate and let zip toss extras
return ["*" * length] + [a + b + c for a, b, c in zip(sequence, blanks, sequence)]

return []

length = 81
threshold = 1

print(*cantor(length, threshold), sep='\n')

输出

> python3 test.py
*********************************************************************************
*************************** ***************************
********* ********* ********* *********
*** *** *** *** *** *** *** ***
* * * * * * * * * * * * * * * *
>

关于python - 康托集代码没有给出预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com