首页 > 编程语言 > 详细

Python获取一个字符串所有连续子串

时间:2014-03-19 12:03:05      阅读:697      评论:0      收藏:0      [点我收藏+]

获取一个字符串所有连续子串组成集合(set)的长度,居然是Facebook的interview题目,我也做出来了,哈哈:

bubuko.com,布布扣
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 alist

print get_all_substring(abcde)
bubuko.com,布布扣

不过感觉写的有点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,没想到啊:

bubuko.com,布布扣
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
bubuko.com,布布扣

最后是关于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了...

Python获取一个字符串所有连续子串,布布扣,bubuko.com

Python获取一个字符串所有连续子串

原文:http://www.cnblogs.com/jaw-crusher/p/3607656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!