[BangPypers] if not with comparision statement in python
Dhananjay Nene
dhananjay.nene at gmail.com
Mon Aug 1 13:08:59 CEST 2011
On Mon, Aug 1, 2011 at 4:17 PM, Anand Chitipothu <anandology at gmail.com> wrote:
> 2011/8/1 Dhananjay Nene <dhananjay.nene at gmail.com>:
>> On Sat, Jul 30, 2011 at 2:15 PM, Asif Jamadar <asif.jamadar at rezayat.net> wrote:
>>> What if I have two lists for both minimum and maximum values
>>>
>>> Minimum Maximum
>>> 0 10
>>> 11 20
>>> 21 30
>>> 31 40
>>>
>>>
>>> Now how should I check if actual result is not laying between above ranges
>>>
>>> if not minimum<=actual_result and not maximum>=actual_result:
>>>
>>> Any suggestions?
>>
>> def in_range(number) :
>> return any(map(lambda (x,y) : x <= number <= y,
>> ((0,10),(11,20), (21,30), (31,40))))
>
> How about this?
>
> def in_range(number, min_max_pairs):
> return any(x <= number <=y for x, y in min_max_pairs)
Definitely better
>
> List comprehensions and generation expressions are usually more
> readable and expressive than using map.
Thats probably truer for the python and python trained eyes than any
other (in other words its both subjective and contextual and a bit to
do with syntax). Allow me to illustrate :
If I want to double all elements in a list and then increment them by
one, here's how I would use a map in python
def double(x) : return x * 2
def increment(x) : return x + 1
print map(increment,map(double,range(5)))
and here's how I would do it in scala - notice the last (third) line
and consider its readability (I'm sure a scala non-novice will offer
something even superior)
def double(n: Int) = n * 2
def increment(n: Int) = n + 1
println(0 to 4 map double map increment)
so readability is often a function of what one's eyes are trained ot
read and also the syntactic capabilities in the language
I also find map much more atomic and portable construct to think in -
after all every list comprehension is syntactic sugar around map +
filter, and map/reduce/filter are far more omnipresent than list
comprehensions.
More information about the BangPypers
mailing list