#编写一个函数findstr(),该函数统计一个长度为2的子字符串在另一个字符串中出现的次数。
# 例如假定输入的字符串为:
# Don't aim for success if you want it; just do what you love and believe in, and it will come naturally
#子字符串为“it”,函数执行后打印:子字符串在目标字符串中出现2次。
方法1:
def findstr(x,y):
lx=list(x)
ly=list(y)
num=0 #出现次数
lengthx=len(x) #原始字符串长度
lengthy=len(y) #字符串长度
for i in range(lengthx):
#print(i)
if lx[i]==ly[0] and lx[i+1]==ly[1]:
num+=1
return num
x1=input("请输入原始字符串:")
y1=input("请输入要查找的字符串:")
num1=findstr(x1,y1)
print(y1,"在原始字符串中出现",num1,"次")
#列表,元组和字符串,他们之间的互相转换使用三个函数,str(),tuple()和list(),具体示例如下所示:
# >>> s = "xxxxx"
# >>> list(s)
# ['x', 'x', 'x', 'x', 'x']
# >>> tuple(s)
# ('x', 'x', 'x', 'x', 'x')
# >>> tuple(list(s))
# ('x', 'x', 'x', 'x', 'x')
# >>> list(tuple(s))
# ['x', 'x', 'x', 'x', 'x']
#列表和元组转换为字符串则必须依靠join函数
# >>> "".join(tuple(s))
# 'xxxxx'
# >>> "".join(list(s))
# 'xxxxx'
# >>> str(tuple(s))
# "('x', 'x', 'x', 'x', 'x')"
方法二:
def findstr(x,y):
num=0 #出现次数
lengthx=len(x) #原始字符串长度
if y not in x:
print("在目标字符串中未找到字符串")
else:
for i in range(lengthx-1):
#print(i)
if x[i]==y[0] and x[i+1]==y[1]:
num+=1
print(y1, "在原始字符串中出现%d次"%num)
x1=input("请输入原始字符串:")
y1=input("请输入要查找的字符串:")
num1=findstr(x1,y1)
# 编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值。
#方法1
def power(x,y):
m=1
i=0
while i <y:
m=m*x
i+=1
return m
m1=power(2,3)
print(m1)
# 方法2
def power(x,y):
result =1
for each in range(y): #range(y) #代表从0到y(不包含y)0,1,2
print(each)
result *= x
return result
r1=power(2,3)
print(r1)
#编写一个函数,利用欧几里得算法求最大公约数,
# 例如gcd(x, y)返回值为参数x和参数y的最大公约数。
#http://blog.csdn.net/canhui_wang/article/details/50760510
def gcd(x, y):
while y:
t = x % y
x = y
y = t
return x
print(gcd(8, 12))
#编写一个将十进制转换为二进制的函数,
# 要求采用“除2取余”的方式,
# 结果与调用bin()一样返回字符串形式。
def Dec2Bin(dec):
temp = []
result = ''
while dec:
quo = dec % 2
dec = dec // 2
temp.append(quo)
while temp:
result += str(temp.pop())
return result
print(Dec2Bin(62))
往期笔记