작성자 | marine12 | ||
---|---|---|---|
작성일 | 2020-05-13 17:15:42 KST | 조회 | 484 |
제목 |
파이썬 중앙값 찾기 출력 에러...
|
import heapq
class Median_Finder:
def __init__(self):
#initialize data structure
self.max_heap = []
self.min_heap = []
def add_Number(self, num):
#type num: int, rtype: void
if not self.max_heap and not self.min_heap:
heapq.heappush(self.min_heap, num)
return
if not self.max_heap:
if num > self.min_heap[0]:
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
heapq.heappush(self.min_heap, num)
else:
heapq.heappush(self.max_heap, -num)
return
if len(self.max_heap) == len(self.min_heap):
if num < -self.max_heap[0]:
heapq.heappush(self.max_heap, -num)
else:
heapq.heappush(self.min_heap, num)
elif len(self.max_heap) > len(self.min_heap):
if num < -self.max_heap[0]:
heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap))
heapq.heappush(self.max_heap, -num)
else:
heapq.heappush(self.min_heap, num)
else:
if num > self.min_heap[0]:
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
heapq.heappush(self.min_heap, num)
else:
heapq.heappush(self.max_heap, -num)
def find_Median(self):
#rtype: float
if len(self.max_heap) == len(self.min_heap):
return (-self.max_heap[0] + self.min_heap[0]) / 2
elif len(self.max_heap) > len(self.min_heap):
return -self.max_heap[0]
else:
return self.min_heap[0]
S = Median_Finder()
n= int(input().split())
A=[]
A.append(n)
for i in A:
s=int(input())
S.add_Number(i)
result = S.find_Median()
i+=1
print (result)
이 밑에 부분에서 막혔는데 제가 원하는 건 1,2,3,4,5 넣으면 1중앙값인 1, 12 중앙값인 1.5 123중앙값인 2 이런 식으로 다 나온 걸 더하는 건데 이 밑부분에서 막히네요... 출력을 어떻게 짜야 할까요? 간단한 거 같은데 아우
|
||
|
© PlayXP Inc. All Rights Reserved.