Skip to content

Instantly share code, notes, and snippets.

@polebug
Last active September 7, 2017 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polebug/f573d4b7b8a93c1e835fead225b9a6de to your computer and use it in GitHub Desktop.
Save polebug/f573d4b7b8a93c1e835fead225b9a6de to your computer and use it in GitHub Desktop.
Most ThinkPython Exercises

上学期看了 ThinkPython,感觉后面的题目引申不错,于是写了写。
以及当时写了一些笔记,都扔在这里好了。

笔记:

对于列表:

列表的操作主要有find, add, 切片, 归并, sort/sorted, map, 筛选(filter), 删除, list, split, join
0.其中add操作有append(添加一个元素并返回None), extend(添加一个列表);
1.这里的归并的定义是:将一系列的元素合并成一个单一值的操作;
2.删除操作有, pop:将移除指定下标的元素并返回最后一个元素; del:移除指定下标的元素,可移除多个元素,结合切片索引使用;remove:直接删除值,无需知道下标;
3.list:将一个字符串转换为字符的列表;
4.split():将字符串分割成一些单词的列表, 在括号内可以指定分隔符;
5.join():功能与split相反;
6.t2 = sorted(t):返回一个新的已排序的列表,原列表保持不变;

PS:
稍微引用一下split和join的用法

>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> t = s.split(delimiter)
>>> t
['spam', 'spam', 'spam']
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> s = delimiter.join(t)
>>> s
'pining for the fjords'

对于字典:

0.字典的元素不使用整数索引来索引,而是用键来查找对应的值;
1.len(): 返回键值对的个数;
2.in: 检验字典是否存在某个key;
3.in dic.values: 检验字典中是否存在某个值;
4.对于dictionary, python使用的是hashtable算法,无论字典中有多少项,in搜索所需的时候都是一样的;
5.get(): 接受一个键和一个默认值作为参数,如果字典中存在该键,则返回对应值;否则返回传入的默认值;
6.字典中的键是无序的,如果要以确定的顺序遍历字典,可以使用内建方法sorted()排序键;
7.lookup: value = dic[key],reverse_lookup则需要遍历;
8.raise语句能出发异常,
例如:

raise LookupError()

则在Traceback后显示LookupError;
9.Dictionary中的kye和value都可以是list;

