Skip to content

Instantly share code, notes, and snippets.

@arsho
Created January 2, 2022 19:46
Show Gist options
  • Save arsho/9e5358e62f3d2fd1419a953e3587a37c to your computer and use it in GitHub Desktop.
Save arsho/9e5358e62f3d2fd1419a953e3587a37c to your computer and use it in GitHub Desktop.

Four numbers each from -1 to 1 that sum up to 1

You can use Python's combination with replacement method.

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment