我想知道从一组数字中可以构建一个数字的次数:
possible_numbers = 1, 2, 4, 8, 16如果我想要23号,我需要
1x 16
0x 8
1x 4
1x 2
1x 1 Python中有没有内置的函数可以做到这一点?
编辑:数字固定为1,2,4,8,16,32,64,128。可以选择多个选项。
由于没有内置函数,我将自己编写代码。
发布于 2012-06-02 21:52:08
假设可能的数字总是2的幂,您基本上希望将数字转换为二进制格式。使用内置的bin function很容易做到这一点
>>> mylist = [int(x) for x in bin(23)[2:]]
>>> print mylist
[1, 0, 1, 1, 1]要获得与您在问题中显示的完全相同的输出:
>>> for i, j in enumerate(mylist):
... print '%ix %i' % (j, 2**(len(mylist)-i-1))
...
1x 16
0x 8
1x 4
1x 2
1x 1发布于 2012-06-02 22:03:02
假设您的数字不限于2的幂,这个解决方案应该是有效的。它肯定不是完美的或高效的,但它是有效的。
#!/usr/bin/env python
import sys
def factors(desired, numbers):
if desired == 0:
return []
elif desired < 0:
return None
for number in sorted(numbers, reverse=True):
f = factors(desired - number, numbers)
if f is not None:
f.append(number)
return f
if __name__ == "__main__":
n = int(sys.argv[1])
possibles = map(int, sys.argv[2].split())
f = factors(n, possibles)
print f
for i in sorted(possibles, reverse=True):
print "{0}x {1}".format(f.count(i), i)下面是一些示例:
$ python test.py 23 "1 2 4 8 16"
[1, 2, 4, 16]
1x 16
0x 8
1x 4
1x 2
1x 1
$ python test.py 23 "1 2 5 8 16"
[2, 5, 16]
1x 16
0x 8
1x 5
1x 2
0x 1
$ python test.py 23 "1 2 3 8 16"
[1, 3, 3, 16]
1x 16
0x 8
2x 3
0x 2
1x 1
$ python test.py 23 "1 2 3 8 17"
[3, 3, 17]
1x 17
0x 8
2x 3
0x 2
0x 1发布于 2012-06-02 22:27:45
如果不允许重复,有一个使用powersets的巧妙方法(以及从http://rosettacode.org/wiki/Power_set#Python抄袭来的一个很好的powerset函数):
def list_powerset(lst):
return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]])
def powerset(s):
return frozenset(map(frozenset, list_powerset(list(s))))
def valid_combos(num, lst):
return filter(lambda x: sum(x) == num, powerset(lst))这只适用于数字只出现一次的情况,但我仍然认为这是一个有趣的解决方案。:)
https://stackoverflow.com/questions/10862776
复制相似问题