简体   繁体   中英

Metaprogramming combinatorics

I am interested in creating a python function which takes in 2*n arguments, where n can be variable. The first n arguments are compared to the second n arguments.

Essentially, if n=2 for example, the function f(a1, a2, b1, b2) would check that (a1==b1 and a2==b2) or (a1==b2 and a2==b1) . For n=3, the function f(a1, a2, a3, b1, b2, b3) would check that (a1==b1 and a2==b2 and a3==b3) or (a1==b2 and a2==b3 and a3==b1) or (a1==b3 and a2==b1 and a3==b2)

However, I would like the function to construct the conditional statement on the fly depending on the value of n.

This is probably a tall order and I can do my own research, but is there anyone who can point me in the right direction? This would be considered metaprogramming right? Does anyone know of a library that exists for this sort of thing?

Thanks,

-AA

def f(*args):
    l = len(args)
    assert l % 2 == 0
    return args[:l / 2] == args[l / 2:] or args[:l / 2] == args[l:l / 2 - 1:-1]


assert f(True, True)
assert not f(True, False)
assert f(True, False, True, False)
assert f(True, False, False, True)
assert not f(True, False, True, True)
assert f(1, 1)
assert not f(1, 2)
assert f(1, 2, 1, 2)
assert f(1, 2, 2, 1)
assert not f(1, 2, 0, 1)
assert not f(1, 2, 1, 0)
assert f(1, 2, 3, 1, 2, 3)
assert f(1, 2, 3, 3, 2, 1)
assert not f(1, 2, 3, 1, 2, 0)
assert not f(1, 2, 3, 0, 2, 1)

Edit: Since you now specified Python, consider this an additional starting point for future askers.

You can start your research with some variadic templates:

template<typename... Args>
void foo(Args&&... args) {
  static_assert(sizeof...(args) % 2 == 0, "Need 2*n parameters for some n");
  // Condition using array + parameter pack expansion.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM