defcountdown(k): if k>0: yield k yieldfrom countdown(k-1) ''' 等价于 for i in countdown(k-1): yield i ''' else: yield'Blast off' if __name__ == "__main__": t = countdown(3) for i in t: print(i)
3
2
1
Blast of
1 2 3 4 5 6 7 8 9 10 11 12
defprefixes(s): if s: yieldfrom prefixes(s[:-1]) yield s defsubstrings(s): if s: yieldfrom prefixes(s) yieldfrom substrings(s[1:]) if __name__ == "__main__": print(list(prefixes("both"))) print(list(substrings("top")))
defpartitions(n,m): if n<0or m==0: return [] else: exact_match = [] if n==m: exact_match = [str(m)] with_m = [p+'+'+str(m) for p in partitions(n-m,m)] without_m = partitions(n,m-1) return exact_match+with_m+without_m if __name__ == "__main__": for p in partitions(6,4): print(p)
defpartitions(n,m): if n>0and m>0: if n==m: yieldstr(m) for p in partitions(n-m,m): yield p+'+'+str(m) yieldfrom partitions(n,m-1) if __name__ == "__main__": t = partitions(6,4) for p inrange(5): print(next(t))