Julieta Shem ha scritto:
Alan Bawden <a...@csail.mit.edu> writes:
jak <nos...@please.ty> writes:
Alan Bawden ha scritto:
> Julieta Shem <js...@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
That's pretty fancy and likely the fastest.
I was pretty happy with a recursive version. If I'm not mistaken,
nobody has offered a recursive version so far. It's my favorite
actually because it seems to be the clearest one.
--8<---------------cut here---------------start------------->8---
def powers_of_2_in(n):
if remainder(n, 2) != 0:
return 0, n
else:
s, r = powers_of_2_in(n // 2)
return 1 + s, r
--8<---------------cut here---------------end--------------->8---
for n = 0 your function get stack overflow
--
https://mail.python.org/mailman/listinfo/python-list