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 dictionary back to its sparese vector representation.

Examples

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

i am totally stuck with this problem, :( trying but nothing comes to my mind.

2
Contributors
1
14
Views
2 Years
Discussion Span
Last Post by woooee

Frist you have to determine the length of the final list. Then append zeroes unless the list offset is in the dictionary passed to the function.

``````def convert_dictionary(dict_in):
""" a dictionary's keys are not necessarily in entry order
"""
print max(dict_in.keys())
print dict_in.keys()

convert_dictionary({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
``````

Edited by woooee

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.