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

Knut Jackowski doxanthropos at googlemail.com
Fri Jul 8 13:38:00 UTC 2011


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

stc = raw_input("Please insert words to count: ")
if len(stc) > 0 :
	count = 1
	for c in stc :
		if c == " " :
			count += 1
	print count
else :
	print "You forgot to type something."

> 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 negative index gets subtracted from the full length. So when you call [-1:] you get only the last part of the string or the list, with [-2:] the last two parts and so on.
I wasn't able to guess, but understood, when I did some testing.

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

Guido van Rossum is the inventor of python and a huge fan of the Monty
Pythons, not so much of snakes. Taking him as an example gives him
credit while learning the language he created and he has a name with
three parts, as was needed.

> 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', 'Six', 'Seven',
'Eight', 'Nine', 'Ten']
countend = raw_input("Please insert a number from one to ten: ")
cend = int(countend)
if 0 < cend <= 10 :
	for i in range(0, cend) :
		print numbers[i]
else :
	print "I can't count to", cend

> 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:
> 
> **
> ****
> ********
> ****************
> ******************
> *****************
> **************
> *********
> *******
> ****
> **
> *

val = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
for i in range(0, len(val)) :
	stars = ""
	for i in range(0, val[i]) :
		stars += "*"
	print stars




More information about the Courses mailing list