summaryrefslogtreecommitdiff
path: root/reverse.py
blob: 304baa176f081a85028a0c595d7562d7b0108d4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3
from sys import argv

def int2card(num, dim=4):
    if num != int(num):
        raise Exception("Number must be an integer.")
    if num < 0:
        raise Exception("Number must be nonnegative.")
    if num >= 3**dim:
        raise Exception("Number must be less than {}.".format(3**dim))
    strlist = []
    for i in range(dim):
        strlist.append(str(num%3))
        num //= 3
    return ''.join(reversed(strlist))

def main():
    """Reverses the card identities in a capset.out file.

    222 becomes 000, etc.
    By default, reads in capset.out and writes to capset.new
    You may give other input/output files as optional arguments.
    It will NOT reverse in-place: you must give a different output file.
    """
    inname = "capset.out"
    outname = "capset.new"
    if len(argv) == 2:
        inname = argv[1]
    if len(argv) == 3:
        inname = argv[1]
        outname = argv[2]
        if inname == outname:
            raise Exception("Input and output files must differ!")
    infile = open(inname, "r")
    outfile = open(outname, "w")

    firstline = infile.readline()
    infile.seek(0)
    capset = firstline[1:-2].split(" ")
    dim = len(capset[0])

    for line in infile:
        capset = line[1:-2].split(" ")
        newcards = []
        for card in capset:
            newcard = 3**dim - 1 - int(card, 3)
            newcards.append(int2card(newcard, dim))
        outfile.write("[" + " ".join(newcards) + "]\n")

    infile.close()
    outfile.close()

if __name__ == "__main__": main()