python练习(11)——若干个数,组成若干位,无重复数字

版权声明:转载请注明出处 https://blog.csdn.net/qq_33287645/article/details/79950297
# 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
def nums():
    nums = []
    for i in range(1,5):
        for j in range(1,5):
            if j != i:
                for k in range(1,5):
                    if k != i and k != j:
                        num = i*100 + j*10 + k
                        nums.append(num)
    return nums
# 连续数字,构建进制数,五进制
def digits():
    digits = []
    fives = [2,2,1] 
    for i in range(int('123',5),int('432',5)+1):
        fives[0] += 1
        for j in range(len(fives)):
            flag = True
            if fives[j] == 5:
                fives[j] = 0
                if j+1 == len(fives):
                    fives.append(0)
                fives[j+1] += 1
                flag = False
            if flag: break
        set1 = set(fives)
        if len(fives) == len(set1) and (0 not in set1):
            sum = 0
            for i in range(-1,-len(fives)-1,-1):
                sum = sum * 10 + fives[i]
            digits.append(sum)   
    return  digits
# 延伸,若干个数,组成若干位无重复数字
# 字典,集合实现,递归即循环? 字典key记录组成的数字,value(用字典)记录剩余没有使用的数字,每一次循环构造新的k,v对
# {1:{2,3,4},                      2:{1,3,4},3:{1,2,4},4:{1,2,3}}
# {12:{3,4},13:{2,4},14:{2,4}}

# 不用递归,循环实现
def numsfor(lst,num):
    dics = {0:set(lst)}
    for i in range(num):
        nums = {}
        for k,v in dics.items():
            for j in v:
                if k == 0 and j == 0:
                    continue
                nums.update({k*10+j:v-{j,}})
            dics = nums
    return [i for i in dics]

 

 

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页