on writing a number as 2^s * q, where q is odd

Alan Bawden alan at csail.mit.edu
Thu Nov 30 01:27:57 EST 2023


jak <nospam at please.ty> writes:

   Alan Bawden ha scritto:
   > Julieta Shem <jshem at yaxenu.org> writes:
   >
   >     How would you write this procedure?
   >     def powers_of_2_in(n):
   >         ...
   >
   > def powers_of_2_in(n):
   >      return (n ^ (n - 1)).bit_count() - 1
   >

   Great solution, unfortunately the return value is not a tuple as in the
   OP version. Maybe in this way?

   def powers_of_2_inB(n):
       bc = (n ^ (n - 1)).bit_count() - 1
       return bc, int(n / (1 << bc))

Good point.  I overlooked that.  I should have written:

def powers_of_2_in(n):
    bc = (n ^ (n - 1)).bit_count() - 1
    return bc, n >> bc


More information about the Python-list mailing list