python 练习题1--打印三位不重复数字

题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。

程序源代码:

源码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if( i != k ) and (i != j) and (j != k):
print i,j,k


我的源码:

num=5
#num=raw_input("input number to get three-digital number:")
list1=range(1,num)
counter=0
for i in list1:
for j in list1:
if(i!=j):
for k in list1:
if(i!=j and j!=k and i!=k):
print(i*100+j*10+k)
counter+=1
else:
continue
else:
continue

print("total :"+str(counter))


其他人的解法参考:
  1. 使用列表形式,并计算总结:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 原答案没有指出三位数的数量,添加无重复三位数的数量
    
    d=[]
    for a in range(1,5):
        for b in range(1,5):
            for c in range(1,5):
                if (a!=b) and (a!=c) and (c!=b):
                    d.append([a,b,c])
    print "总数量:", len(d)
    print d
     
  2.    盼盼

      946184399@qq.com

    将for循环和if语句综合成一句,直接打印出结果

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    
    list_num = [1,2,3,4]
    
    list  = [i*100 + j*10 + k for i in list_num for j in list_num for k in list_num if (j != i and k != j and k != i)]
    
    print (list)
     

     

  3.    习惯乌龙茶

      realsongtao@163.com

    参考方法(设置最大,最小值):

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    line=[]
    for i in range(123,433):
    	a=i%10
    	b=(i%100)//10
    	c=(i%1000)//100
    	if a!=b and b!=c and a!=c  and 0<a<5 and 0<b<5 and 0<c<5 :
    		print (i)
    		line.append(i)
    print('the total is :',len(line))



posted on 2017-04-25 17:38  gaomatlab  阅读(2239)  评论(0编辑  收藏  举报

导航