1. 程式人生 > >2018網易校招-字串碎片

2018網易校招-字串碎片

題目描述:

一個由小寫字母組成的字串可以看成一些同一字母的最大碎片組成的。例如,”aaabbaaac”是由下面碎片組成的:’aaa’,’bb’,’c’。

牛牛現在給定一個字串,請你幫助計算這個字串的所有碎片的平均長度是多少。

輸入描述:

輸入包括一個字串s,字串s的長度length(1length50),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函式是一個比較好選擇。