蓝桥杯--数字排列的Python解法

今有7对数字:两个1,两个2,两个3,...两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,
两个7之间有7个其它数字。如下就是一个符合要求的排列:
17126425374635

当然,如果把它倒过来,也是符合要求的。
请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。

注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。


这里用Python解决可以利用生成器的强大回溯能力,可以参考一下8皇后的Python解法。
在各种编程语言实现的算法中Python的这个还是相当精练巧妙的,当然了性能就不好说了偷笑

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def solution(num_list, slots):
    n = num_list[0]
    for pos in range(len(slots)-n-1):
        if slots[pos] == 0 and slots[pos+n+1] == 0:
            temp = list(slots)
            temp[pos] = n
            temp[pos+n+1] = n
            if n == 1:
                yield temp
            else:
                for result in solution(num_list[1:], temp):
                    yield result

init = (7, 4, 0, 0, 0, 0, 4, 0, 7, 0, 0, 0, 0, 0)
nums = (6,5,3,2,1)

for s in solution(num_list=nums, slots=init):
    print(''.join(map(str, s)))


# 74151643752362


如果要找出所有符合模式的排列还要省事一些:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def solution(n, slots):
    for pos in range(len(slots)-n-1):
        if slots[pos] == 0 and slots[pos+n+1] == 0:
            temp = list(slots)
            temp[pos] = n
            temp[pos+n+1] = n
            if n == 1:
                yield temp
            else:
                for result in solution(n-1, temp):
                    yield result
               
for s in solution(n=7, slots=[0]*14):
    print(''.join(map(str, s)))

输出结果:
73625324765141
72632453764151
72462354736151
73161345726425
71416354732652
71316435724625
74151643752362
72452634753161
57263254376141
37463254276151
57416154372632
57236253471614
17126425374635
57141653472362
17125623475364
27423564371516
62742356437151
26721514637543
36713145627425
51716254237643
23726351417654
41716425327635
52732653417164
35743625427161
35723625417164
24723645317165
56171354632742
46171452632753
16172452634753
46171435623725
53672352461714
45671415362732
34673245261715
52472654131763
34573641512762
15173465324726
61517346532472
46357432652171
26327435614175
53647352462171
41617435263275
23627345161475
15167245236473
14167345236275
16135743625427
26325734615147
52642753461317
25623745361417
52462754316137
15163745326427
15146735423627
14156742352637
>>> 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值