473,378 Members | 1,380 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

max(), sum(), next()

Empty Python lists [] don't know the type of the items it will
contain, so this sounds strange:
>>sum([])
0

Because that [] may be an empty sequence of someobject:
>>sum(s for s in ["a", "b"] if len(s) 2)
0

In a statically typed language in that situation you may answer the
initializer value of the type of the items of the list, as I do in the
sum() in D.

This sounds like a more correct/clean thing to do:
>>max([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

So it may be better to make the sum([]) too raise a ValueError, in
Python 3/3.1 (if this isn't already true). On the other hand often
enough I have code like this:
>>max(fun(x) for x in iterable if predicate(x))
This may raise the ValueError both if iterable is empty of if the
predicate on its items is always false, so instead of catching
exceptions, that I try to avoid, I usually end with a normal loop,
that's readable and fast:

max_value = smallvalue
for x in iterable:
if predicate(x):
max_value = max(max_value, fun(x))

Where running speed matters, I may even replace that max(max_value,
fun(x)) with a more normal if/else.

A possible alternative is to add a default to max(), like the next()
built-in of Python 2.6:
>>max((fun(x) for x in iterable if predicate(x)), default=smallvalue)
This returns smallvalue if there are no items to compute the max of.

Bye,
bearophile
Sep 3 '08
54 8269

Quoting Mensanator <me********@aol.com>:
Actualy, I already get the behaviour I want. sum([1,None])
throws an exception. I don't see why sum([]) doesn't throw
an exception also
If you take a "start value" and add to it every element of a list, shouldthe
process fail if the list is empty? If you don't add anything to the startvalue,
you should get back the start value.

Python's sum is defined as sum(sequence, start=0). If sum were to throwan
exception with sum([]), it should also throw it with sum([], start=0), wich
makes no sense.

--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
Sep 10 '08 #51
On Sep 7, 3:38*pm, Luis Zarrabeitia <ky...@uh.cuwrote:
Quoting Mensanator <mensana...@aol.com>:
Actualy, I already get the behaviour I want. sum([1,None])
throws an exception. I don't see why sum([]) doesn't throw
an exception also

If you take a "start value" and add to it every element of a list, shouldthe
process fail if the list is empty?
No.
If you don't add anything to the start value,
you should get back the start value.
Agree.
>
Python's sum is defined as sum(sequence, start=0).
That's the issue.
If sum were to throw an
exception with sum([]), it should also throw it with sum([], start=0), wich
makes no sense.
Given that definition, yes. But is the definition correct
in ALL cases? Are there situations where the sum of an empty
list should NOT be 0? Of course there are.

Can sum() handle those cases? No, it can't, I have to write
my own definition if I want that behaviour. There's no reason
why sum([]) and sum([],0) have to mean the same thing at the
exclusion of a perfectly valid alternative definition.

But that's the way it is, so I have to live with it.

But that's not conceeding that I'm wrong.
>
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UHhttp://profesores.matcom.uh.cu/~kyrie
Sep 10 '08 #52


Mensanator wrote:
On Sep 10, 5:36 pm, Terry Reedy <tjre...@udel.eduwrote:
>Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be
the most common use of reduce. Sum(s,start) replaces the much less
common reduce(lambda x,y: x+y, s, start).

Reduce(S, s), where S = sum function, raises an exception on empty s.
So use that and you are no worse off than before.
What am I doing wrong?
>>>S = sum
[snip]

Taking me too literally out of context. I meant the sum_of_2 function
already given in the example above, as you eventually tried.

def S(x,y): return x+y

Sorry for the confusion.

....
>>>reduce(lambda x,y:x+y,s)
6
>>>s=[]
reduce(lambda x,y:x+y,s)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
reduce(lambda x,y:x+y,s)
TypeError: reduce() of empty sequence with no initial value
These two are exactly what I meant.
This is supposed to happen. But doesn't reduce(S,s) work
when s isn't empty?
It did. You got 6 above. The built-in 'sum' takes an iterable, not a
pair of numbers.

tjr

Sep 11 '08 #53
Tino Wildenhain wrote:
Hi,

Luis Zarrabeitia wrote:
>Quoting Laszlo Nagy <ga*****@shopzeus.com>:
...
>Even better:

help(sum) shows

===
sum(...)
sum(sequence, start=0) -value
Returns the sum of a sequence of numbers (NOT strings) plus
the value
of parameter 'start'. When the sequence is empty, returns start.
===

so the fact that sum([]) returns zero is just because the start value
is zero...
sum([],object()) would return an object().

BTW, the original code:
>>>>sum(s for s in ["a", "b"] if len(s) 2)

wouldn't work anyway... it seems that sum doesn't like to sum strings:
>>>>sum(['a','b'],'')

<type 'exceptions.TypeError'>: sum() can't sum strings [use
''.join(seq) instead]

Yes which is a bit bad anyway. I don't think hard wiring it is such a
nice idea. You know, walks like a duck, smells like a duck...
If it makes sense to handle things differently for performance, then
please have it doing it silently, e.g. when it detects strings just
use join() internally.

Cheers
Tino
+1

''.join is horrible. And it adds insult to injury that S.join(S.split(T)) != T
as a rule. The interpreter has no business to patronize us into this shamefully
contorted neighborhood while it understands what we want.

Cheers, BB

Sep 13 '08 #54
I wrote:
Tino Wildenhain wrote:
[...]
>>>>>sum(['a','b'],'')

<type 'exceptions.TypeError'>: sum() can't sum strings [use
''.join(seq) instead]

Yes which is a bit bad anyway. I don't think hard wiring it is such a
nice idea. You know, walks like a duck, smells like a duck...
If it makes sense to handle things differently for performance, then
please have it doing it silently, e.g. when it detects strings just
use join() internally.

Cheers
Tino

+1

''.join is horrible. And it adds insult to injury that
S.join(S.split(T)) != T as a rule. The interpreter has no business to
patronize us into this shamefully contorted neighborhood while it
understands what we want.
What makes ''.join particularly horrible is that we find ourselves forced to use
it not only for concatenating arbitrary-length strings in a list, but also to
convert to a str what's already a sequence of single characters. IOW string
types fail to satisfy a natural expectation for any S of sequence type :

S == type(S)(item for item in S) == type(S)(list(S))

And this, even though strings are sequence types deep-down-ly enough that they
achieve to act as such in far-fetched corner cases like

(lambda *x : x)(*'abc')==('a','b','c')

....and even though strings offer not one but two distinct constructors that play
nicely in back-and-forth conversions with types to which they are much less
closely related, ie.

'1j' == repr(complex('1j') == str(complex('1j'))
1j == complex(repr(1j)) == complex(str(1j))

Not-so-cheerfully-yours, BB

Sep 13 '08 #55

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Stefan Bauer | last post by:
Hi NG, I have problem... I'm currently using UDB v8.1 for Linux. Here is the table "test": ID1 ID2 ID3 VALUE ----------------- 1 0 1 23 1 0 2 9
7
by: turtle | last post by:
I want to find out the max value of a field on a report if the field is not hidden. I have formatting on the report and if the field doesn't meet a certain criteria then it is hidden. I want to...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.