Algorithm that spans orthogonal vectors: Python The code consists of three functions:


Spans arbitrary vector (takes dimension as an argument)
Spans vector orthogonal to the one passed in the argument
Finds cross product between two vectors.


The code is following:

def span_vector(n):
    '''n represents dimension of the vector.'''
    return [random.randrange(-1000,1000) for x in range(n)]


def span_orthogonal(vec):
    '''vec represents n-dimensional vector'''
    '''Function spans an arbitrary vector that is orthogonal to vec'''

    dimension = len(vec)
    orthogonal_vec = []
    for k in range(dimension-1):
        orthogonal_vec.append(random.randrange(-1000,1000))
    last_k = ((-1)*sum([vec[x]*orthogonal_vec[x] for x in range(dimension-1)]))/vec[-1]
    orthogonal_vec.append(last_k)
    return orthogonal_vec

def cross_product(v1,v2):
    return sum(v1[x]*v2[x] for x in range(len(v1)))




What can be improved?



EDIT The last function must read dot_product, but not cross_product. I made a mistake.
You should probably be using Numpy, although I don't know enough about your situation to comment any further.

Assuming that you need to retain "pure Python", the following improvements can be made:

Negation

Replace (-1)* with -

Generators

Replace your for k in range(dimension-1): loop with

orthogonal_vec = [
    random.randrange(-1000,1000)
    for _ in range(dimension-1)
]


Type hints

n: int, vec: typing.Sequence[float] (probably) . And the first two functions return -&gt; typing.List[float]. cross_product both accepts and returns float.

Inner list

sum([ ... ])


shouldn't use an inner list. Just pass the generator directly to sum.