zoukankan      html  css  js  c++  java
  • 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 alist
    
    print 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了...

  • 相关阅读:
    单词统计-续
    “帮你APP”团队冲刺10
    软件工程周总结15
    梦断代码阅读笔记03
    个人课程总结
    梦断代码阅读笔记02
    梦断代码阅读笔记01
    软件工程周总结14
    计算最长英语单词链
    软件工程周总结13
  • 原文地址:https://www.cnblogs.com/jaw-crusher/p/3607656.html
Copyright © 2011-2022 走看看