[Tutor] Maths operations on lists

Kalle Svensson kalle@lysator.liu.se
Tue Jun 10 16:52:02 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[valhalla]
> I *think* what I am after is a way of adding the contents of a list
> and then dividing that total to yield an average - but I'm not sure
> (i) whether one can do those operations with lists and if so, how or
> (ii) if not, what the next best thing would be, given that there has
> to be a data structure to catch the number of guesses per game.

Sure you can, it sounds to me like a list is the prefect data
structure for the job here.  Basically, first you loop through the
list, computing the sum for each step:

  sum = 0.0
  for num in guesses:
      sum += num

If you add print statements to the loop body, you'll see what's
happening.

  guesses = [3, 6, 2, 5]
  sum = 0.0
  for num in guesses:
      sum += num
      print "Number:", num
      print "Current sum:", sum

will produce

  Number: 3
  Current sum: 3.0
  Number: 6
  Current sum: 9.0
  Number: 2
  Current sum: 11.0
  Number: 5
  Current sum: 16.0

(Note for the attentive reader: I made the sum a floating point number
instead of an integer.  This will make the code for the division step
more natural, and I avoid having to explain integer division.  Ooops,
shouldn't have said anything.)

Now, we have the sum in the variable 'sum'.  Next, we divide it by the
number of games (which, very conveniently, is also the length of the
list 'guesses') and print it:

  average = sum / len(guesses)
  print "Average:", average

which prints

  Average: 4.0

Now, there are other ways to write this.  For example, the for loop
and temporary variable 'sum' could be replaced by a call to the
built-in function 'filter' or even, in Python 2.3, the function 'sum'.
A nice exercise for the interested reader might be to write a
recursive function to generate the sum of a list of numbers.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE+5kSjdNeA1787sd0RAl2xAJ95rQdg5dlTxNMPsCz1ShveUr0PCQCgwn3U
eZvpKIEEC7OAJeVTt5ZAqqI=
=lTaM
-----END PGP SIGNATURE-----