As part of a problem for CS1301, I'm trying to write a function using recursion that will perform the exact same thing as len(). However, I have two issues:
- I'm using global variables, where I haven't learned this yet in the course.
- The cs1301 autograder is telling me that my function is returning 26 instead of 13 (although when I run it, it prints 13). Not sure if this has something to do with global variable assignment.
Rest is self-explanatory as within the code below:
#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")) https://stackoverflow.com/questions/66837212/alternative-to-len-using-recursion-in-python March 28, 2021 at 07:52AM
没有评论:
发表评论