Python Forum
Someone explains to me how this works please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Someone explains to me how this works please
#1
my question here

Q4.  Ask the user for a sentence and print out a table of words in that sentence. The words should be printed alphabetically with its number of occurrences next to it.  
Note: You should avoid editing the list in a for loop traverses over. If you need to edit a list use the while loop.

#Q4
s = input("Enter a sentence: ")
previous = ""
L = s.split()
L.sort()

for w in L:
   current = w
   if current == previous:
       continue
   else:
       c = L.count(w)
       print(w,c)
   previous = current
Reply
#2
s = input("Enter a sentence: ")
previous = "" # This should really be just before the 'for' loop
L = s.split() # Split the sentence into a list of words
L.sort() # Sort that list. Identical words are now next to each other: ['be', 'be', 'not', 'or', 'to', 'to'] 
 
for w in L:  # Iterate the words in the list
   current = w # Actually this is useless, "w" can be used everywhere "current" is used
   if current == previous: # If this is the same as the previous one, then we already printed the count
       continue
   else:
       c = L.count(w) # First time we see this word: get the count of the occurrences of the word over the whole list
       print(w,c)
   previous = current # remember for which word we have printed the count
Otherwise, add print statements to see the variable contents....
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
(May-16-2017, 08:37 AM)franklee809 Wrote: my question here

Q4.  Ask the user for a sentence and print out a table of words in that sentence. The words should be printed alphabetically with its number of occurrences next to it.  
Note: You should avoid editing the list in a for loop traverses over. If you need to edit a list use the while loop.

#Q4
s = input("Enter a sentence: ")
previous = ""
L = s.split()
L.sort()

for w in L:
   current = w
   if current == previous:
       continue
   else:
       c = L.count(w)
       print(w,c)
   previous = current

Thanks
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020