1、迭代器
迭代器有两个基本的方法:iter() 和 next()。
import sys
list=[1,2,3,4]
it = iter(list)
while True:
try:
print (next(it))
except StopIteration:
sys.exit()
生成器
在 Python 中,使用了 yield 的函数被称为生成器(generator)。
跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。
调用一个生成器函数,返回的是一个迭代器对象。
以下实例使用 yield 实现斐波那契数列:
import sys
def fibonacci(n):
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10)
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
2、求最长公共子序列
while True:
string1,string2 = input('input two string').split()
result = [[0 for i in range(len(string2)+1)] for j in range(len(string1)+1)]
for i in range(1,len(string1)+1):
for j in range(1,len(string2)+1):
if string1[i-1]==string2[j-1]:
result[i][j] = result[i-1][j-1]+1
else:
result[i][j] = max(result[i - 1][j], result[i][j - 1])
print(result,result[-1][-1])
3、求最长公共子串
def LCstring(string1,string2):
len1 = len(string1)
len2 = len(string2)
res = [[0 for i in range(len1+1)] for j in range(len2+1)]
result = 0
for i in range(1,len2+1):
for j in range(1,len1+1):
if string2[i-1] == string1[j-1]:
res[i][j] = res[i-1][j-1]+1
result = max(result,res[i][j])
return result
print(LCstring("helloworld","loop"))
4、爬楼梯
def climbStairs(n):
if n == 1 or n == 2:
return n
result = [1,2]
for i in range(2,n):
result.append(result[i-1]+result[i-2])
return result[-1]
print(climbStairs(5))
5、按之字打印二叉树
class Solution:
def PrintFromTopToBottom(self, root):
array = []
result = []
if root == None:
return result
array.append(root)
while array:
newNode = array.pop(0)
result.append(newNode.val)
if newNode.left != None:
array.append(newNode.left)
if newNode.right != None:
array.append(newNode.right)
return result
def getBSTwithPreTin(self, pre, tin):
if len(pre)==0 | len(tin)==0:
return None
root = treeNode(pre[0])
for order,item in enumerate(tin):
if root .val == item:
root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order])
root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:])
return root
class treeNode:
def __init__(self, x):
self.left = None
self.right = None
self.val = x
if __name__ == '__main__':
flag = "printTreeNode"
solution = Solution()
preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8]
middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6]
treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
if flag == "printTreeNode":
newArray = solution.PrintFromTopToBottom(treeRoot1)
print(newArray)
6、隔步长翻转
s = 'asdfghjk'
k = 2
for idx in range(0, len(s), 2*k):
s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:]
print(s)
一个字符串按照k步长分组,再进行反转
s = 'asdfghjk'
k = 3
for idx in range(0, len(s), k):
s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:]
print(s)