while 循环判断 出错
def func(S, length):res = ''
while length>0:
for j in S:
res += j if j != ' ' else '%20'
length -= 1
return res
l = func('aa bbbbccccc', 13)
print(l)#aa%20bbbb%20%20ccccc%20%20
请教大家一道算法题,为什么这个外层的while length > 0没有对for循环起到限定作用
因为你 length 在 for 循环内,每次 for 循环执行一次 都会导致 length - 1
而你 while 循环的条件是 > 0 当你的 S 字符串参数为 'aa bbbbccccc' 此时字符串中字符个数为 16
所以 for 循环遍历 S 字符串时,会遍历 16 次,而你传入的 length = 13,导致 length 在一次完整的 for 循环后就为 13-16 = -3 ,即不满足 while 条件 ,所以此时直接退出 while 循环了
我之前写过一个清除多余空白字符(空格, Tab)的函数,去除头尾和连续重复的,你要不要
页:
[1]