티스토리 뷰
Coursera Algorithm 강의 첫번째 과제. 단순하게 mergesort를 이용해서 순서를 정할때 거꾸로 정리되는 경우의 수를 체크하는 문제였다.
mergesort를 쓰게 되면 기존에 O(n^2)의 complexity가 O(nlogn)으로 떨어진다.
def readFile(filename, l): with open(filename, "r") as f: for line in f: l.append(int(line)) if f.closed == False: f.close() def sortAndCount(A): mid = len(A) // 2 if len(A) == 1: return A, 0 B, x = sortAndCount(A[:mid]) C, y = sortAndCount(A[mid:]) D, z = mergeAndCountSplitInv(B, C, len(A)) return D, x + y + z def mergeAndCountSplitInv(B, C, n): D = [] i = 0 j = 0 inverse = 0 for k in range(n): if i == len(B): D.append(C[j]) j += 1 elif j == len(C): D.append(B[i]) i += 1 else: if B[i] < C[j]: D.append(B[i]) i += 1 else: D.append(C[j]) inverse += len(B[i:]) j += 1 return D, inverse x = 0 y = 0 test = [] readFile("IntegerArray.txt", test)
print sortAndCount(test)[1]
'Hobby > Code' 카테고리의 다른 글
[C] fifteen game (0) | 2014.05.26 |
---|---|
[C] vigenere cipher (1) | 2014.05.25 |
[C] Caesar Cipher (1) | 2014.05.25 |
[ruby] Rock-Paper-Scissors class (0) | 2014.05.19 |
[ruby] Very simple class for dessert (0) | 2014.05.19 |
[Ruby] Palindrome, dictionary, anagram (0) | 2014.05.18 |
[C] n squared matrix 덧셈 (0) | 2014.05.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- RL
- 한빛미디어
- bias
- Expression Blend 4
- Gan
- Offline RL
- Variance
- processing
- 파이썬
- Policy Gradient
- End-To-End
- Kinect
- 인공지능
- Pipeline
- DepthStream
- arduino
- Kinect SDK
- Kinect for windows
- Distribution
- SketchFlow
- Windows Phone 7
- windows 8
- ColorStream
- TensorFlow Lite
- PowerPoint
- dynamic programming
- reward
- 강화학습
- 딥러닝
- Off-policy
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함