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

Aica Palce jicpalce at gmail.com
Mon Jul 4 02:36:00 UTC 2011


Good day!

I am new to this course, but I read the past two Lessons. I use Ubuntu 11.04
with Python 2.7.1.

Here are my answers:

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

*words = (raw_input("Enter string: ").split())

print "Number of words:", len(words) *

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

*The last element of the list/string.*



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

*The  Python Inventor.*



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

*numbers = ["one", "two", "three", "four", "five"]

for i in numbers:
    print i*


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

for i in vals:
    a = ""
    for j in range(0, i):
        a = a + "*"
    print a *


More information about the Courses mailing list