Created
August 11, 2016 04:01
-
-
Save peace098beat/3c32d8f86f637fd7a8179e174d14babb to your computer and use it in GitHub Desktop.
[Python]直積
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
| def cartesian_product(X): | |
| """直積を求める | |
| 直積とは A={a, b, c}, B={d, e}のような2つの集合が与えられたとすると | |
| A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)} | |
| """ | |
| import itertools | |
| Y = list(itertools.product(*X)) | |
| # >> [(11, 21, 31), (11, 21, 32), (11, 21, 33), (11, 22, 31), (11, 22, 32), (11, 22, 33), | |
| return Y | |
| def test_cartesian_product(): | |
| X = [ | |
| [11, 12, 13], | |
| [21, 22, 23], | |
| [31, 32, 33], | |
| ] | |
| x_size = [3, 3, 3] | |
| x_length = 3 * 3 * 3 | |
| Y = [ | |
| (11, 21, 31), | |
| (11, 21, 32), | |
| (11, 21, 33), | |
| (11, 22, 31), | |
| (11, 22, 32), | |
| (11, 22, 33), | |
| (11, 23, 31), | |
| (11, 23, 32), | |
| (11, 23, 33), | |
| (12, 21, 31), | |
| (12, 21, 32), | |
| (12, 21, 33), | |
| (12, 22, 31), | |
| (12, 22, 32), | |
| (12, 22, 33), | |
| (12, 23, 31), | |
| (12, 23, 32), | |
| (12, 23, 33), | |
| (13, 21, 31), | |
| (13, 21, 32), | |
| (13, 21, 33), | |
| (13, 22, 31), | |
| (13, 22, 32), | |
| (13, 22, 33), | |
| (13, 23, 31), | |
| (13, 23, 32), | |
| (13, 23, 33), | |
| ] | |
| y_length = len(Y) | |
| assert y_length == x_length | |
| ans = make_tree(X) | |
| assert Y == ans, (ans, Y) | |
| assert len(Y) == len(ans), (len(Y), len(ans)) | |
| def matched_list(Y1, Y2): | |
| result = [] | |
| for y1 in Y1: | |
| for y2 in Y2: | |
| if y1 == y2: | |
| assert y1 == y2, (y1, y2) | |
| result.append(y1) | |
| return result | |
| Y_matched = matched_list(Y, ans) | |
| assert len(Y) == len(Y_matched), (y_length, len(Y_matched)) | |
| test_cartesian_product() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment