Function to determine list max without itertools
Chris Angelico
rosuav at gmail.com
Thu Apr 18 04:17:09 EDT 2019
On Thu, Apr 18, 2019 at 5:41 PM Sayth Renshaw <flebber.crue at gmail.com> wrote:
>
> Thank you for the advice everyone.
>
> >
> > The first thing to try is find every place where you update myMax, and
>
> This was actually where I was going wrong. I was setting max but then overwriting it with item. Then kept checking item only to return myMax.
>
> I went looking for other solutions as I thought I must be well off the path in the shrubs but I was actually close.
>
> This is how I ended up. There may be better solutions but this works.
>
> def maximum(listarg):
> items = list(listarg)
> myMax = items[0]
> for item in items:
> for i in items[items.index(item)+1:len(items)]:
> if myMax < i:
> myMax = i
> else:
> pass
>
> return myMax
>
>
> if __name__ == "__main__":
> print(maximum([4,3,6,2,1,4]))
>
This is where I would strongly recommend printing lots of stuff out,
to explore what the algorithm is doing at each point. See if you can
figure out when myMax is being updated.
(Also: items.index(item) will potentially give the wrong result if you
have duplicates.)
ChrisA
More information about the Python-list
mailing list