Created
March 6, 2014 17:48
-
-
Save onriv/9395444 to your computer and use it in GitHub Desktop.
python;生成所有元组;多重循环节简化;tuplesGen.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """ | |
| 根据给定的范围,用混合进制的方式输出所有元组。 | |
| """ | |
| def tuplesGen(ranges): | |
| """ | |
| >>> ranges = (2,3,4) | |
| >>> for t in tuplesGen(ranges): | |
| ... print t | |
| [0, 0, 0] | |
| [1, 0, 0] | |
| [0, 1, 0] | |
| [1, 1, 0] | |
| [0, 2, 0] | |
| [1, 2, 0] | |
| [0, 0, 1] | |
| [1, 0, 1] | |
| [0, 1, 1] | |
| [1, 1, 1] | |
| [0, 2, 1] | |
| [1, 2, 1] | |
| [0, 0, 2] | |
| [1, 0, 2] | |
| [0, 1, 2] | |
| [1, 1, 2] | |
| [0, 2, 2] | |
| [1, 2, 2] | |
| [0, 0, 3] | |
| [1, 0, 3] | |
| [0, 1, 3] | |
| [1, 1, 3] | |
| [0, 2, 3] | |
| [1, 2, 3] | |
| """ | |
| n = len(ranges) | |
| t = [0 for i in xrange(n)] | |
| while True: | |
| yield t | |
| j = 0 | |
| while (j < n and t[j] == ranges[j] - 1): | |
| t[j] = 0 | |
| j += 1 | |
| if j == n: | |
| break | |
| else: | |
| t[j] += 1 | |
| if __name__ == "__main__": | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment