gpt4 book ai didi

python - 方案到 Python : most elegant translation of a recursive procedure?

转载 作者:行者123 更新时间:2023-11-28 20:53:15 25 4
gpt4 key购买 nike

我最近再次阅读了“简单方案”一书中的递归介绍(这里是相关章节的link),其中介绍了这个递归过程(在方案语言中) :

(define (downup wd)
(if (= (count wd) 1)
(se wd)
(se wd (downup (bl wd)) wd)))

> (downup 'toe)
(TOE TO T TO TOE)

> (downup 'banana)
(BANANA BANAN BANA BAN BA B BA BAN BANA BANAN BANANA)

我试图将该程序翻译成 python,我在日常工作中使用它。结果如下:

def recursivefun(word):
if len(word) == 1:
return word
else:
x = []
x.append(word)
x.extend(recursivefun(word[1:]))
x.append(word)
return x

print recursivefun("ciao")
# ==> ['ciao', 'iao', 'ao', 'o', 'ao', 'iao', 'ciao']

所以我的问题是:有没有更好的方法在 python 中表示这个递归过程?或者更“优雅”的方式?

最佳答案

如果你想更接近地表示原始的递归 Scheme 函数:

def downup(word):
if len(word) <= 1:
return [word]
return [word] + downup(s[1:]) + [word]

请注意,如果传入字符串的长度为 1,您自己的函数将返回一个字符串,否则返回一个列表。这可能会导致令人惊讶的行为。尝试

def recursivefun(word):
if len(word) == 2:
return word
else:
x = []
x.append(word)
x.extend(recursivefun(word[1:]))
x.append(word)
return x

print recursivefun("banana")

例如,打印

['banana', 'anana', 'nana', 'ana', 'n', 'a', 'ana', 'nana', 'anana', 'banana']

这可能与您的预期不同。

关于python - 方案到 Python : most elegant translation of a recursive procedure?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5300242/

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