最痛心以前做的笔记 Python 练习实例1
人世间最痛心以前做的笔记的就是我以前做的笔记找不到了。唉,多年的心血啊,都 是经验所得
题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。
程序源代码:
实例(Python 2.0+)
#!/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
以上实例输出结果为:
1 2 3 1 2 4 1 3 2 1 3 4 1 4 2 1 4 3 2 1 3 2 1 4 2 3 1 2 3 4 2 4 1 2 4 3 3 1 2 3 1 4 3 2 1 3 2 4 3 4 1 3 4 2 4 1 2 4 1 3 4 2 1 4 2 3 4 3 1 4 3 2
Python 100例
浙公网安备 33010602011771号
zavier
1262660796@qq.com
使用列表形式,并计算总结:
#!/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 dzavier
1262660796@qq.com
盼盼
946184399@qq.com
将for循环和if语句综合成一句,直接打印出结果
盼盼
946184399@qq.com
习惯乌龙茶
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))习惯乌龙茶
realsongtao@163.com
成科
121142125@qq.com
参考地址
python3 下参考方案:
#!/usr/bin/env python3 #coding:utf-8 num=[1,2,3,4] i=0 for a in num: for b in num: for c in num: if (a!=b) and (b!=c) and (c!=a): i+=1 print(a,b,c) print('总数是:',i)成科
121142125@qq.com
参考地址
whaike
huang4573@126.com
来一个更Pythonic的方式:
whaike
huang4573@126.com
白色帽子
liuy057@163.com
参考方法:
#!/usr/bin/env python #-*- coding:utf-8 -*- #用集合去除重复元素 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)白色帽子
liuy057@163.com
Chyroc
chen_yunpeng@foxmail.com
python自带这个函数的
#!/usr/bin/env python3 #coding:utf-8 from itertools import permutations for i in permutations([1, 2, 3, 4], 3): print(i)Chyroc
chen_yunpeng@foxmail.com
weapon
965842124@qq.com
补充一下:
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #补充一下 from itertools import permutations for i in permutations([1, 2, 3, 4], 3): k = '' for j in range(0, len(i)): k = k + str(i[j]) print (int(k))weapon
965842124@qq.com
逸章
me@dingdewen.com
没事找事之位运算
# coding:utf-8 #从 00 01 10 到 11 10 01 for num in range(6,58): a = num >> 4 & 3 b = num >> 2 & 3 c = num & 3 if( (a^b) and (b^c) and (c^a) ): print a+1,b+1,c+1www.pdfxs.com
www.123lala.cn