Python实现PAT 1063. Set Similarity (25)

我不是女神ヾ 2022-06-05 12:05 247阅读 0赞

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%

解答

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

  1. def distinct(line):
  2. line.sort()
  3. dline = [e for i, e in enumerate(line) if i == 0 or (i != 0 and e != line[i - 1])]
  4. return dline
  5. N=int(input())
  6. dlines=[]
  7. for i in range(N):
  8. line0=input().split(' ')[1:]
  9. line=[int(e) for e in line0]
  10. dlines.append(distinct(line))
  11. M=int(input())
  12. for i in range(M):
  13. ab = input().split(' ')
  14. a=int(ab[0])-1
  15. b=int(ab[1])-1
  16. lineab=dlines[a]+dlines[b]
  17. ld=len(distinct(lineab))
  18. r=(len(dlines[a])+len(dlines[b])-ld)/ld*100
  19. print ('%.1f%%'%r)

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

发表评论

表情:
评论列表 (有 0 条评论,247人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PAT A1063

    ![clipboard.png][] 这里面还是用到了set去重,还是要多掌握stl的用法; 这里注意一个巧妙地处理; 由于我们寻找的时两个集合a,b的不重复元素,

    相关 PAT A1063

    ![clipboard.png][] 这里面还是用到了set去重,还是要多掌握stl的用法; 这里注意一个巧妙地处理; 由于我们寻找的时两个集合a,b的不重复元素,