This is very simple question

wes weston wweston at att.net
Wed Apr 21 13:31:21 EDT 2004


Eric wrote:
> I would want to obtain a list of factors (multiples of 2) given a
> prime number in python.
> 
> For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1]
> 
> I would appreciate a fuction which would do this.
> 
> Eric

Eric,
    To be less illustrative and somewhat more efficient.
wes

import math

def ListOfPowersLessThan(n):
     list = []
     i    = 0
     while True:
         x = int(math.pow(2,i))
         if x <= n:
             list.append(x)
         else:
             break
         i += 1
     return list

TEST   = [13,5,7,15,17,33]
powers = ListOfPowersLessThan( max(TEST) )
powers.reverse()

for x in TEST:
     sum = 0
     list = []
     for s in powers:
         if (sum + s) <= x:
             sum += s
             list.append(s)
         if sum >= x:
             break
     print x,list

 >>>
13 [8, 4, 1]
5 [4, 1]
7 [4, 2, 1]
15 [8, 4, 2, 1]
17 [16, 1]
33 [32, 1]
 >>>




More information about the Python-list mailing list