osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


On 12 September 2017 at 16:03, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
> Chris Angelico wrote:
>> Rick Johnson wrote:
>> > Ruby:
>> >     farray = [1.5, 1.9, 2.0, 1.0]
>> >     uniqueIntegers = farray.map{|f| f.to_i()}.uniq.length
>> >
>> > Python:
>> >     flist = [1.5, 1.9, 2.0, 1.0]
>> >     uniqueIntegers = len(set(map(lambda f:int(f), flist)))
>>
>> Python:
>>
>> floats = [1.5, 1.9, 2.0, 1.0]
>> unique_integers = len(set(int(f) for f in floats))
>>
>> or:
>>
>> unique_integers = len(set(map(int, floats))
>>
>> If you're going to use Python, at least use it right.
>
> Okay, you've replaced my map function with an implicit list
> comprehension (aka: generator expression)... so how is
> either more "right" than the other? What is your
> justification that your example is "right", and mine is not?
>
> (1) Is is a speed issue? Then prove it.
>
> (2) Is it a readability issue? If so, then that's an opinion
> _you_ get to have.
>
> (3) Is a matter of "python purity"?  If so, then map should be
> removed from the language. And don't forget to remove reduce
> and filter while you're at it. And then, you may want to
> grab a shield, because the functional fanboys will be all
> over you like white on rice!
>
> (4) Something else...?

Ignoring stylistic choices (variable naming, map vs generator) then
for me the key distinction here is "lambda f: int(f)" vs just "int".
Python's callables (of which the integer constructor int is one) are
first class objects, so you should just pass them directly. Creating
an anonymous function using lambda that just calls int is slower,
harder to read, and less natural. The lambda is a direct translation
of the Ruby "|f| f.to_i()" - I don't know if Ruby lacks a built in
"convert to integer" function - maybe it does because it takes the
"everything is an object" philosophy much further than Python does,
but that's where "this code was translated from another language"
shows.

Using map vs comprehensions is mostly a stylistic choice. Python
programmers will typically choose a comprehension, so that style looks
more idiomatic, but the map is not wrong. I haven't tested which is
faster - I can't imagine it would make much practical difference in a
real program. Readability is certainly a personal choice - but writing
code that looks natural to other users of the language is an element
of readability (not the only one, but it is one).

Paul