0
\$\begingroup\$

I'm looking for a way to make my code more simple. This code takes a list of vectors and returns all subset of that list that sum up to another vector.

For example:

{'a','b','c'} is the subset consisting of: a (1100000), b (0110000), and c (0011000).

def AddVectors(A, B):
    if not A:
        return B
    if not B:
        return A
    return [A[i] + B[i] for i in range(len(A))]

def SumVectorList(lst, SuperSet):
    result = []
    for l in lst:
        if not result:
            result = SuperSet[l]
        else:
            for j in range(len(l)):
                result = AddVectors(result, SuperSet[l[j]])
    return result

def GetPowerSet(lst):
    result = [[]]
    for x in lst:
        result.extend([subset + [x] for subset in result])
    return result

S = {'a': [one, one, 0, 0, 0, 0, 0], 'b': [0, one, one, 0, 0, 0, 0],
     'c': [0, 0, one, one, 0, 0, 0], 'd': [0, 0, 0, one, one, 0, 0],
     'e': [0, 0, 0, 0, one, one, 0], 'f': [0, 0, 0, 0, 0, one, one]}
P = GetPowerSet(S)
u = [0, 0, one, 0, 0, one, 0]
v = [0, one, 0, 0, 0, one, 0]
u_0010010 = {y for x in P for y in x if SumVectorList(x, S) == u}
u_0100010 = {y for x in P for y in x if SumVectorList(x, S) == v}
\$\endgroup\$
5
  • \$\begingroup\$ What does your code do ? What is it supposed to do ? Does it work ? I've tried replacing one by 1 and it is now running fine but it doesn't seem to be doing much. \$\endgroup\$
    – SylvainD
    Commented Jul 25, 2013 at 19:43
  • \$\begingroup\$ one should not be replace with 1. The one in this case is 1 in GF2. So one+one=0 where as 1+1 in R = 2 \$\endgroup\$ Commented Jul 25, 2013 at 19:48
  • \$\begingroup\$ @Josay As stated about I'm trying to find subset of S that when summed over GF2 you get the value of u or v respectively. I left out the GF2 portion, sorry. The code works just fine. I just was wondering how I could make it cleaner and with less lines maybe. \$\endgroup\$ Commented Jul 25, 2013 at 19:50
  • \$\begingroup\$ Thanks for the clarification. That makes sense now. Can you give the definition of one (and any other things we might need for testing purposes) ? \$\endgroup\$
    – SylvainD
    Commented Jul 25, 2013 at 20:00
  • \$\begingroup\$ @Josay you can go to resources.codingthematrix.com and Download GF2.py \$\endgroup\$ Commented Jul 25, 2013 at 20:38

1 Answer 1

2
\$\begingroup\$

Please have a look at PEP 8 giving the Style Guide for Python Code.

Now, in AddVectors (or add_vectors), it seems like you assume that A and B have the same size. You could achieve the same result with zip.

def add_vectors(a, b):
    assert(len(a)==len(b))
    return [sum(i) for i in zip(a,b)]

I have to go, I'll some more later :-)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.