L=[2,8,3,50] length = len(L) count = 0 for i in xrange(length): minum = L[i] index = i for j in xrange(i + 1, length): if L[j] < minum: minum = L[j] index = j if index != i: L[i],L[index] = L[index],L[i] count += 1 print count
defegg(n, e=2): dp = [[n for i in xrange(e + 1)] for j in xrange(n + 1)] for i in xrange(1, n + 1): dp[i][1] = i for i in xrange(1, e + 1): dp[1][i] = 1 dp[2][i] = 2 for i in xrange(3, n + 1): for j in xrange(2, e + 1): for r in xrange(1, n): dp[i][j] = min(dp[i][j], 1 + max(dp[i - r][j], dp[r - 1][j - 1]))
取石子游戏说的是有两堆任意数量的小石子,游戏由两个人轮流取石子,对于取法,游戏规定有两种,一种是可以在任意的一堆中,取走任意多的石子;一种是在两堆中同时取走相同数量的石子。游戏规定,最后把石子全部取完的为胜者。现在假设初始时两堆石子的数目为a和b, a <= b,假设双方都采取最好的策略,问先取的人是胜者还是败者。
defedit_distance(a, b): la = len(a) lb = len(b) dp = [[0for i in xrange(lb + 1)] for j in xrange(la + 1)] for i in xrange(1, la + 1): dp[i][0] = i for j in xrange(1, lb + 1): dp[0][j] = j for i in xrange(la): for j in xrange(lb): if a[i] == b[j]: dp[i + 1][j + 1] = dp[i][j] else: dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j + 1], dp[i][j]) + 1 return dp[la][lb]
from collections import defaultdict defget_divisors(n): divisors = defaultdict(int) if n % 2 == 0: while n % 2 == 0: divisors[2] += 1 n /= 2 i = 3 while i * i <= n: if n % i == 0: while n % i == 0: divisors[i] += 1 n /= i i += 2 if n > 1: divisors[n] += 1 return divisors
有了这个方法就可以用来求一些数的最小公倍数,例如求,2 3 5 8 的最小公倍数
1 2 3 4 5 6 7 8 9 10
L = [2, 3, 5, 8] factors = defaultdict(int) for i in L: divisors = get_divisors(i) for d in divisors.iterkeys(): factors[d] = max(factors[d], divisors[d]) res = 1 for d in factors.iterkeys(): res *= d ** factors[d] print res
#coding:utf-8 from collections import defaultdict import codecs from math import log
classTrie(object): classTrieNode(): def__init__(self): self.value = 0 self.trans = {} def__init__(self): self.root = self.TrieNode() defadd(self, word, value=1): cur = self.root for ch in word: try: cur = cur.trans[ch] except: cur.trans[ch] = self.TrieNode() cur = cur.trans[ch] cur.value = value def_walk(self, node, ch): if ch in node.trans: node = node.trans[ch] return node, node.value else: returnNone, 0 defmatch_all(self, s): ret = [] cur = self.root for ch in s: cur, value = self._walk(cur, ch) ifnot cur: break if value: ret.append(value) return ret