题目描述:
一个由小写字母组成的字符串可以看成一些同一字母的最大碎片组成的。例如,”aaabbaaac”是由下面碎片组成的:’aaa’,’bb’,’c’。
牛牛现在给定一个字符串,请你帮助计算这个字符串的所有碎片的平均长度是多少。
输入描述:
输入包括一个字符串s,字符串s的长度length(1 ≤ length ≤ 50),s只含小写字母('a'-'z')
输出描述:
输出一个整数,表示所有碎片的平均长度,四舍五入保留两位小数。
如样例所示: s = “aaabbaaac”
所有碎片的平均长度 = (3 + 2 + 3 + 1) / 4 = 2.25
输入例子1:
aaabbaaac
输出例子1:
2.25
解题方案:
import numpy as np
s=raw_input()
#s = "wwwwssffiuuuuusssssooooolllsssssshhhhcccchhhhhllo"
len_s=len(s)
temp=''
temp_list=[]
for i in range(len_s-1):
if s[i+1]==s[i]:
temp+=s[i]
else:
temp+=s[i]
temp_list.append(len(temp))
temp=''
if len(temp)==0:
temp_list.append(1)
else:
temp_list.append(len(temp)+1)
#print temp_list
#print str(round(float(sum(temp_list))/len(temp_list),2))
print format(float(sum(temp_list))/float(len(temp_list)),'.2f')
Tips: 这里值得注意的是 format这种保留两位小数的方法,我们常见的做法是利用python内置的round函数,round(x,2)来保留两位小数,但是在这题时会出现一个问题,如果x本身就是一位小数,那么无法保留两位小数。例如x=3.5, round(3.5,2)还是3.5无法实现 3.50的输出,因此使用format函数是一个比较好选择。