Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sparse vector in python?

A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 0, 2, 0]. Storing all those zeros wastes memory and dictionaries are commonly used to keep track of just the nonzero entries. For example, the vector shown earlier can be represented as {0:1, 7:2}, since the vector it is meant to represent has the value 1 at index 0 and the value 2 at index 7. Write a function that converts a sparse vector into a dictionary as described above.

Examples

>>> convertVector([1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4])
{0: 1, 3: 2, 7: 3, 12: 4}
>>> convertVector([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
{0: 1, 2: 1, 4: 2, 6: 1, 9: 1}
>>> convertVector([0, 0, 0, 0, 0])
{}

My Code

def convertVector(numbers):
    d = {i: 0 for i in numbers}
    for k, c in enumerate(numbers):
        d[c] = k  # increment its value

    return d
print convertVector([1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4])
print convertVector([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
print convertVector([0, 0, 0, 0, 0])

Code Returning it as

{0: 11, 1: 0, 2: 3, 3: 7, 4: 12}
{0: 10, 1: 9, 2: 4}
{0: 4}

The problem is it's returning last index, correspond to the value. where as it should return as

   {0: 1, 3: 2, 7: 3, 12: 4}
    {0: 1, 2: 1, 4: 2, 6: 1, 9: 1}
    {}

Any Help?

like image 640
ravenwingz Avatar asked Aug 26 '26 07:08

ravenwingz


2 Answers

def convertVector(numbers):
    d = {}
    for k, c in enumerate(numbers):
        if c:
            d[k] = c  
    return d

print convertVector([1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4])
print convertVector([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
print convertVector([0, 0, 0, 0, 0])
like image 63
Dima Kudosh Avatar answered Aug 28 '26 22:08

Dima Kudosh


A one liner using conditional dictionary comprehension:

def sparseVector(v): 
    return {n: val for n, val in enumerate(v) if val}

 v1 = [1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4]
 v2 = [1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0]
 v3 = [0, 0, 0, 0, 0]

 >>> [sparseVector(v) for v in [v1, v2, v3]]
 [{0: 1, 3: 2, 7: 3, 12: 4}, 
  {0: 1, 2: 1, 4: 2, 6: 1, 9: 1}, 
  {}]

if val at the end of the compression means that it will only add the key and value to the dictionary if val does not evaluate to False (i.e. it is not 0, None, etc.).

enumerate(v) goes through an iterable object (e.g. a list) and returns its index value together with the object/value at that location.

n: val adds the value to the dictionary keyed on index value n (only if val is not zero/None).

like image 45
Alexander Avatar answered Aug 28 '26 20:08

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!