PAT 1104 Sum of Number Segments python解法

1104 Sum of Number Segments (20 分)
Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For example, given the sequence { 0.1, 0.2, 0.3, 0.4 }, we have 10 segments: (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) and (0.4).

Now given a sequence, you are supposed to find the sum of all the numbers in all the segments. For the previous example, the sum of all the 10 segments is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N, the size of the sequence which is no more than 105​​ . The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space.

Output Specification:
For each test case, print in one line the sum of all the numbers in all the segments, accurate up to 2 decimal places.

Sample Input:
4
0.1 0.2 0.3 0.4
Sample Output:
5.00

题意:给出一个序列,求出它的所有段总和(段:连续的子序列)。比如,给定序列{0.1,0.2,0.3,0.4},求出10个段:(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) 和 (0.4).然后求和: 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0,注意要保留2位小数,最终结果是5.00

解题思路:通过找规律,可以发现,0.1出现了4次,0.2出现了6次,0.3出现了6次,0.4出现了4次,结果就是0.1*4+0.2*6+0.3*6+0.4*4=5.00。如果扩展到n个数的序列,可以发现,第i个数出现了i*(n+1-i)次(如:0.1出现了1*4次,0.2出现了2*3次,0.3出现了3*2次,0.4出现了4*1次),因为索引从0开始,所以代码中是(n-i)*(i+1)次,接下来只需要求和就行了。

n = int(input())
l = list(map(float,input().split()))
s = 0
for i in range(len(l)):
        s += l[i]*(n-i)*(i+1)
print('%.2f'%s)

你可能感兴趣的:(python,用Python刷PAT,(Advanced,Level),Practice)