【发布时间】:2011-11-25 11:50:56
【问题描述】:
我正在尝试编写一个函数来计算字符串的唯一排列数。例如,aaa 将返回 1,abc 将返回 6。
我正在写这样的方法:
(伪代码:)
len(string)! / (A!*B!*C!*...)
其中 A,B,C 是每个唯一字符的出现次数。例如,字符串'aaa' 将是3! / 3! = 1,而'abc' 将是3! / (1! * 1! * 1!) = 6。
到目前为止我的代码是这样的:
def permutations(n):
'''
returns the number of UNIQUE permutations of n
'''
from math import factorial
lst = []
n = str(n)
for l in set(n):
lst.append(n.count(l))
return factorial(len(n)) / reduce(lambda x,y: factorial(x) * factorial(y), lst)
一切正常,除非我尝试传递一个只有一个唯一字符的字符串,即aaa - 我得到了错误的答案:
>>> perm('abc')
6
>>> perm('aaa')
2
>>> perm('aaaa')
6
现在,我可以看出问题在于在长度为 1 的列表上运行带有阶乘的 lambda 函数。不过,我不知道为什么。大多数其他 lambda 函数都适用于长度为 1 的列表,即使它需要两个元素:
>>> reduce(lambda x,y: x * y, [3])
3
>>> reduce(lambda x,y: x + y, [3])
3
这个没有:
>>> reduce(lambda x,y: ord(x) + ord(y), ['a'])
'a'
>>> reduce(lambda x,y: ord(x) + ord(y), ['a','b'])
195
有什么我应该做的不同的事情吗?我知道我可以用许多不同的方式重写函数来规避这个问题(例如,不使用lambda),但我正在寻找为什么这特别不起作用。
【问题讨论】:
标签: python lambda permutation reduce factorial