递归

有些话、适合烂在心里 提交于 2019-11-26 15:57:45

问题一:

输入正整数n,例如n=4 返回 4+3+2+1 也就是10

def rec_sum(n):
    if n == 1:
        return 1
    else:
        return n + rec_sum(n-1)
rec_sum(6)

21

问题二:

输入正整数n,例如4321 返回4+3+2+1 也就是10

def sum_func(n):
    if (n < 10):
        return n
    else:
        return n%10 + sum_func(n//10)
sum_func(4321)

10

问题三:

输入 短语字符串 和 单词列表

将字符串分割并转换为 出现的单词列表

例如:
字符串为’ilovedogsJohn’

备选单词列表为 ‘i’ ‘am’ ‘a’ ‘dogs’ ‘lover’ ‘love’ ‘John’

返回答案:‘i’ ‘love’ ‘dogs’ ‘John’

phrase = 'ilovedogsJohn'
list_of_words = ['i', 'am', 'a', 'dogs', 'lover', 'love', 'John']
#这段代码暂时只能匹配完全分割的字符串,对于部分分割还存在问题,
#而且对于单词列表中出现的,例如dogs,如果单词列表中有单词do,也会匹配出来
def word_split(phrase, list_of_words, output=None):
    pos = 0
    if output is None:
        output = []

    for word in list_of_words:
        if phrase.startswith(word):
            output.append(word)
            word_split(phrase[len(word):],list_of_words,output)
                    
    return output
word_split(phrase,list_of_words)

[‘i’, ‘love’, ‘dogs’, ‘John’]

Python startswith()方法:
描述:
Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

语法:
startswith()方法语法:
str.startswith(str, beg=0,end=len(string));

参数:
str – 检测的字符串。
strbeg – 可选参数用于设置字符串检测的起始位置。
strend – 可选参数用于设置字符串检测的结束位置。

返回值:
如果检测到字符串则返回True,否则返回False。

实例:
以下实例展示了startswith()函数的使用方法:

#!/usr/bin/python

str = "this is string example....wow!!!";
print str.startswith( 'this' );
print str.startswith( 'is', 2, 4 );
print str.startswith( 'this', 2, 4 );

以上实例输出结果如下:
True
True
False

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!