python数据结构学习笔记-2-算法

这篇博客主要探讨了三种算法:穷举法、回溯法和递归法。在穷举算法部分,通过数字谜的例子解释了如何列举所有可能的解。回溯算法则通过通用的排列生成函数展示了如何模拟人类操作,通过选择、计数和回溯来生成所有可能的排列。最后,博客提到了递归算法,包括磁盘使用情况、二分查找的递归实现和汉诺塔问题,强调理解和记忆经典例子的重要性。
摘要由CSDN通过智能技术生成

一、穷举算法

将解的所有可能情况一一列举出来,并验证其是否是符合条件的解。列举过程中,不能遗漏,不能重复。

1.实例1,求解数字谜

#数字迷 send + more = money
#相同的字母表示相同的数字,不同的字母表示不同的数字
for send in range(1000, 10000, 1):           #send取值范围1000~9999
    for more in range(1000,10000,1):         #more<span style="font-family: Arial, Helvetica, sans-serif;">取值范围1000~9999</span>
        money=send + more
        s = send /1000
        e = (send % 1000) / 100
        n = (send %100) / 10
        d = send % 10
        m = more /1000
        o = (more % 1000) / 100
        r = (more %100) / 10
        e1 =more % 10
        m2 = money / 10000
        o2 = (money % 10000) / 1000
        n2 = (money % 1000) / 100
        e2 =  (money % 100) / 10
        y = money % 10
        
        if e == e1 and e == e2 and m == m2 and o==o2 and n==n2:
            if s != e and s != n and s != d and s != m and s != o and s != r and s != y:
                if  e != n and e != d and e != m and e != o and e != r and e != y:
                    if   n != d and n != m and n != o and n != r and n != y:
                        if   d != m and d != o and d != r and d != y:
                            if  m != o and m != r and m != y:
                                if  o != r and o != y:
                                    if  r != y:
                                        print money , ' = ' , send, ' + ', more
输出结果(时间比较长,要等待一会)

10652  =  9567  +  1085
2.实例2,求a、b、c、d、e、f 6字母的全排列

a1 = ('a','b','c','d','e','f')
count = 0
for i1 in range(0,6):
    c1 = a1[i1]
    a2 = a1[0:i1] + a1[i1+1:6]
    for i2 in range(0,5):
        c2 = a2[i2]
        a3 = a2[0:i
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值