[Tutor] A bit long, but would appreciate anyone's help, if time permits!

Blake Winton bwinton at latte.ca
Fri Jul 23 18:16:19 CEST 2004


Hee-Seng Kye wrote:
> [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, 
> 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]]     #r
> 
> How would I find the smallest values of a list r[0], take only those 
> values (r[0][3] and r[0][5]) for further comparison (r[1][3] and 
> r[1][5]), and finally print a p3?

Well, what do you have so far?

Here, I'll help you out a little.  So you want to find the smallest 
values of a list, huh?  Well, this is one way to do it.

 >>> def findSmallestValues( r ):
...   # We'll need somewhere to store the indices of the smallest values.
...   indices = []
...   for index in range(len(r)):
...     if len(indices) == 0 or r[index] < r[ indices[0] ]:
...       indices = [index]
...     elif r[index] == r[ indices[0] ]:
...       indices.append( index )
...   return indices
...
 >>> findSmallestValues([10, 11, 10, 9, 11, 9])
[3, 5]
 >>> r = [10, 11, 10, 9, 11, 9]
 >>> findSmallestValues(r)
[3, 5]
 >>> r[3], r[5]
(9, 9)
 >>>

Or, I think you can make that shorter (but much less efficient) by using 
list comprehensions, and the reduce function.

 >>> def findSmallestNumber(r):
...   return [i for i in range(len(r)) if r[i] == reduce( min, r ) ]
...
 >>> findSmallestNumber(r)
[3, 5]

It would be a little more efficient like this.

 >>> def findSmallestNumber(r):
...   s = reduce( min, r )
...   return [i for i in range(len(r)) if r[i] == s ]
...
 >>> findSmallestNumber(r)
[3, 5]

(Uh, I ran into problems trying to time the various versions of the
  functions, so I'll let someone else do that part of it.)

Later,
Blake.



More information about the Tutor mailing list