[Courses] [python] Lesson 3: Fun with Strings and Lists

GcX linuxchix.gcx at gishpuppy.com
Sun Jul 3 03:06:52 UTC 2011


Instructor Peck,

Forgive the spam. It was a mistake.

Hope you had a fine week.

Here is my homework.

1. How would you count the number of words in a single string?
  Assume words are separated by spaces ... don't worry about
  things like newlines, commas or hyphens.

Use split and len
e.g.:

numbers = 'one, two, three, four'
count= numbers.splt(',')
len(count)

2. What does an index of [-1], or another negative number mean in a
  list or string? Take a guess, then try it and see if you were right.

That you are going from the end of the list/string instead of the start.
e.g.,

list = [1, 2, 3, 4, 5, 6]
# so x[1] = 2
# and x[-1] = 5 (?)

I was wrong. x[-1] is the last ting in a list/string. in this case x[-1] = 6
and x[-2] = 5 etc.

3. Who is Guido van Rossum and why am I using him as an example?

He is/was a former/current boyfriend/husband and/or the creator of Python.
:-)

4. Rewrite the exercise from lesson 2, the one where
  you printed "one", "two", "three", "four", "five",
  using a list instead of a series of if-elif.
  (A few people already posted solutions that worked that way
  in their lesson 2 answers. If you already did this for lesson 2, no
  need to do it again. If you read other people's, it's still worth
  writing it yourself now without going back and looking.)

I used a list then. Then I looked at the other students answers. Wow (I said
to myself), why could I not think of that?

5. This one's a little harder, but give it a try if you have time.
  Plot a histogram graph from a list of numbers, with each number in
  the list on its own line.

  For instance, if you start with numbers like this:
vals = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
  you might plot something like this:

**
****
********
****************
******************
*****************
**************
*********
*******
****
**
*
   where the first line has no stars, the second has two, then 4, etc.
   Hint: you'll need two loops, one inside the other.

vals = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
count = 0
for x in vals:
    print ' * ' * vals[count]
    count += 1

After number 5, my head hurts.

Take care, till next week.

-- 
Always Faitful,

GcX


More information about the Courses mailing list