python学习(13)
2021-06-22 08:06
标签:odi 执行 参数 算法 common 自身 out letter last >> random.uniform(1,20) 习题1:生成[“z1”,”y2”,”x3”,”w4”,”v5”] #coding=utf-8 习题2:拼接一个字符串的首字母、末尾字母、中间字母为一个字符串 方式1:直接拼字符串 方式2:利用列表 切片没有越界 >> s = "a" >> a = [1] >> a = [1] >> a = [1] >> a >> a[0] = [55,66] >> a[0:5] = [1] 习题3:S = “i am, a boy ”把boy替换为m 算法:先把字符串转换为列表 习题4:非递归实现生成斐波那契数列 习题5:非递归实现求第n项斐波那契数列值 习题6:递归求两个数的最大公约数 算法: 找出两个数的较小数(第一次) ?????? 方式2:更相减损法 方式3:辗转相除法 习题7:利用递归,处理嵌套列表,生成列表[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 引用传参: python学习(13) 标签:odi 执行 参数 算法 common 自身 out letter last 原文地址:http://blog.51cto.com/13496943/2177529
随机生成a,b之间的一个浮点数
1.0130916166719703#coding=utf-8
result = []
for i in range(1,6):
result.append(chr(122-i+1)+str(i))
print(result)
result = []
for i in range(1,6):
result.append(chr(97+i-1)+str(i))
print(result)
要考虑奇数偶数长度,如果只有1个2个字母的字符串s = "abcdefghig"
result_str = ""
result_str += s[0]
if len(s)%2 == 1:
middle_letter = s[len(s)//2]
else:
middle_letter = s[len(s)//2-1]
middle_letter += s[len(s)//2]
print(middle_letter)
result_str += middle_letter
result_str += s[-1]
print("拼接后的字符串: ",result_str)
def join_str(s):
result = []
result.append(s[0])
if len(s)%2==1:
result.append(s[len(s)//2])
else:
result.append(s[len(s)//2-1])
result.append(s[len(s)//2])
result.append(s[-1])
return "".join(result)
s = "abcdefghig"
s2 = "abcdefghi"
print("拼接后的字符串: ",join_str(s))
print("拼接后的字符串: ",join_st
>> s[5:] #没有越界
‘‘
>> s[5]
Traceback (most recent call last):
File "
IndexError: string index out of range
>> a[0:1] = [1,2,3,4]
>> a
[1, 2, 3, 4]
>> a =[1]
>> a[0:2] = [1,2,3,4]
>> a
[1, 2, 3, 4]
>> a[0]
1
>> a[0] = [1,2,3,4]
>> a
[[1, 2, 3, 4]]
>> a[0:7]
[1]
>> a[0:7] = [1,2,3,4]
>> a
[1, 2, 3, 4]
[1, 2, 3, 4]
>> a[0:2] = [7,8,9,10]
>> a
[7, 8, 9, 10, 3, 4]
>> a
[[55, 66], 8, 9, 10, 3, 4]
>> a
[1, 4]
利用切片赋值特性
遍历列表,找到boy字符串
替换boy字符串为m#coding=utf-8
s = "i am, a boy!!"
list_s = list(s)
sub_length = len("boy")
for i in range(len(list_s)):
if "".join(list_s[i:i+sub_length]) == "boy":
list_s[i:i+sub_length] = "m"#可以用切片直接替换
print("".join(list_s))
#coding=utf-8
def fib(n):
result = []
if n
算法:遍历n,如果n等于0或1直接返回1
如果n >=2,记录前面两个项的和,并重新记录新的第1个,第2个数;
#coding=utf-8
def fib(n):
a,b=1,1
sum = 0
if n
方式1:
如果两个数除以较小数余数都等于0的话,添加到一个列表中
不然的话继续调用函数自身,并且num-1传入到num参数中。def max_common_divisor(a,b,num=0,result=[]):
if num == 0:
if a
def get(small,big):
if small > big:
small,big = big,small
if small == big:
return small
return get(small,big-small)
print(get(30,24))
def?gain(small,?big):
????if?small?>?big:
????????small,?big?=?big,?small
????if?small?==?0:
????????return?big
????return?gain(small,?big?%?small)
定义全局变量:(尽量不使用全局变量)l = [1,2,[3,4,[5,6,7,[8,9,[10,11]]]]]
result = []
def func(p):
global result
for v in p:
if not isinstance(v,list):
result.append(v)
else:
func(v)
return result
print(func(l))
def get_list(l,result=[]):
for v in l:
if not isinstance(v,list):
result.append(v)
else:
get_list(v)
return result
l = [1,2,[3,4,[5,6,7,[8,9,[10,11]]]]]
print(get_list(l))