파이썬 질문있습니다.
import random
def QuickSort(aList, start, end): if start < end: pivot = partitionRand(aList, start, end) QuickSort(aList, start, pivot -1) QuickSort(aList, pivot + 1, end)
def partitionRand(aList, start, end): # pivot을 랜덤하게 뽑기 위해서 사용 rand_pivot = random.randrange(start, end, 1) aList[start], aList[rand_pivot] = aList[rand_pivot], aList[start] return partition(aList, start, end)
def partition(aList, start, end): leftM = start + 1; rightM = end; while True: while (leftM < end)and(aList[leftM] < aList[start]): leftM += 1; while (start < rightM)and(aList[start] < aList[rightM]): rightM -= 1; if leftM >= rightM: break; aList[leftM], aList[rightM] = aList[rightM], aList[leftM] leftM += 1; rightM -= 1; aList[start], aList[rightM] = aList[rightM], aList[start] return rightM def QuickSelect(aList, start, end, s): pivot = partitionRand(aList, start, end) if s < pivot: return QuickSelect(aList, start, pivot - 1, s); elif pivot < s: return QuickSelect(aList, pivot + 1, end, s); else: return aList[pivot]; dataList = [2,0,2,0,1,2,3,4,5,6] QuickSort(dataList, 0, len(dataList) - 1) print(dataList) if len(dataList) % 2 == 0: # 데이터 개수가 홀수, 짝수일때 모두 만족하도록 조건문을 사용 resultValue1 = QuickSelect(dataList, 0, len(dataList) - 1, (len(dataList)/2) - 1) resultValue2 = QuickSelect(dataList, 0, len(dataList) - 1, len(dataList)/2) Median = (resultValue1 + resultValue2) / 2 else: resultValue = QuickSelect(dataList, 0, len(dataList) - 1, len(dataList)//2) Median = resultValue print("중앙값(median):",Median)
--------------------------------------------------------------------------------------------------------
퀵소트와 퀵셀렉트를 이용한 이용하여 데이터의 중앙값을 구하는 코드를 작성하였습니다.
그런데 코드를 실행할때마다
정상적으로 실행이 되기도하고 ValueError: empty range for randrange() (5,5, 0) 오류가 뜨기도 합니다.
어떻게 오류를 해결할 수 있을까요
답변 1개
답변을 작성하려면 로그인이 필요합니다.
로그인