找到集合 P 中的所有 ”最大“ 點的集合
阿新 • • 發佈:2020-10-23
題目描述
P為給定的二維平面整數點集。定義 P 中某點x,如果x滿足 P 中任意點都不在 x 的右上方區域內(橫縱座標都大於x),則稱其為“最大的”。求出所有“最大的”點的集合。(所有點的橫座標和縱座標都不重複, 座標軸範圍在[0, 1e9) 內)
如下圖:實心點為滿足條件的點的集合。請實現程式碼找到集合 P 中的所有 ”最大“ 點的集合並輸出。
例子:
input:
5
1 2
5 3
4 6
7 5
9 0
output:
4 6
7 5
9 0
程式碼實現
#!/usr/bin/env python # -*- encoding: utf-8 -*- class MaxPointDraw: def__init__(self): self.xy = [] self.max_x = 0 self.max_y = 0 def generateCoordinateCollection(self): number = int(input('please input a number(1 <= number <= 10000):')) for i in range(number): input_xy = input() x = int(input_xy.split('')[0]) y = int(input_xy.split(' ')[1]) if x > self.max_x: self.max_x = x if y > self.max_y: self.max_y = y self.xy.append([x, y]) def checkIsMaxPoint(self, xy_args): x = xy_args[0] y = xy_args[1]for xy_list in self.xy: x_value = xy_list[0] y_value = xy_list[1] if x_value > x and y_value > y: return False return True def Output(self): print('--------------------') for xy_list in self.xy: x_value = xy_list[0] y_value = xy_list[1] if self.checkIsMaxPoint(xy_list): print(' '.join(['%s'%xy for xy in xy_list])) if __name__ == "__main__": mpd = MaxPointDraw() mpd.generateCoordinateCollection() mpd.Output()
輸出:
please input a number(1 <= number <= 10000):5
1 2
5 3
4 6
7 5
9 0
--------------------
4 6
7 5
9 0
拓展
使用matplotlib來展示效果,以及隨機生成一個點集合:
#!/usr/bin/env python # -*- encoding: utf-8 -*- from random import randint import matplotlib.pyplot as plt class MaxPointDraw: def __init__(self): self.xy = [] self.max_x = 0 self.max_y = 0 # generate CoordinateCollection def generateCoordinateCollection(self): number = int(input('please input a number(1 <= number <= 10000):')) for i in range(number): x = randint(0, number) y = randint(0, number) if x > self.max_x: self.max_x = x if y > self.max_y: self.max_y = y self.xy.append([x, y]) # check the point is Max or not def checkIsMaxPoint(self, xy_args): x = xy_args[0] y = xy_args[1] for xy_list in self.xy: x_value = xy_list[0] y_value = xy_list[1] if x_value > x and y_value > y: return False return True # show the MaxPoint result def DrawPaint(self): fig = plt.figure() ax = fig.add_subplot(111) ax.set(xlim=[0, self.max_x+self.max_x//2], ylim=[0, self.max_y+self.max_y//2], title='Max Point Set', ylabel='Y-Axis', xlabel='X-Axis') for xy_list in self.xy: x_value = xy_list[0] y_value = xy_list[1] if self.checkIsMaxPoint(xy_list): plt.scatter([x_value], [y_value], color='red') else: plt.scatter([x_value], [y_value], color='blue') plt.show() if __name__ == "__main__": mpd = MaxPointDraw() mpd.generateCoordinateCollection() mpd.DrawPaint()
input1:
please input a number(1 <= number <= 10000):10
result1:
input2:
please input a number(1 <= number <= 10000):50
output2:
效果就是上面的樣子,複製程式碼後執行前需要pip installmatplotlib 不然會找不到這個包。