Python获取一个字符串所有连续子串
生活随笔
收集整理的這篇文章主要介紹了
Python获取一个字符串所有连续子串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
獲取一個字符串所有連續子串組成集合(set)的長度,居然是Facebook的interview題目,我也做出來了,哈哈:
def get_all_substrings(string):length = len(string)alist = []for i in xrange(length):for j in xrange(i,length):alist.append(string[i:j + 1]) return alistprint get_all_substring('abcde')不過感覺寫的有點simple,問問stackoverflow:
還是這樣寫比較簡單:
def get_all_substrings_1(input_string):length = len(input_string)return [input_string[i:j + 1] for i in xrange(length) for j in xrange(i,length)]還有個朋友用yeild,沒想到啊:
def get_all_substrings(string):length = len(string)for i in xrange(length):for j in xrange(i + 1, length + 1):yield(string[i:j]) for i in get_all_substrings("abcde"):print i最后是關于simple的討論:
"not so simple" -?stop. Before you go any further, please understand that?simple is good. Simple is simple to understand, simple to maintain, and simple to debug. No one is going to reject your code because it's too simple. The simpler you can make your code, the better.
看來我還是too young, too simple了...
?
轉載于:https://www.cnblogs.com/jaw-crusher/p/3607656.html
總結
以上是生活随笔為你收集整理的Python获取一个字符串所有连续子串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ASP.NET】判断访问网站的客户端是
- 下一篇: 类和对象:一些相关的BIF - 零基础入