Shell halts while looping and 'transforming' values in dictionary (Python 2.7.5)
Posted
by
Gus
on Stack Overflow
See other posts from Stack Overflow
or by Gus
Published on 2013-11-09T03:52:04Z
Indexed on
2013/11/09
3:52 UTC
Read the original article
Hit count: 126
I'm building a program that will sum digits in a given list in a recursive way. Say, if the source list has 10 elements, the second list will have 9, the third 8 and so on until the last list that will have only one element. This is done by adding the first element to the second, then the second to the third and so on. I'm stuck without feedback from the shell. It halts without throwing any errors, then in a couple of seconds the fan is spinning like crazy.
I've read quite a few posts here and changed my approach, but I'm not sure that what have so far can produce the results I'm looking for. Thanks in advance:
#---------------------------------------------------
#functions
#---------------------------------------------------
#sum up pairs in a list
def reduce(inputList):
i = 0
while (i < len(inputList)):
#ref to current and next item
j = i + 1
#don't go for the last item
if j != len(inputList):
#new number eq current + next number
newNumber = inputList[i] + inputList[j]
if newNumber >= 10:
#reduce newNumber to single digit
newNumber = sum(map(int, str(newNumber)))
#collect into temp list
outputList.append(newNumber)
i = i + 1
return outputList;
#---------------------------------------------------
#program starts here
#---------------------------------------------------
outputList = []
sourceList = [7, 3, 1, 2, 1, 4, 6]
counter = len(sourceList)
dict = {}
dict[0] = sourceList
print '-------------'
print 'Level 0:', dict[0]
for i in range(counter):
j = i + 1
if j != counter:
baseList = dict.get(i)
#check function to understand what it does
newList = reduce(baseList)
#new key and value from previous/transformed value
dict[j] = newList
print 'Level %d: %s' % (j, dict[j])
© Stack Overflow or respective owner