from collections import deque # 双头列表 defpalindrome(word): return word == word[::-1] defpalindrome(word): wd = deque(word) whilelen(wd) > 1: if wd.pop() != wd.popleft(): returnFalse returnTrue print(palindrome("x")) print(palindrome("abccba")) print(palindrome("radar")) print(palindrome("python"))
from pprint import pprint # 一行输出多个元素 print(sys.path)
import itertools for i in itertools.chain([1,2],['b','c']): # 1,2,b,c print(i) for i in itertools.cycle(('a','b','c')): # a,b,c,a,b,c print(i) for i in itertools.accumulate((1,2,3,4,5)): # 1,3,6,10,15 print(i) defmul(x, y): return (x * y) for i in itertools.accumulate((1,2,3,4,5),mul): # 1,2,6,24,120 print(i) x = ['a', 'b', 'c'] r = 2 y = itertools.combinations(x, r) print(list(y)) # [('a', 'b'), ('a', 'c'), ('b', 'c')]
trials = 1000000 Hits = 0 for i inrange(trials): x = random.random() * 2 - 1# x轴坐标 y = random.random() * 2 - 1# y轴坐标 if x * x + y * y <= 1: # 判断是否在圆内 Hits += 1 PI = 4 * Hits / trials