Home > Mobile >  Program that reads strings typed by user until nothing entered then prints strings in reverse order
Program that reads strings typed by user until nothing entered then prints strings in reverse order

Time:04-26

I am trying to write a program that allows a user to continue to type out strings until an empty string is entered. Then the program sorts through the strings and prints the string in depending order ( lexicographically ).

The string output should look something like this.

enter a string: the tree is nice and brown
output: tree the nice is brown and 

I have tried to implement this code for myself however I have ran into a problem where it prints the code multiple times. see bellow code.

Enter string: the tree is nice and brown
Output:  tree Output:  the Output:  nice Output:  is Output:  brown Output:  and Enter string: 

how can I fix my code to remove the Output: that continues to be printed after each word in the string. And also make the final enter new string print on a new line. See bellow my final code.

s=input("Enter string: ")

while s!="":
    a=s.lower()
    b=a.split()
    b.sort(reverse=True)
    for i in b:
        answer=""
        answer =i
        print("Output: ", answer, end=" ")
    s=input("Enter string: ")

CodePudding user response:

while s := input('Enter string: '):
    a=s.lower()
    b=a.split()
    b.sort(reverse=True)
    output = ("OUTPUT: \n"   " ".join(b)
    print(output)

CodePudding user response:

You could break this down to just two lines. Not necessarily very instructive but just for fun:

while s := input('Enter string: '):
    print('Output:\n' ' '.join(sorted(s.lower().split(), reverse=True)))

CodePudding user response:

You should probably collect all data first and the perform the operations you want on said data.

Left some comments on your code:

s=input("Enter string: ")

while s!="":
    a=s.lower()
    b=a.split()
    b.sort(reverse=True)
    for i in b:               #Every time you input something new you also enter this for-loop
        answer=""             #This resets the variable every for-loop
        answer =i             #This tries to concatenate a string i to the variable answer but since you reset the variable every loop you will never get anything else than i here
        print("Output: ", answer, end=" ")  #Does this run?
    s=input("Enter string: ")

"Correct" code:

s=input("Enter string: ")
input_words=[s]
while s!="":
    s=input("Enter string: ")
    input_words.append(s)

# All the input data is now gathered into a single variable "input_words" that you can manipulate as you want.
wordlist=[]
for words in input_words:
    a=words.lower()
    b=a.split()
    for i in b:
        wordlist.append(i)

# After splitting and making all strings lowercase sort the new list.
wordlist.sort(reverse=True)

# Concatenate the list into a new string
answer=""
for i in wordlist:
    answer =" " i

#Print
print("Output:" answer "\n")
  • Related