[Tutor] Calculate hours

Mitya Sirenef msirenef at lightbird.net
Wed Jan 23 04:08:58 CET 2013


On 01/22/2013 09:52 PM, anthonym wrote:
> Hello All,
 >
 > I originally wrote this program to calculate and print the employee
 > with the most hours worked in a week. I would now like to change this
 > to calculate and print the hours for all 8 employees in ascending
 > order.
 >
 > The employees are named employee 0 - 8
 >
 > Any ideas?
 >
 > Thanks,
 > Tony
 >
 > Code below:
 >
 >
 >
 > # Create table of hours worked
 >
 > matrix = [
 > [2, 4, 3, 4, 5, 8, 8],
 > [7, 3, 4, 3, 3, 4, 4],
 > [3, 3, 4, 3, 3, 2, 2],
 > [9, 3, 4, 7, 3, 4, 1],
 > [3, 5, 4, 3, 6, 3, 8],
 > [3, 4, 4, 6, 3, 4, 4],
 > [3, 7, 4, 8, 3, 8, 4],
 > [6, 3, 5, 9, 2, 7, 9]]
 >
 > maxRow = sum(matrix[0]) # Get sum of the first row in maxRow
 > indexOfMaxRow = 0
 >
 > for row in range(1, len(matrix)):
 > if sum(matrix[row]) > maxRow:
 > maxRow = sum(matrix[row])
 > indexOfMaxRow = row
 >
 > print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours")


There is an issue with this program: it omits the first row.

It's better to use enumerate, e.g.:

for n, row in enumerate(matrix): ...


To make the change you need, use list comprehension to make sums of all
rows, sort it (using list sort method); iterate over it using
enumerate() and print out "employee N, sum of hours:"


HTH, -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Idleness is the mother of psychology.  Friedrich Nietzsche



More information about the Tutor mailing list