This is very simple question

Peter Abel PeterAbel at gmx.net
Thu Apr 22 12:14:04 EDT 2004


claird at lairds.com (Cameron Laird) wrote in message 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.

I'm not quite sure, if I understood, what you mean.
One-liners ... OK.
Readable ??? Mmmhm ??
i2b=lambda num,s=[],i=1:num and i2b(num>>1,(num &1) and [(num &1)*i]+s
or s,i<<1) or s

>>> i2b(13)
[8, 4, 1]
>>> i2b(15)
[8, 4, 2, 1]

Let's test it in general:
>>> sum=lambda l:reduce(lambda x,y:x+y,l,0)
>>> sum([8, 4, 2, 1])
15
>>> for i in range(1,100000):
... 	if sum(i2b(i))!=i:
... 		print 'i=%d: sum(i2b(i))=%d' % (i,sum(i2b(i)))
... 		break
... else:
... 	print 'OK'
... 	
OK
>>>

Regards
Peter



More information about the Python-list mailing list