def right_justify(s):
l = len(s)
for i in range(70-l):
print " ",
print s
s = raw_input()
right_justify(s)
def print_twice(s):
for i in range(2):
print s
def do_four(print_twice, s):
for i in range(4):
print_twice(s)
s = raw_input()
do_four(print_twice, s)
def printForm(n, m):
for i in range(n):
for j in range(m):
print '+ - - - -',
print '+'
for k in range(n+1):
for t in range(4):
print '| ',
print '| '
for j in range(m):
print '+ - - - -',
print '+'
if __name__=='__main__':
n = input()
m = input()
printForm(n, m)
from swampy.TurtleWorld import *
import math
def flower(t, n, r, angle):
for i in range(n):
arc(t, r, angle)
lt(t, 180-angle)
arc(t, r, angle)
lt(t, 180-angle)
lt(t, 360/n)
def arc(t, r, angle):
AllLength = 2*math.pi*r*angle/360 #求出周长
n = int(AllLength/2) #(圆周率的定义)已知周长,求出近似圆的多边形边数n
EachLength = AllLength / n #每条边的长度
EachAngle = float(angle) / n #转过的角度
polyline(t, n, EachLength, EachAngle)
def polyline(t, n, length, angle): #画弧
for i in range(n):
fd(t, length)
lt(t, angle)
if __name__=='__main__':
world = TurtleWorld()
bob = Turtle()
bob.delay = 0
print bob
n = input()
r = input()
angle = input()
flower(bob, n, r, angle)
wait_for_user()
from swampy.TurtleWorld import *
import math
def pie(t, n, Length):
DingAngle = float(360/n)
DiAngle = 90 - float(DingAngle)/2
DoubleLength = Length
DiLength = math.sqrt((1.0-math.cos(DingAngle*1.0*math.pi/180))*2.0*Length*Length)
for i in range(n):
fd(t, DoubleLength)
lt(t, 180 - DiAngle)
fd(t, DiLength)
lt(t, 180 - DiAngle)
fd(t, DoubleLength)
lt(t, 180)
if __name__ == '__main__':
w = TurtleWorld()
bob = Turtle()
print bob
n = input()
Length = input()
pie(bob, n, Length)
wait_for_user()
import math
def CheckFermat(n, a, b, c):
if math.pow(a, n) + math.pow(b, n) == math.pow(c, n):
print "不,那样不行"
else:
print "天哪,费马弄错了"
while True:
n = input()
if n>2:
break
else:
print "输入的n不满足条件,请再次输入"
a = input()
b = input()
c = input()
CheckFermat(int(n), int(a), int(b), int(c))
def IsTriangle(a, b, c):
if a+b>c and a+c>b and b+c>a :
print "YES"
else:
print "NO"
print "Please Enter Three Number: "
a = input()
b = input()
c = input()
IsTriangle(a, b, c)
from swampy.TurtleWorld import *
import math
def draw(t, length, n):
"""
通过回溯画一个二叉树
"""
if n==0:
return
angle =50
fd(t, length*n)
lt(t, angle)
draw(t, length, n-1)
rt(t, 2*angle)
draw(t, length, n-1)
lt(t, angle)
bk(t, length*n)
world = TurtleWorld()
bob = Turtle()
print "Please Enter length and n: "
length = input()
n = input()
draw(bob , length, n)
from swampy.TurtleWorld import *
def koch(t, length):
if length<3:
fd(t, length)
return
m = length/3
koch(t, m)
lt(t, 60)
koch(t, m)
rt(t, 120)
koch(t, m)
lt(t, 60)
koch(t, m)
def snowflake(t, length):
for i in range(3):
koch(t, length)
rt(t, 120)
world = TurtleWorld()
bob = Turtle()
bob.delay = 0
print "Please Enter Length: "
length = input()
snowflake(bob, length)
def Ackermann(m, n):
if m == 0:
return n + 1
elif m > 0 and n == 0:
return Ackermann(m-1, 1)
elif m > 0 and n > 0:
return Ackermann(m-1, Ackermann(m, n-1))
m = input()
n = input()
print Ackermann(m, n)
def palindrome(s):
l = len(s)
if l<=1:
return True
if s[0] != s[-1]:
return False
else:
return True
return palindrome(s[1:-2])
s = raw_input()
if palindrome(s):
print "YES"
else:
print "NO"
Raw
def is_power(a, b):
if a % b == 0:
a = a/b
if a > b:
is_power(a, b)
elif a == b:
return True
else:
return False
a = int(raw_input())
b = int(raw_input())
if is_power(a, b):
print "True"
else:
print "False"
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
a = int(raw_input())
b = int(raw_input())
if a > b:
print gcd(a, b)
else:
print gcd(b, a)
import math
def mysqrt(a, x):
while True:
y = (x + a / x) / 2
if abs(y - x) < 1e-7:
break
x = y
test_squre_root(a, x)
def test_squre_root(a, x):
n = math.sqrt(a)
print "%.2f" % a,5*" ","%.10f" % x,2*" ","%.10f" % n,4*" ","%.6f" % abs(n - x)
a = input()
x = a*1.0/2
print "a",8*" ","mysqrt",8*" ","math.sqrt(a)",4*" ","diff"
print "-",8*" ",6*"-",8*" ",12*"-",4*" ",4*"-"
mysqrt(a, x)
def eval_loop():
while True:
UserInput = raw_input()
if UserInput == "done":
break
print eval(UserInput)
eval_loop()
import math
def estimate_pi():
k = 0
sum = 0
while True:
n = 1
m = 1
for i in range(1,4*k):
n *= i
n *= (1103 + 26390*k)
for i in range(1,k):
m *= i
m = math.pow(m, 4)
m *= math.pow(396, 4*k)
sum += (n*1.0/m)
if (n*1.0/m) < 1e-15:
break
k += 1
sum *= 2 * math.sqrt(2) / 9801
return 1.0/sum
d = abs(estimate_pi() - math.pi)
print d
# strip用法
http://www.runoob.com/python/att-string-strip.html
# replace用法
http://www.runoob.com/python/att-string-replace.html
# count用法
http://www.runoob.com/python/att-string-count.html
def is_palindrome(s):
return s == s[::-1]
s = raw_input()
if is_palindrome(s):
print "YES"
else:
print "NO"
def rotate_world(s, n):
new = ''
for c in s:
new += chr(ord(c) + n)
print new
s = raw_input()
n = input()
rotate_world(s, n)
fin = open('words.txt')
for line in fin:
word = line.strip()
if len(word) > 20:
print word
def has_no_e(s):
for c in s:
if c == 'e':
return False
return True
while True:
print "Please Enter a string: "
s = raw_input()
if has_no_e(s):
print True
else:
print False
print "Enter again?(y/n): "
answer = raw_input()
if answer == 'n':
break
fin = open('words.txt')
sum = 0
num = 0
for line in fin:
sum += 1
word = line.strip()
if has_no_e(word):
num += 1
print word
print "不含e的单词的比例:",sum*1.0/num
def avoids(word, str):
for letter in word:
if letter in str:
return False
return True
def uses_only(word, str):
for c in word:
if c not in str:
return False
return True
def uses_all(word, str):
for c in str:
if c not in word:
return False
return True
def is_abecedarian(s):
for i in range(len(s)-1):
if ord(s[i]) != ord(s[i+1]) -1 :
return False
return True
fin = open('words.txt')
for line in fin:
word = line.strip()
num = 0
i = 0
flag = False
while i < len(word) -1 :
if word[i] == word[i+1]:
num += 1
if num == 3:
flag = True
i = i + 2
else:
num = 0
i = i + 1
if flag :
print word
def is_palindrome(i, start, end):
ss = str(i)[start:end]
return ss == ss[::-1]
i = 100000
while i<= 999999:
if is_palindrome(i, 2, 5) and is_palindrome(i+1, 1, 5) and
is_palindrome(i+2, 1, 4) and is_palindrome(i+3, 0, 6):
print i
i += 1
def check(d, m):
num = 0
for i in range(int(d),int(m)):
ds = str(i)
ms = ds.zfill(2)[::-1]
if int(ds) in range(int(d),int(m)) and int(ms) in range(int(d),int(m)) and int(ds)<int(ms) and int(ms)>15 and int(ms)-int(ds)<50:
num +=1
return num
for d in range(1,99):
s = str(d)
m = s.zfill(2)[::-1]
if check(str(d),m) == 6:
print d
import copy
def nested_sum(t):
tot = 0
for i in t:
tot += i
return tot
def cumsum(t):
s = t[:]
for i in range(1,len(s)):
s[i] += s[i-1]
print s
def middle(t):
l = []
for i in t[1:-1]:
l.append(i)
print l
def chop(t):
s = copy.copy(t)
t.pop(0)
t.pop(-1)
print t
def is_sorted(t):
for i in range(1,len(t)):
if t[i]<t[i-1]:
return False
return True
def is_anagram(str1, str2):
l = list(str2)
for c in str1:
if c in l:
l.remove(c)
else:
return False
return True
def has_duplicates(t):
for i in range(len(t)):
for j in range(len(t)):
if i!=j and t[i]==t[j]:
return True
return False
if __name__=='__main__':
t = input()
print "nested_sum():"
nested_sum(t)
print "cumsum():"
cumsum(t)
print "middle():"
middle(t)
s = copy.deepcopy(t)
chop(s)
print "chop():", s
print "is_sorted():", is_sorted(t)
print "has_duplicates():", has_duplicates(t)
str1 = raw_input()
str2 = raw_input()
print "is_anagram():", is_anagram(str1, str2)
import random
def RandomDay():
t = []
for i in range(23):
day = random.randint(1,365)
t.append(day)
return t
def main():
num = 0
for i in range(1000):
t = RandomDay()
t.sort()
for i in range(len(t)-1):
if t[i] == t[i+1]:
num += 1
print num*1.0/1000
if __name__=='__main__':
main()
from time import time
def test1():
fin = open('words.txt')
t = []
start = time()
for line in fin:
word = line.strip()
t.append(word)
end = time()
print "Time for Test1:", end - start
def test2():
fin = open('words.txt')
t = []
start = time()
for line in fin:
word = line.strip()
t = t + [word]
end = time()
print "Time for Test2:", end - start
if __name__ == '__main__':
test1()
test2()
import bisect
def in_bisect(s):
left = 0
right = len(t)
while left<right :
mid = (left + right)/2
if t[mid] > s:
right = mid
elif t[mid] < s:
left = mid
else:
print "in_bisect(): ",mid + 1
return
print "in_bisect(): None"
def is_bisect(s):
print "is_bisect(): ",bisect.bisect(t, s)
if __name__=='__main__':
fin = open('words.txt')
t = []
for line in fin:
t.append(line.strip())
s = raw_input()
in_bisect(s)
is_bisect(s)
fin = open('words.txt')
t = []
for line in fin:
t.append(line.strip())
for word in t:
s = word[::-1]
if s in t and word!=s :
print word, s
import bisect
def interlock2(word):
s1 = word[::2]
s2 = word[1::2]
return bisect.bisect(t, s1) and bisect.bisect(t, s2)
def interlock3(word):
for i in range(3):
inter = word[i::3]
if not bisect.bisect(t, inter):
return False
return True
if __name__=='__main__':
fin = open('words.txt')
t = []
for line in fin:
t.append(line.strip())
for word in t:
if interlock2(word):
print word, word[::2], word[1::2]
for word in t:
if interlock3(word):
print word, word[::3], word[1::3], word[2::3]
from time import time
def judge(s):
fin = open('words.txt')
t = {}
for word in fin:
t[word] = 1
start = time()
if s in t:
print s,"is in the dictionary"
else:
print s,"isn't in the dictionary"
end = time()
print "time: ",end - start
if __name__=='__main__':
s = raw_input()
judge(s)
def inver_dic(s):
if t[s]:
return "True"
else:
return "False"
if __name__=='__main__':
fin = open('words.txt')
t = {}
for word in fin:
t.setdefault(word.strip(),1)
s = raw_input()
print inver_dic(s)
def ackermann(m, n):
if (m, n) in known:
return known[(m, n)]
if n==0:
return ackermann(m-1, 1)
if m==0:
return n + 1
try:
return known[(m, n)]
except KeyError:
known[(m, n)] = ackermann(m-1, ackermann(m, n-1))
return known[(m, n)]
if __name__ == '__main__':
m = input()
n = input()
known = {}
known[(0, n)] = n+1
print ackermann(m, n)
def has_duplicates(l):
d = {}
for i in l:
if i in d:
print "True"
return
else:
d[i] = 1
print "False"
if __name__ == '__main__':
l = input()
has_duplicates(l)
def rotate_pairs():
d = {}
for line in fin:
word1 = line.strip().lower()
d[word1] = None
word2 = word1[::-1]
if word2 in d:
print word1, word2
if __name__ == '__main__':
fin = open('words.txt')
rotate_pairs()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment