Created
January 2, 2022 19:46
-
-
Save arsho/9e5358e62f3d2fd1419a953e3587a37c to your computer and use it in GitHub Desktop.
Revisions
-
arsho created this gist
Jan 2, 2022 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ ### Four numbers each from -1 to 1 that sum up to 1 You can use Python's [combination with replacement method](https://docs.python.org/3.1/library/itertools.html?highlight=combinations#itertools.combinations_with_replacement). ``` from itertools import combinations_with_replacement import csv def get_four_numbers(target_sum=100): result = [] ar = list(range(-100, 101, 1)) for quadruplet in combinations_with_replacement(ar, 4): if sum(quadruplet) == target_sum: result.append([i / 100.0 for i in quadruplet]) return result if __name__ == "__main__": with open("output.csv", "w") as output_file: csv_writer = csv.writer(output_file) csv_writer.writerows(get_four_numbers()) ``` **Output from `output.csv` (truncated due to filesize):** ``` -1.0,0.0,1.0,1.0 -1.0,0.01,0.99,1.0 -1.0,0.02,0.98,1.0 -1.0,0.02,0.99,0.99 -1.0,0.03,0.97,1.0 -1.0,0.03,0.98,0.99 -1.0,0.04,0.96,1.0 ..... ``` **References:** - [combination with replacement method](https://docs.python.org/3.1/library/itertools.html?highlight=combinations#itertools.combinations_with_replacement)