[Tutor] Algorithm
Alan Gauld
alan.gauld at btinternet.com
Mon Dec 28 12:46:25 EST 2015
On 28/12/15 12:34, cicy felix wrote:
> Create a function get_algorithm_result to implement the algorithm below
> Get a list of numbers L1, L2, L3....LN as argument
> Assume L1 is the largest, Largest = L1
> Take next number Li from the list and do the following
> If Largest is less than Li
> Largest = Li
> If Li is last number from the list then
> return Largest and come out
> Else repeat same process starting from step 3
OK, That seems fairly clear. Although it does
seem to imply a while loop which is maybe not
the best option here.(see below)
> This what I've come up with:
Thanks for showing us the code, but there are several
issues with it
> def get_algorithm_result( numlist ):
> largest = numlist[0]
> i = 1
> while ( i < len(numlist) ):
> if ( largest < numlist[i]):
> largest = numlist[i]
> i = i + 1
Notice that you only increase i if the if test is true.
If largest >= numlist[i] then your loop will simply go
round and round forever. The normal way in Python to
process all elements in a list is to use a for loop.
In your case that would look an awful lot simpler.
Try it.
> return largest
> numlist1 = [1,2,3,4,5]
> numlist2 = [10,20,30,40,50]
I've no idea what you think these numbers are for,
they are not mentioned in your problem description.
> largest = get_algorithm_result(numlist1)
This should(if it worked properly) return 5
> print largest
So this (should) always print 5
> largest = get_algorithm_result(numlist2)
and his should(if it worked properly) return 50
> print largest
and this should print 50.
Two largests - isn't that a bit confusing?
Especially since neither number may be in your
original list of numbers.
> And I keep getting this error :
> . test_maximum_number_two
> Failure in line 15, in test_maximum_number_two self.assertEqual(result,
> "zoo", msg="Incorrect number") AssertionError: Incorrect number
> Using unittest
Since you don't show us any code involving test_maximum_number_two
or even maximum_number_two() we can't help you there.
But it does seem to me that you are over complicating things.
Even if you stick with a while loop, just follow the algorithm
you were given and it should work.
One final point. You are printing the results but your problem states
that you should write a function that *returns* the largest. Not one
that prints it.
In general this is what functions should always do - return
values not print them. It makes them much more reusable and flexible.
You can always print the output later using:
print get_algorithm_result(numlist)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list