Python Forum
Someone explains to me how this works please - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Someone explains to me how this works please (/thread-3332.html)



Someone explains to me how this works please - franklee809 - May-16-2017

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



RE: Someone explains to me how this works please - Ofnuts - May-16-2017

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....


RE: Someone explains to me how this works please - franklee809 - Jun-20-2017

(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