34 lines
1.1 KiB
Python
Executable File
34 lines
1.1 KiB
Python
Executable File
import random
|
|
|
|
# We want this array to be sorted from smallest to greatest
|
|
# We will be adding random numbers from 1 -> 10 into this array
|
|
# There are two ways we could do this:
|
|
#
|
|
# 1) We append 10 random numbers and then we sort it once we're done
|
|
#
|
|
# 2) Every time we append a random number, we determine where it should go so that
|
|
# once it's added the arry is still ordered
|
|
#
|
|
# Evidently, method 1 is banned by the assignment so let's implement part two
|
|
arr = []
|
|
|
|
for _ in range(10):
|
|
random_num = random.randrange(0, 11)
|
|
|
|
if len(arr) == 0:
|
|
# Add the first element into the array if it's empty
|
|
arr.append(random_num)
|
|
else:
|
|
# We must determine the right index before adding into the array
|
|
for i in range(len(arr)):
|
|
if arr[i] > random_num:
|
|
# We insert right before the number that's larger than it
|
|
arr.insert(i, random_num)
|
|
break
|
|
|
|
if i == len(arr) - 1:
|
|
# This is the largest number yet so we can just append it
|
|
arr.append(random_num)
|
|
|
|
print(arr)
|