开发者

Python string length recursion

开发者 https://www.devze.com 2023-02-24 16:48 出处:网络
I\'m blanking out trying to write a simple function to count the string length recursively. I can do sums, fibonacc开发者_如何学JAVAi, and factorial easy but I\'m trying to create the simplest functi

I'm blanking out trying to write a simple function to count the string length recursively.

I can do sums, fibonacc开发者_如何学JAVAi, and factorial easy but I'm trying to create the simplest function with only one parameter, I don't like having a second just as a counter index..

Can any post something small for me?


Is this what you are looking for?

def recursiveLength(theString):
    if theString == '': return 0
    return 1 + recursiveLength(theString[1:])


This does it:

def length(s):
    return 0 if s == '' else 1 + length(s[:-1])

print length('hello world') # prints 11


Functional haskell style

       >>> def RecListValue(list_value):
               return type(list_value) in [list,str,tuple] and list_value and    1+RecListValue(list_value[1:]) or 0
       >>> example_struct  = [range(10), ("one",)*12, "simple string", 12]       
       >>> map(RecListValue, example_struct)
           [10, 12, 13, 0]
       >>> 


If it doesn't have to be tail-recursive:

def strlen(s):
  if s == '':
    return 0
  return 1 + strlen(s[1:])

It's pretty inefficient though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号