some problems for an introductory python test

Hope Rouselle hrouselle at jevedi.xotimo
Tue Aug 10 08:46:43 EDT 2021


Chris Angelico <rosuav at gmail.com> writes:

> On Tue, Aug 10, 2021 at 7:25 AM Hope Rouselle <hrouselle at jevedi.xotimo> wrote:
>> I came up with the following question.  Using strings of length 5
>> (always), write a procedure histogram(s) that consumes a string and
>> produces a dictionary whose keys are each substrings (of the string) of
>> length 1 and their corresponding values are the number of times each
>> such substrings appear.  For example, histogram("aaaaa") = {"a": 5}.
>> Students can "loop through" the string by writing out s[0], s[1], s[2],
>> s[3], s[4].
>
> In other words, recreate collections.Counter? Seems decent, but you'll
> need to decide whether you want them to use defaultdict, use
> __missing__, or do it all manually.

Yes, the course introduces very little so there is a lot of recreation
going on.  Hm, I don't know defaultdict and I don't know how to use
__missing__.  The course does introduce dict.get(), though.  If students
use dict.get(), then the procedure could essentially be:
  
def histogram(s):
  d = {}
  d[s[0]] = d.get(s[0], 0) + 1
  d[s[1]] = d.get(s[1], 0) + 1
  d[s[2]] = d.get(s[2], 0) + 1
  d[s[3]] = d.get(s[3], 0) + 1
  d[s[4]] = d.get(s[4], 0) + 1
  return d

>> I think you get the idea.  I hope you can provide me with creativity.  I
>> have been looking at books, but every one I look at they introduce loops
>> very quickly and off they go.  Thank you!
>
> Probably because loops are kinda important? :)

Totally important.  But each course author thinks they know better.
Sometimes a college professor can do very little to help her students.
I am actually fond of functional programming as a first course using a
language with as little syntax as possible.  Python is very nice but
it's not a small language.  It's easy to see courses spending an entire
semester on introducing syntax and this one is no different.  I think
it's more interesting to see all the syntax in a few minutes and spend
the semester on strategies.


More information about the Python-list mailing list