有以下几个数字:1、2、3、4、5,能组成多少个互不相同且无重复数字的三位数?都是多少?
方法1:
import itertools from functools import reduce lyst = [1, 2, 3, 4, 5] result = [] for el in itertools.permutations(lyst, 3): temp = reduce(lambda x,y:x * 10 +y, el) result.append(temp) print(f'总共有{len(result)}个互不相同且五重复数字的三位数,分别是:') print(result)
方法2:
import copy numbers = [1, 2, 3, 4, 5] tri = [] for i in numbers: d_u = copy.copy(numbers) d_u.remove(i) for j in d_u: u = copy.copy(d_u) u.remove(j) for k in u : tri.append(i * 100 + j * 10 + k) print(tri) print(len(tri))
方法3:
import itertools count = 0 for i in itertools. product([1,2,3,4,5], repeat=3): if i[0] != i[1] and i[0] != i[2] and i[1] != i[2]: print(i[0]*100 + i[1]*10 + i[2]) count += 1 print(count)
方法4:
firstNumber = [1, 2, 3, 4, 5] count = 0 for i in firstNumber: secondNumber = firstNumber[:] secondNumber.remove(i) for j in secondNumber: thirdNumber = secondNumber[:] thirdNumber.remove(j) for k in thirdNumber: print(str(i) + str(j) + str(k), end=",") count += 1 print("一共有{}个数".format(count))