声明:课程学习总结,问题和答案参考自FISHC网,代码全部采用的是python3,编译器为jupyter notebook。
http://bbs.fishc.com/forum.php?mod=forumdisplay&fid=243&filter=typeid&typeid=398
1 输出星星
my own answer
tmp = int(input("please enter an int:"))
while tmp:
for i in range(0,tmp-1):
print(" ",end = '')
for j in range(0,tmp):
print ("*",end='')
print('\n')
tmp-=1
2 Python3可以给变量命名中文名,知道为什么吗?
Python3源码文件默认使用utf-8编码(支持中文),这就使得下面的代码是合法的
女朋友 = '莫莫'
print (女朋友)
结果为
莫莫
3 成员资格运算符(in)
成员资格运算符,in,用于检查一个值是否在序列中,在返回True,不在返回False
love = "我爱莫莫"
print ("莫莫" in love)
print ("琳琳" in love)
结果为
True
False
4 比较大小
输出x,y中较大(或者较小)值
法一
x = 1
y = 2
(x>y and [x] or [y])[0] # 输出x和y较大的那个,这种实现方法是pyhon没有出现三目运算符之前
结果是2
法二:
x = 1
y = 2
x if x>y else y #三目运算符操作,输出较大值
那么三个数比较大小呢?试试用三目运算符写写
x,y,z = 1,2,3
small = x if (x<y and y<z) else (y if y<z else z) #输出最小
big = x if (x>y and y>z) else (y if y>z else z) #输出最大
5 if-else 与 if-elif-else比较
多判断条件下,if-elif-else效率会比if-else高一些
if-else
mark = int(input("please enter an mark:"))
if 90<=mark<100:
print ("A")
if 80<=mark<90:
print ("B")
if 60<=mark<80:
print ("C")
if 0<=mark<60:
print ("D")
if-elif-else
mark = int(input("please enter an mark:"))
if 90<=mark<100:
print ("A")
elif 80<=mark<90:
print ("B")
elif 60<=mark<80:
print ("C")
elif 0<=mark<60:
print ("D")
else:
print("wrong input")
上面是,即使满足情况,也会执行下面的if
下面是,满足情况后,就不会执行后面的了,所以效率会高一些
6 最小公约数(欧几里德算法——递归)
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
7 bin
def bin1(a):
tmp = []
while a:
x = a%2
a = a//2
tmp.append(x)
l = len(tmp)
print("'0b",end='')
for i in range(0,l):
print(tmp[l-i-1],end='')
print("'")
8 汉诺塔
# x,y,z三根柱子,目标为,把X的汉诺塔移动到Z上,y过度
def han(n,x,y,z):
if n==1:
print(x,z)
else:
han(n-1,x,z,y)# 将n-1个从X移动到y上
print(x,z)# 最后一个从X移动到Z上
han(n-1,y,x,z)#n-1个从y移动到Z上
han(3,'x','y','z')
9 用filter和lambda输出100以内被3整除的数
list(filter(lambda x:x if x%3==0 else None,range(100)))
10 递归
10.1 递归阶乘
def nnn(n):
if n==1:
return 1
else:
return n*nnn(n-1)
10.2 递归拍照
(自拍模式,正面对着镜子)
10.3 递归幂运算
def power(x,y):
if y==0:
return 1
if y==1:
return x
else:
return x*power(x,y-1)
作者
01.def power(x, y):
02. if y:
03. return x * power(x, y-1)
04. else:
05. return 1
06.
07.print(power(2, 3))
10.4 整数分解并放在列表中(递归)
yyy = []
def xxx(n):
if n>0:
yyy.insert(0,n%10)
xxx(n//10)
xxx(34567890)
yyy
output
[3, 4, 5, 6, 7, 8, 9, 0]
10.5 思考一下,按照递归的特性,在编程中有没有不得不使用递归的情况?
答:例如汉诺塔,目录索引(因为你永远不知道这个目录里边是否还有目录),快速排序(二十世纪十大算法之一),树结构的定义等如果使用递归,会事半功倍,否则会导致程序无法实现或相当难以理解。
10.6 maximum recursion depth
无限递归1
def recurse():
recurse()
recurse()
output
RecursionError: maximum recursion depth exceeded
你可以认为系统设置了一个最大递归次数,如果超过这个次数还没解决问题,则抛出异常
11 排序BIF
sorted(list)
list.sort()
19 二维数组转置
方法一 T
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
a.T
output
array([[1, 3, 5],
[2, 4, 6]])
法二:zip *
import numpy as np
a = [[1,2],[3,4],[5,6]] # list
t = zip(* a)
print(list(t))
20 插值排序
def insertion_sort(list_):
for index in range(1, len(list_)):
value = list_[index]
position = index
# YOUR CODE HERE
for j in range(index,-1,-1):
# j为当前位置,试探j-1位置
if value < list_[j-1]:
list_[j] = list_[j-1]
else:
# 位置确定为j
break
list_[j] = value
21 zip(*变量)
unzip,前提是这个zip变量没有被迭代和list()过3
a = [1,2,3]
b = [4,5,6]
c = zip(a,b)
e,f = zip(*c)
e,f
output
((1, 2, 3), (4, 5, 6))
22 tensorflow: 查看 tensor详细数值4
import tensorflow as tf
x = tf.constant(1)
with tf.Session() as sess:
print sess.run(x)
output
1
或者
import tensorflow as tf
x = tf.constant(1)
sess = tf.InteractiveSession()
print x.eval()
output
1
23 模拟RPN选roi过程(多bath_size)
20W+ 根据 RPN分数排序,选6000
我们仿真,5个anchors,选3个roi出来,batch_size = 2 的情况
import tensorflow as tf
scores = [[1,2,3,4,5],[5,4,3,2,1]]
idx = [[2,3,4],[0,1,2]]
inputs = [scores,idx]
graph_fn = lambda x, y: tf.gather(x, y)
outputs = []
for i in range(2):
inputs_slice = [x[i] for x in inputs]
print(inputs_slice)
output_slice = graph_fn(*inputs_slice)
with tf.Session() as sess:
print (sess.run(output_slice))
if not isinstance(output_slice, (tuple, list)):
output_slice = [output_slice]
outputs.append(output_slice)
outputs = list(zip(*outputs))
with tf.Session() as sess:
print (sess.run(outputs))
output
[[1, 2, 3, 4, 5], [2, 3, 4]]
[3 4 5]
[[5, 4, 3, 2, 1], [0, 1, 2]]
[5 4 3]
[(array([3, 4, 5], dtype=int32), array([5, 4, 3], dtype=int32))]
names = None
if names is None:
names = [None] * len(outputs)
result = [tf.stack(o, axis=0, name=n)
for o, n in zip(outputs, names)]
if len(result) == 1:
result = result[0]
with tf.Session() as sess:
print (sess.run(result))
output
[[3 4 5]
[5 4 3]]
24 *args和**kwargs
学习任何语言时都会遇到很多里程碑。对于 Python 来说,理解神秘的**kwargs 语法可能算是其中之一5。
词典对象前面的双星号可以让你把该词典的内容作为命名参数输入到函数中。
词典的秘钥是参数名,值是传递给函数的值。你甚至不需要称它为 kwargs!
dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
print(a + b)
return
# these do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)
output
3
3
当你想编写能够处理事先未定义的命名参数的函数时,这个很有用。
25 Quick Sort
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[int(len(arr) / 2)]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
quicksort([3,6,8,10,1,2,1])
# Prints "[1, 1, 2, 3, 6, 8, 10]"
output
26 Emoji
http://www.unicode.org/emoji/charts/full-emoji-list.html
先pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:")) # 复制上图最后一栏的名字,加个下划线
print(emojize(":thumbs_down:"))
print(emojize(":sparkling_heart:"))
output
?
?
?
27 fuzzywuzzy(字符串匹配)
https://github.com/seatgeek/fuzzywuzzy
资源 | 让你事半功倍的小众Python库
安装
pip install fuzzywuzzy
pip install python-Levenshtein
测试下
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
# Simple Ratio
fuzz.ratio("this is a test", "this is a test!")
output
97
28 python用time函数计算程序运行时间
import time
start = time.clock()
#当中是你的程序
elapsed = (time.clock() - start)
print("Time used:",elapsed)
output
29
out
未完待续……