forked from das-jishu/algoexpert-data-structures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-three-largest-numbers.py
51 lines (43 loc) · 1.14 KB
/
find-three-largest-numbers.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# FIND THREE LARGEST NUMBERS
# SOLUTION 1
def findThreeLargestNumbers(array):
# Write your code here.
i = 0
while i < 3:
pos = i
largest = array[pos]
j = i + 1
while j < len(array) - 1:
if array[j] > largest:
largest = array[j]
pos = j
j += 1
temp = array[i]
array[i] = array[pos]
array[pos] = temp
i += 1
return [array[2], array[1], array[0]]
# SOLUTION 2
def findThreeLargestNumbers(array):
# Write your code here.
largestNumbers = [None, None, None]
for elem in array:
print(largestNumbers)
checkAndUpdate(array, elem, largestNumbers)
return largestNumbers
def checkAndUpdate(array, num, largestNumbers):
if largestNumbers[2] is None or num > largestNumbers[2]:
updateResult(largestNumbers, num, 2)
elif not largestNumbers[1] or num > largestNumbers[1]:
updateResult(largestNumbers, num, 1)
elif not largestNumbers[0] or num > largestNumbers[0]:
updateResult(largestNumbers, num, 0)
else:
pass
def updateResult(largestNumbers, num, index):
print("Uppdate result")
for i in range(index+1):
if i == index:
largestNumbers[i] = num
else:
largestNumbers[i] = largestNumbers[i+1]