Home > Mobile >  In python how do I preform addition/subtraction on a custom base defined by lists?
In python how do I preform addition/subtraction on a custom base defined by lists?

Time:10-23

There is probably a term for what I want to do, I will edit my question with the proper term when I find it out.

Assume 3 lists:

a = ["alpha", "beta", gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three" "four", "five"]

My custom base has the following sequence:

alpha-a-one, alpha-a-two, ..., alpha-a-five, alpha-b-one, ..., alpha-d-five, beta-a-one, ..., gamma-d-five

I want to be able to define num1 and num2 so that I can calculate addition and subtraction. For example

>>> num1 = alpha-b-two
>>> num2 = alpha-a-four
>>> num1-num2
3

and

>>> num = alpha-a-four
>>> num 3
alpha-b-two

How can I do that? (and what is the term for this?)

CodePudding user response:

If I understand what the OP means, then this is just a matter of creating the required list in the relevant order, and then doing opperations on the indexes.
For instance, the following exemplifies the minus operation, but can be generalized rather easily -

from itertools import product
a = ["alpha", "beta", "gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three", "four", "five"]

ordered_combos = list(map(lambda x: '-'.join(x), product(a, b, c)))

def weird_minus(x, y):
    assert x in ordered_combos and y in ordered_combos
    return ordered_combos.index(x) - ordered_combos.index(y)

num1 = 'alpha-b-two'
num2 = 'alpha-a-four'
print(weird_minus(num1, num2))
# 3

Not sure there a well known term. You're just enumerating a cartesian product of lists and then speaking about their respecting locations in said list.

CodePudding user response:

Do you mean "base" as in each digit has a different domain, and so your arithmetic combines base 3, base 4, and base 5 for different slots? This seems like a quite mangled way to do ... whatever it is you are hoping to accomplish. Having said that, simply mapping the symbols back to regular integers would easily do what you seem to be asking.

a = ["alpha", "beta", "gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three", "four", "five"]

def mapping():
    i = 0
    key = {}
    for _a in a:
        for _b in b:
            for _c in c:
                key["-".join([_a, _b, _c])] = i
                i  = 1
    return key

key = mapping()
reverse = {v: k for k, v in key.items()}

num1 = key["alpha-b-two"]
num2 = key["alpha-a-four"]
print(num1-num2)

print(reverse[key["alpha-a-four"]   3])

Demo: https://ideone.com/GJ1jw6

You could use the global symbol table instead of a separate dictionary, but that tends to result in confusion, and you can't use dashes in symbol names anyway.

  • Related