有1,2,3,4 四个数字,能组成多少互不重复的四位数,各是多少。
方法一:
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
for d in range(1,5):
if i != k and j != k and i != j and d != i and d != k and d != j:
print(1000 * i + 100 * j + 10 * k + d)
方法一的变形
a = [1,2,3,4]
for i in a:
for j in a:
for k in a:
for d in a:
if i != k and j != k and i != j and d !=i and d !=k and d !=j:
print(1000*i+100*j+10*k+d)
方法二:
import pprint
list_num = ['1', '2', '3', '4']
list_result = []
for i in list_num:
for j in list_num:
for k in list_num:
if len(set(i + j + k)) == 3: #利用数组的重复
list_result += [int(i + j + k)]
print("能组成%d个互不相同且无重复数字的三位数:" % len(list_result))
pprint.pprint(list_result)