def permutation(iterable, r=None): # r:lengthpermutations of elements in the iterable # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012021102120201210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = list(range(n)) cycles = list(range(n, n-r, -1)) yield tuple(pool[i] for i inindices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i inindices[:r]) break else: return
源码还是挺复杂的,,,,,
1 2 3 4 5 6 7 8 9 10 11
### 力扣方法,也是递归
def permutation(S): iflen(S)==1: return [S] ans=[] for i in range(len(S)): s=S[:i]+S[i+1:] forstring in permutation(s): ans.append(S[i]+string) return ans
def merge(left, right): '''合并操作,将两个有序数组left[]和right[]合并成一个大的有序数组''' #left与right的下标指针 l, r = 0, 0 result = [] while l<len(left) and r<len(right): if left[l] < right[r]: result.append(left[l]) l += 1 else: result.append(right[r]) r += 1 result += left[l:] result += right[r:] returnresult
print(merge(a, b))
每个 SNP 位点用一个长度为 2 的 list 表示,第一个元素为染色体编号(chr,范围为 1~22),第二个元素为染色体上的位置(pos)。写一个 python 函数,输入两个正序(按 chr 和 pos 排序)的 SNP 位点 list,输出一个合并且去重的正序 SNP 位点 list。不能使用 sorted 函数、pandas 库,要求时间复杂度尽可能低。 例如:
def merge(list1, list2): l, r = 0, 0 result = [] while l<len(list1) and r<len(list2): if list1[l][0] < list2[r][0]: if list1[l] not in result: result.append(list1[l]) l += 1 else: if list2[r] not in result: result.append(list2[r]) r += 1
result += list1[l:] result += list2[r:] return result
print(merge(list1, list2))
题目描述:
输出单向链表中倒数第k个结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classNode(object):
def__init__(self, val=0): self.val = val self.next = None
whileTrue: try: l, s, k, head = int(input()), list(map(int, input().split())), int(input()), Node() while k: head.next = Node(s.pop()) head = head.next k -= 1 print(head.val) except: break
defeditDistance(str1, str2): ''' 计算字符串str1和str2的编辑距离 ''' edit = [[i+j for j inrange(len(str2)+1)] for i inrange(len(str1)+1)] print(edit) for i inrange(1,len(str1)+1): for j inrange(1,len(str2)+1): if str1[i-1] == str2[j-1]: d = 0 else: d = 1 edit[i][j] = min(edit[i-1][j]+1,edit[i][j-1]+1,edit[i-1][j-1]+d) return edit[len(str1)][len(str2)]
editDistance('python', 'pyton')
题目描述:
最长回文字串
1 2 3 4 5 6 7 8 9 10
s = input() win_len = 2 s_list = [] foriin range(len(s)): for j in range(i+1, len(s) + 1): ss = s[i:j] if ss == ss[::-1]: s_list.append(len(ss))