Jacob Jacob - 2 months ago 8
Python Question

How to fix python program that appears to be doing an extra loop?

A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... if not I can try to explain better. Perhaps the code will help)

def getInput(emptyList):
inputString = input("Please enter a sentence:\n").strip().upper()
functionList = [x for x in inputString]
emptyList.extend(functionList)
return 0

def sortList(listA,listB):
listA.sort()
currentElement = listA[0]
compareTo = listA[0]
elementsCounted = 0
i = 0
listB.append([])
while elementsCounted < len(listA):
while currentElement == compareTo:
listB[i].append(currentElement)
elementsCounted += 1
print(listB)
if elementsCounted < len(listA):
currentElement = listA[elementsCounted]
else:
break
if currentElement != compareTo:
i += 1
listB.append([])
compareTo = listA[i]

return 0

def main():
myList = list()
sortedList = list()
getInput(myList)
sortList(myList,sortedList)
print(sortedList)

main()


If the user enters
qwerty
, the program returns
[['E'], ['Q'], ['R'], ['T'], ['W'], ['Y']]
which is correct but if the user enters
qwwerrty
the program returns
[['E'], ['Q'], ['R', 'R'], [], ['T'], ['W', 'W'], [], ['Y']]
. Note the extra empty list after each "double" character. It appears that the loop is making one extra iteration or that the
if
statement before
listB.append([])
isn't written properly.

I can't seem to figure it out more than this. Thank you in advance for your help.

NOTE:
elementsCounted
should be a cumulative tally of each element that has been processed from listA.
i
is the index of the current element in listB. For example, if
['A','A','B']
was listA and the program is processing the second A, then it is the second element being counted but
i
is still 0 because it belongs in listB[0].
currentElement
is the one currently being processed and it is being compared to the first element that was processed as that "i". For the
['A','A','B'] example, when processing the second A, it is being compared to the first A to see if
i
should be incremented. In the next loop, it is comparing 'B' to the first 'A' and thus will increase
i` by one since 'B' belongs in the next sub-list.

Answer

Your mistake lies in this part:

if currentElement != compareTo:
    ...
    compareTo = listA[i]

It should be:

if currentElement != compareTo:
    ...
    compareTo = listA[elementsCounted]

It's an overly complex function for such a simple task.