Homework help

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue Apr 1 13:42:49 EDT 2008


On Tue, 01 Apr 2008 09:11:12 -0700, bobby.connor wrote:

> #  (2 Points) Write a python function howMany(item,lst) which accepts
> an item and a lst of items and returns the number of times item occurs
> in lst. For example, howMany(3,[1,2,3,2,3]) should return 2.

Study the methods on lists.

> # (2 Points) Write a python function upTo(n) which accepts a non-
> negative number n and returns a list of numbers from 0 to n. For
> example, upTo(3) should return the list [0, 1, 2, 3].

Study the built in functions.  I don't know if it is considered cheating
but you can get away with binding an existing one to the new name.

> # (2 Points) Write a python function dotProduct(a,b) which accepts two
> lists of integers a and b that are of equal length and which returns
> the dot product of a and b. I.e., the sum a0 * b0 + ... + an-1 * bn-1
> where n is the length of the lists. For example:
> 
> dotProduct([1,2,3],[4,5,6]) is 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32

Again study the built in functions.  Here the function from the `zip()`
exercise below might be handy.

> # (2 Points) A pair (exp0, exp1) is a combination of expressions that
> are attached together by their joint membership in the pair. For
> example:
> 
>>>> (1+2, 'This')
> (3, 'This')
> 
> A component of a pair can be obtained using an index in brackets as
> with lists (and strings!). For example:
> 
>>>> (33,44)[0]
> 33

And the exercise to solve is!?  Study the built in data types.

> Write a function zip(lst1, lst2) such that zip accepts two equal
> length lists and returns a list of pairs. For example, zip(['a', 'b',
> 'c'], [10, 20, 30]) should evaluate to the list [('a', 10), ('b', 20),
> ('c', 30)].

Hey not even a rebinding necessary.  :-)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list