0

Stuck again, this time my problem is getting the dictionary to be sorted in ascending order. Please Advise! the following is what the task says:
"""
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 wrote the following:

def convertVector(numbers):
	t = []
	c = []
	h = len(numbers)
	for x in numbers:
		if x == 0:
			continue
		else:
			t.append(numbers.index(x)+ (h-len(numbers)))
			c.append(x)
			numbers.pop(numbers.index(x))
	return dict(zip(t,c))

which returns the correct results, but in the wrong order, i experimented with sort and sorted but it always messed up, how can i sort the dictionary as it is, without changing the results? seems i always get stuck at the easiest bits

Help appreciated.

2
Contributors
2
Replies
7
Views
5 Years
Discussion Span
Last Post by pwolf
1

You are not taking dictionary as input, this is the other direction? The dictionary has not order, so that does not matter.

>>> def print_dictionary(d):
	print '[%s]' % (', '.join('%s' % (0 if v not in d else d[v]) for v in range(min(d), max(d)+1)))
	
>>> print_dictionary({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
[1, 0, 1, 0, 2, 0, 1, 0, 0, 1]
>>>

Edited by pyTony: n/a

0

LOL, i realized my mistake, i hit submit and it went, but came back wanting the sparse vector, but i realized just now its just a very similar exercise, so i already completed the one before. Thanks for the help though!

This question has already been answered. 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.