problem: reducing comparison

Xah Lee xah at xahlee.org
Tue Feb 15 07:59:30 EST 2005


my Python coding is not experienced. In this case, is
ps.pop("%d,%d"%(j[1],k[1]),0) out of ordinary?

if i have long paragraphs of documentation for a function, do i still
just attach it below the fun def?

 Xah

Xah Lee wrote:
> here are the answers:
>
> ©Python code.
> ©
> ©def reduce(pairings, pair):
> ©    ps=pairings.copy(); j=pair;
> ©    ps.pop("%d,%d"%(j[0],j[1]),0)
> ©    for k in pairings.itervalues():
> ©        if (k[0]==j[0]):
> ©            if (j[1] < k[1]):
> ©                ps.pop("%d,%d"%(j[1],k[1]),0)
> ©            else:
> ©                ps.pop("%d,%d"%(k[1],j[1]),0)
> ©        if (k[1]==j[0]):
> ©            if (k[0] < j[1]):
> ©                ps.pop("%d,%d"%(k[0],j[1]),0)
> ©            else:
> ©                ps.pop("%d,%d"%(j[1],k[0]),0)
> ©    return ps
> ©
>
> In imperative languages such as Perl and Python and Java, in general
it
> is not safe to delete elements when looping thru a list-like entity.
> (it screws up the iteration) One must make a copy first, and work
with
> the copy.
>
> Note also that in Python there's already a function called reduce.
(it
> is equivalent to Mathematica's Fold.) In Python, looks like user can
> over-ride default functions.
>
> This post is archived at
> http://xahlee.org/perl-python/pairing_reduce.html
> Possible errata or addenda will appear there.
> 
>  Xah
>  xah at xahlee.org
>  http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list