获取一个字符串所有连续子串组成集合(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,问问*:
还是这样写比较简单:
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了...