LoginSignup
0
1

More than 5 years have passed since last update.

PythonのlambdaとreduceのList処理

Last updated at Posted at 2018-05-16

PythonであるByte中「1」のBit数を計算する

1. Lambda

get_bits = lambda value: get_bits(value>>1) +  (0x01&(value))  if  value.bit_length() > 0 else 0
get_bits(0x15)
get_bits = lambda bits, value:  get_bits(bits -1, value) +  (0x01&(value >> bits-1))  if bits > 0 else 0
get_bits(8, 0x70)

2.Reduce

import functools
f = lambda value: functools.reduce(lambda x, y: x + y, [ 0x01&value>>i for i in range(value.bit_length())])
OR
def f(value):
    return functools.reduce(lambda x, y: x + y, [ 0x01&value>>i for i in range(value.bit_length())])
f(0x12)
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1