[Tutor] transforming an integer to a list of integers

Andre Engels andreengels at gmail.com
Tue Feb 3 16:25:44 CET 2009


On Tue, Feb 3, 2009 at 4:24 PM, Andre Engels <andreengels at gmail.com> wrote:
> On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy <hgleroy at gmail.com> wrote:
>> Hi,
>>
>> recently I learned about Project Euler (http://projecteuler.net/) and now
>> I'm trying to work me through. At the moment I'm thinking about
>> http://projecteuler.net/index.php?section=problems&id=8
>>
>> One step for my solution should be transforming this big integer to a list
>> of integers. I did:
>>
>> import math
>>
>> bignr = 12345
>> bignrs =[]
>>
>> for i in xrange(math.ceil(math.log10(bignr)):
>>   rem = bignr % 10
>>   bignrs.append(rem)
>>   bignr /= 10
>>
>> However this "feels" a bit complicated, Do you know a better (more simple,
>> nice etc.) way to do this?
>
> One way could be to represent the number as a string; a string can be
> treated as a list, so you get what you want quite quickly that way:
>
> bignr = 12345
> bignrs =[]
>
> for char in str(bignr):
>    bignrs.append(int(char))

Or as a one-liner:

bignr = 12345
bignrs =[int(char) for char in str(bignr)]


-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list