gpt4 book ai didi

python - 在 python 中使用递归替代 len()

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

作为 CS1301 问题的一部分,我正在尝试使用递归编写一个函数,该函数将执行与 len() 完全相同的操作。但是,我有两个问题:

  1. 我正在使用全局变量,但我在类(class)中尚未学到这一点。
  2. cs1301 自动评分器告诉我,我的函数返回 26 而不是 13(尽管当我运行它时,它打印 13)。不确定这是否与全局变量赋值有关。

其余部分是不言自明的,如下面的代码所示:

#We've started a recursive function below called
#measure_string that should take in one string parameter,
#myStr, and returns its length. However, you may not use
#Python's built-in len function.
#
#Finish our code. We are missing the base case and the
#recursive call.
#
#HINT: Often when we have recursion involving strings, we
#want to break down the string to be in its simplest form.
#Think about how you could splice a string little by little.
#Then think about what your base case might be - what is
#the most basic, minimal string you can have in python?
#
#Hint 2: How can you establish the base case has been
#reached without the len() function?

#You may not use the built-in 'len()' function.

def measure_string(myStr):
global ind
global count
if myStr == "":
try: return count+1
except: return 0
else:
ind = 0
try: count +=1
except: count = 0
return measure_string(myStr[ind+1:])


#The line below will test your function. As written, this
#should print 13. You may modify this to test your code.
print(measure_string("13 characters"))

最佳答案

完全避免全局变量。它们在这里不是必需的。

def measure_string(myStr):
if myStr == "":
return 0
else:
return 1 + measure_string(myStr[:-1])

measure_string('myStr')
# 5

编辑:如果你对黑魔法感兴趣,你可以考虑这个。但请你自己弄清楚为什么它会起作用。

def measure_string(myStr):
return (
(not myStr) or
(2 + measure_string(myStr[:-1]))
) - 1

关于python - 在 python 中使用递归替代 len(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66837212/

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