This is very simple question

Nicolas Lehuen nicolas.lehuen at thecrmcompany.com
Thu Apr 22 06:39:50 EDT 2004


"Cameron Laird" <claird at lairds.com> a écrit dans le message de news:108dbd1aftmkc48 at corp.supernews.com...
> In article <mailman.840.1082563771.20120.python-list at python.org>,
> Brian Quinlan  <brian at sweetapp.com> 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.
> >
> >If we told you it wouldn't be fair to the other students in your class :-)
> .
> .
> .
> I'm surprised only one of the responses I've seen so far has 
> objected to what sure seems like an inappropriate response to
> classwork.  I'm astonished that no one is reading this question
> as I do.  I leave as an exercise for readers this generalization
> of what *I* think is going on:
> 
>   def positional_addends(positive_integer, base = 2):
>       result = []
>       current = 1
>       while positive_integer:
>   remainder = positive_integer % (base * current)
>           if remainder:
>               result.append(remainder)
>               positive_integer -= remainder
>           current *= base
>       result.reverse()
>       return result
>   
>   print positional_addends(13)
>   print positional_addends(5)
>   print positional_addends(7)
>   print positional_addends(15)
>   print positional_addends(78904, 10)
> 
> The real exercise is to convert this to a readable one-liner,
> at least for the binary case.
> -- 
> 
> Cameron Laird <claird at phaseit.net>
> Business:  http://www.Phaseit.net

You can also use divmod :

def decompose(i,base=2):
    result=[]
    factor=1
    while i>0:
        i,r=divmod(i,base)
        if r:
            result.append(r*factor) # or result.extend([factor]*r), depending on style
        factor*=base
    return result.reverse() # if you really want it reversed

Regards,
Nicolas



More information about the Python-list mailing list