作为 CS1301 问题的一部分,我正在尝试使用递归编写一个函数,该函数将执行与 len() 完全相同的操作。但是,我有两个问题:
- 我正在使用全局变量,但我在课程中还没有学到这一点。
- 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
Edit:如果你对黑魔法感兴趣,你可以考虑这个。但请你自己弄清楚为什么它会起作用。
def measure_string(myStr):
return (
(not myStr) or
(2 + measure_string(myStr[:-1]))
) - 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)