[Tutor] Occurrence of number 2 in a range from 1 to 100

Mark Lawrence breamoreboy at yahoo.co.uk
Sun Dec 1 18:53:40 CET 2013


On 01/12/2013 17:40, eryksun wrote:
> On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:
>>> I mean occurrence of 2 from numbers 1 to 100.  The number could be the
>>> first digit or second digit in a two digit number..for e.g. In number 21 it
>>> appears as first digit. For number 92 it appears as second digit
>>
>> The most efficient way is to use a bit of reasoning:
>>
>> 2, 12, 20 through 29, then 32, 42, 52 etc.
>
>      >>> [n for n in range(100) if n % 10 == 2 or n // 10 == 2]
>      [2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
>       32, 42, 52, 62, 72, 82, 92]
>
> Floor division (//) and modulo (%) are explained here:
>
> http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations
>

I wish people would use Python 3 references.  I believe it would lead to 
a greater take up of, IMHO, a superior product than Python 2.

-- 
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence



More information about the Tutor mailing list