-2

I have an ordered dictionary like following:

source =([('a',[1,2,3,4,5,6,7,11,13,17]),('b',[1,2,3,12])])

I want to calculate the length of each key's value first, then calculate the sqrt of it, say it is L.

Insert L to the positions which can be divided without remainder and insert "1" after other number.

For example, source['a'] = [1,2,3,4,5,6,7,11,13,17] the length of it is 9. Thus sqrt of len(source['a']) is 3.

Insert number 3 at the position which can be divided exactly by 3 (eg. position 3, position 6, position 9) if the position of the number can not be divided exactly by 3 then insert 1 after it.

To get a result like folloing:

result=([('a',["1,1","2,1","3,3","4,1","5,1","6,3","7,1","11,1","13,3","10,1"]),('b',["1,1","2,2","3,1","12,2"])]

I dont know how to change the item in the list to a string pair. BTW, this is not my homework assignment, I was trying to build a boolean retrival engine, the source data is too big, so I just created a simple sample here to explain what I want to achive :)

xlk3099
  • 15
  • 1
  • 3
  • If this is a standard Python dictionary, then it is not ordered. You need to use collections.OrderedDict (maybe you do?). – uselpa Mar 03 '13 at 08:43
  • It's always a good idea to show us what you tried or what you think might solve the problem, even if completely wrong. – Kev Mar 03 '13 at 16:43

1 Answers1

2

As this seems to be a homework, I will try to help you with the part you are facing problem with

I dont know how to change the item in the list to a string pair.

As the entire list needs to be updated, its better to recreate it rather than update it in place, though its possible as lists are mutable

Consider a list

lst = [1,2,3,4,5]

to convert it to a list of strings, you can use list comprehension

lst = [str(e) for e in lst]

You may also use built-in map as map(str,lst), but you need to remember than in Py3.X, map returns a map object, so it needs to be handled accordingly

Condition in a comprehension is best expressed as a conditional statement

<TRUE-STATEMENT> if <condition> else <FALSE-STATEMENT>

To get the index of any item in a list, your best bet is to use the built-in enumerate

If you need to create a formatted string expression from a sequence of items, its suggested to use the format string specifier

"{},{}".format(a,b)

The length of any sequence including a list can be calculated through the built-in len

You can use the operator ** with fractional power or use the math module and invoke the sqrt function to calculate the square-root

Now you just have to combine each of the above suggestion to solve your problem.

Abhijit
  • 62,056
  • 18
  • 131
  • 204