gpt4 book ai didi

python 3.3 : Recursive version of a function

转载 作者:行者123 更新时间:2023-11-28 16:46:01 25 4
gpt4 key购买 nike

def abc(s):
filter = [i for i in s.lower() if i in 'abcdefghijklmnopqrstuvwxyz']
for i in range(len(filter) - 1):
if filter[i] > filter[i+1]:
return print(s, "is not abcdearian")
return print(s, "is abcdearian")


while True:
try:
s = input("String? ")
abc(s)

我在制作 abc(s) 的递归版本时遇到问题。有什么想法吗?

最佳答案

非递归解决方案:

def issorted(L):
return all(x <= y for x, y in zip(L, L[1:]))

要制作递归函数,您应该找到一种方法将问题拆分为更小和/或更简单的子问题,这些子问题可以用相同的方式解决:

#!/usr/bin/env python3
from string import ascii_lowercase

def abcdearian(s):
return issorted_recursive([c for c in s.lower() if c in ascii_lowercase])

def issorted_recursive(L):
return L[0] <= L[1] and issorted_recursive(L[1:]) if len(L) > 1 else True

在这里issorted_recursive()是一个递归函数。基本情况是 len(L) <= 1 (具有零个或一个元素的列表始终排序,因此在这种情况下返回 True)。在递归情况下 ( len(L) > 1 ) 列表 L如果第一项按排序顺序 ( L[0] <= L[1] ) 进行排序,则视为已排序 并且 列表的其余部分 ( L[1:] ) 也已排序。每次函数收到越来越小的输入,直到发现乱序元素 ( L[0] > L[1] ) 或遇到基本情况,函数结束。

Example

while True:
s = input("String? ")
if not s:
break
print("{} is {}abcdearian".format(s, "" if abcdearian(s) else "not "))

输入

    abc    bac

Output

String? abc is abcdearian
String? bac is not abcdearian
String?

关于 python 3.3 : Recursive version of a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13637401/

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