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.
Aucun commentaire:
Enregistrer un commentaire