Python实现PAT 1063. Set Similarity (25)

来源:互联网 发布:java float与double 编辑:程序博客网 时间:2024/06/14 19:05

1063. Set Similarity (25)

Given two sets of integers, the similarity of the sets is defined to be Nc/Nt*100%, where Nc is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

Input Specification:

Each input file contains one test case. Each case first gives a positive integer N (<=50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (<=104) and followed by M integers in the range [0, 109]. After the input of sets, a positive integer K (<=2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.

Output Specification:

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

Sample Input:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
Sample Output:
50.0%
33.3%

解答

题目本身比较简单,但是循环用多了,容易超时啊!

def distinct(line):    line.sort()    dline = [e for i, e in enumerate(line) if i == 0 or (i != 0 and e != line[i - 1])]    return dlineN=int(input())dlines=[]for i in range(N):    line0=input().split(' ')[1:]    line=[int(e) for e in line0]    dlines.append(distinct(line))M=int(input())for i in range(M):    ab = input().split(' ')    a=int(ab[0])-1    b=int(ab[1])-1    lineab=dlines[a]+dlines[b]    ld=len(distinct(lineab))    r=(len(dlines[a])+len(dlines[b])-ld)/ld*100    print ('%.1f%%'%r)

有一个结果超时了。
这里写图片描述

原创粉丝点击