免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
123
最近访问板块 发新帖
楼主: teebye
打印 上一主题 下一主题

排列组合的题,有点难度哦 [复制链接]

论坛徽章:
0
21 [报告]
发表于 2009-03-22 20:22 |只看该作者
参考网上的算法:
#!/usr/bin/env python

def perm(seq, l=None):
        if l is None:
                l = len(seq)
        for i in range(len(seq)):
                c  = seq[i:i+1]
                if l == 1:
                        yield c
                else:
                        rest = seq[:i] + seq[i+1:]
                        for p in perm(rest, l-1):
                                yield c + p

def main(seq):
        a = perm(seq)
        b = set(a)
        print "There are %i sequences:" %len(b)
        for i in b:
                print i

if __name__ == '__main__':
        main('aaab')


运行结果:
$ python tst.py
There are 4 sequences:
abaa
aaba
aaab
baaa

[ 本帖最后由 爱知 于 2009-3-22 20:30 编辑 ]

论坛徽章:
0
22 [报告]
发表于 2009-03-23 12:11 |只看该作者
ls 太麻烦了,如果只要输出个数的话:

  1. #!/usr/bin/python
  2. fact=lambda x : x and reduce(lambda a,b:a*b,xrange(1,x+1) or 1;
  3. l=raw_input().split();
  4. t=[l.count(l[i]) for i in xrange(len(l)) if i=l.index(l[i])];
  5. x=fact(len(l));
  6. for i in t : x=x/fact(i);
复制代码

论坛徽章:
0
23 [报告]
发表于 2009-04-02 20:09 |只看该作者
发霉题配发霉算法:

def perm(s):
    if len(s)==1:
        yield s
    else:
        for x in set(s):
            i=s.find(x)
            for j in perm(s[:i]+s[i+1:]):
                yield s[i]+j


大家都被Teebye弄头晕了吧

论坛徽章:
0
24 [报告]
发表于 2009-04-02 20:41 |只看该作者

回复 #23 niexining 的帖子

想了想,find改成index更通用一点,既能用于list, 也能用于str.

论坛徽章:
0
25 [报告]
发表于 2009-04-02 22:36 |只看该作者
def judge(s,k,i):
    for j in range(k,i):
        if s[i] == s[j]:
            return True
    return False
def reperm(s,k,m):
    if k==m:
        print s
    else:
        for i in range(k,m+1):
            if judge(s,k,i):
                continue
            s[k],s[i]=s[i],s[k]
            perm(s,k+1,m)
            s[k],s[i]=s[i],s[k]
s=['a','a','b']
reperm(s,0,len(s)-1)

结果:
['a', 'a', 'b']
['a', 'b', 'a']
['b', 'a', 'a']

论坛徽章:
0
26 [报告]
发表于 2009-04-09 22:35 |只看该作者

回复 #1 teebye 的帖子

可以打印出所有可能的排列,重复的组合不会打印出来

其中有些实现的地方很ugly,见笑

#!/usr/bin/python
import copy

l = ['a', 'b', 'c', 'd']

# xx() is a recursive function
# it returns a list of list which represents all possible assembles for given list
# NOTE: there might be identical assembles in the returned list
def xx(ll):
    result = list()
    if len(ll) == 1:
        result = ll   
    else:
        # tail is the last element of current list
        # pre is the list of possible assembles for ll[:-1]
        tail = ll[-1]
        pre = xx(ll[:-1])
        # insert tail to all possible positions in pre
        # use copy.deepcopy to create a new list from pre everytime
        # put all newly generated assembles into result
        for pre_sub in pre:
            for i in xrange(len(pre_sub)):
                tmp = list(copy.deepcopy(pre_sub))
                tmp.insert(i, tail)
                result.append(tmp)
            tmp = list(copy.deepcopy(pre_sub))
            tmp.append(tail)
            result.append(tmp)
    return result

if __name__ == '__main__':
    t = xx(l)
    # convert the return value of xx() from list of list
    # to list of strings
    for i in xrange(len(t)):
        t[i] = reduce(lambda x, y: x + y, t[i])
    # eleminate identical results with set()
    t = set(t)
    print 'Number of possible assembles for list', l, 'is:', len(t)
    for ele in t:
        print ele
    


结果如下:
Number of possible assembles for list ['a', 'b', 'c', 'd'] is: 24
abcd
bacd
dbac
dcab
cabd
cadb
cdba
dacb
cdab
bdca
dbca
cbda
adcb
acbd
dcba
acdb
bdac
cbad
bcda
dabc
abdc
adbc
badc
bcad

论坛徽章:
0
27 [报告]
发表于 2009-04-10 09:03 |只看该作者

回复 #11 teebye 的帖子

呵呵,
飘过
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP