[Tutor] this group and one liners
avi.e.gross at gmail.com
avi.e.gross at gmail.com
Fri Jul 8 17:52:59 EDT 2022
Alan,
I get annoyed at myself when I find I do not apparently understand something
or it makes no sense to me. So I sometimes try to do something about it.
My first thought was to see if I could make a wrapper for max() that allowed
the use of a non-iterable.
My first attempt was to have this function that accepts any number of
arguments and places them in an iterable concept before calling maxim and I
invite criticism or improvements or other approaches.
We know max(1,2,3) fails as it demands an iterable like [1,2,3] so I tried
this:
def maxim(*args): return(max(args))
maxim(1,2,3)
3
maxim([1,2,3])
[1, 2, 3]
Well, clearly this needs work to be more general and forgiving! But it sort
of works on an empty list with a sort of default:
maxim([] or 0)
0
To make this more general would take quite a bit of work. For example, if
you want to make sure max(iterator) works, you may need to check first if
you have a simple object and if that object is a list or set or perhaps
quite a few other things, may need to convert it so it remains intact rather
than a list containing a list which max() returns as the maximum.
As always, I have to suspect that someone has already done this, and more,
and created some function that is a Swiss Army Knife and works on (almost)
anything.
-----Original Message-----
From: Tutor <tutor-bounces+avi.e.gross=gmail.com at python.org> On Behalf Of
Alan Gauld via Tutor
Sent: Friday, July 8, 2022 6:54 AM
To: tutor at python.org
Subject: Re: [Tutor] this group and one liners
On 08/07/2022 02:52, avi.e.gross at gmail.com wrote:
> But oddly although brackets work, an explicit call to list() generates
> an error! Ditto for {number} working and set(number) failing. Is this
> an anomaly with a meaning?
list() and set() require iterables. They won't work with single values:
>>> set(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> set((1,))
{1}
>>> list(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> list([3])
[3]
>>> list((3,))
[3]
>>>
The error you are getting is not from max() its from list()/set()
What is slightly annoying is that, unlike max(), you cannot just pass a
sequence of values:
>>> set(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 argument, got 2
--
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
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list