我这个低级的算法,看了官方代码显得更加的低级了:
原始思维:以解决问题为目标
# -*- coding: UTF-8 -*-
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
def worker(num = ()):
print(num)
length = len(num)
ruselt = []
for i in range(length):
if i == 0:
other = num[i + 1:length]
elif i == length - 1:
other = num[0:length - 1]
else:
other = num[0:i] + num[i + 1:length]
length2 = len(other)
for j in range(length2):
if j == 0:
other2 = other[j + 1:length]
elif j == length - 1:
other2 = other[0:length - 1]
else:
other2 = other[0:j] + other[j + 1:length]
for x in other2:
ruselt.append(f"{num[i]}{other[j]}{x}")
return ruselt
ruselt = worker((1, 2, 3, 4))
print("有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?".center(100, "*"))
print(ruselt)
print(f"结束,共{len(ruselt)}个结果!".center(100, "*"))
2次升级改造,处理相似的需求:
# -*- coding: UTF-8 -*-
import time # 引入time模块
import sys
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
inputData = [] # 基础数据
for d in range(4): # 1~9 最大到9
inputData.append(d + 1)
# print(inputData)
# sys.exit()
outputLen = 3 # 生成几位数
ruselt = [] # 输出结果
# num: 基础数据,递归传入
# tag: 标记,是否进入递归
# qNum: 前边排列好的数字
def worker(num, tag, qNum = ""):
# print(num, tag, qNum)
if tag > len(inputData) - outputLen + 1:
length = len(num)
for i in range(length):
if i == 0:
other = num[i + 1:length]
elif i == length - 1:
other = num[0:length - 1]
else:
other = num[0:i] + num[i + 1:length]
if qNum == "":
q = ""
else:
q = ","
worker(other, tag - 1, qNum + q + str(num[i]))
else:
for x in num:
ruselt.append(f"{qNum},{x}")
print("有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?".center(100, "*"))
startT = time.time()
worker(inputData, len(inputData))
print(ruselt)
startE = time.time()
print(f"结束,共{len(ruselt)}个结果!耗时:{startE - startT}秒!".center(100, "*"))