Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's analyze your problem step-by-step.</p> <p>You need to:</p> <ol> <li>Retrieve all the words from a file</li> <li>Iterate over all the words</li> <li>Increment the counter <code>N</code> every time you find a word of length <code>N</code></li> <li>Output the result</li> </ol> <p>You already did the step 1:</p> <pre><code>def many(fname): infile = open(fname,'r') text = infile.read() infile.close() L = text.split() </code></pre> <p>Then you (try to) sort the words, but it is not useful. You would sort them alphanumerically, so it is not useful for your task.</p> <p>Instead, let's define a <a href="http://docs.python.org/library/stdtypes.html#typesmapping" rel="nofollow">Python dictionary</a> to hold the count of words</p> <pre><code> lengths = dict() </code></pre> <p>@sukhbir correctly suggested in a comment to use the Counter class, and I encourage you to go and search for it, but I'll stick to traditional dictionaries in this example as i find it important to familiarize with the basics of the language before exploring the library.</p> <p>Let's go on with step 2:</p> <pre><code> for word in L: length = len(word) </code></pre> <p>For each word in the list, we assign to the variable <code>length</code> the length of the current word. Let's check if the counter already has a slot for our length:</p> <pre><code> if length not in lengths: lengths[length] = 0 </code></pre> <p>If no word of length <code>length</code> was encountered, we allocate that slot and we set that to zero. We can finally execute step 3:</p> <pre><code> lengths[length] += 1 </code></pre> <p>Finally, we incremented the counter of words with the current length of 1 unit.</p> <p>At the end of the function, you'll find that <code>lengths</code> will contain a map of <strong>word length -> number of words of that length</strong>. Let's verify that by printing its contents (step 4):</p> <pre><code> for length, counter in lengths.items(): print "Words of length %d: %d" % (length, counter) </code></pre> <p>If you copy and paste the code I wrote (respecting the indentation!!) you will get the answers you need.</p> <p>I strongly suggest you to go through the <a href="http://docs.python.org/tutorial/" rel="nofollow">Python tutorial</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload