Search code examples
pythonsparse-matrix

Python - Create sparse matrix representation from 10000 random values


I'm having a homework assignment about airport flights, where at first i have to create the representation of a sparse matrix(i, j and values) for a 1000x1000 array from 10000 random numbers with the following criteria:

  • i and j must be between 0-999 since are the rows and columns of array
  • values must be between 1.0-5.0
  • i must not be equal to j
  • i and j must be present only once

The i is the departure airport, the j is the arrival airport and the values are the hours for the trip from i to j.

Then i have to find the roundtrips for an airport A with 2 to 8 maximum stops based on the criteria above. For example:

  • A, D, F, G, A is a legal roundtrip with 4 stops
  • A, D, F, D, A is not a legal roundtrip since the D is visited twice

NOTE: the problem must be solved purely with python built-in libraries. No external libraries are accepted like scipy and numpy.

I have tried to run a loop for 10000 numbers and assign to row, column and value a random number based on the above criteria but i guess this is not what the assignment asks me to do since the loop doesn't stop.

I guess the i and j are not the actual iloc and j representations of the sparse matrix but rather the values of those? i don't know.

I currently don't have a working code other than the example for the roundtrip implementation. Although will raise an error if the list is empty:

dNext = {
    0: [],
    1: [4, 2, 0],
    2: [1, 4],
    3: [0],
    4: [3, 1]
}

def findRoundTrips(trip, n, trips):
    if (trip[0] == trip[-1]) and (1 < len(trip) <= n + 1):
        trips.append(trip.copy())
        return
    for x in dNext[trip[-1]]:
        if ((x not in trip[1:]) and (len(trip) < n)) or (x == trip[0]):
            trip.append(x)
            findRoundTrips(trip, n, trips)
            trip.pop()

Solution

  • Here's how I would build a sparse matrix:

    from collections import defaultdict
    import random
    
    max_location = 1000
    min_value = 1.0
    max_value = 5.0
    
    sparse_matrix = defaultdict(list)
    
    num_entries = 10000
    for _ in range(num_entries):
        source = random.randint(0, max_location)
        dest = random.randint(0, max_location)
        value = random.uniform(min_value, max_value)
    
        sparse_matrix[source].append((dest, value))
    

    What this does is define a sparse matrix as a dictionary where the key of the dictionary is the starting point of a trip. The values of a key define everywhere you can fly to and how long it takes to fly there as a list of tuples.

    Note, I didn't check that I'm using randint and uniform perfectly correctly, if you use this, you should look at the documentation of those functions to find out if there are any off-by-one errors in this solution.