I am absolutely clueless because I ran this code earlier and it worked fine. I don’t remember changing anything. Once I enter my input it returns empty but is still running the program.
import random
print("This program finds the smallest difference between any two elements in"+
" a randomly generated list of integers, using two different algorithms with"+
" different Big-O efficiency.\n")
min_ran = int(input("Enter random min range:"))
max_ran = int(input("Enter random max range:"))
len_list = int(input("Enter length of list:"))
counter = 1
output_list = []
while counter <= len_list:
output_list.append(random.randint(min_ran,max_ran))
def algorithm1():
diff = 10**20
for i in range(len_list-1):
for j in range(i+1,len_list):
if abs(output_list[i]-output_list[j]) < diff:
diff = abs(output_list[i]-output_list[j])
return diff
def algorithm2():
mid = len_list // 2
list1 = output_list[:mid]
list2 = output_list[mid:]
list1.sort()
list2.sort()
ans = 10**20
i = j = 0
while i < len(list1) and j < len(list2):
ans = min(ans,abs(list1[i]-list2[j]))
if list1[i] < list2[j]:
i += 1
else:
j +=1
return ans
print("\nList:",output_list)
print("List length:",len_list)
print(algorithm1())
print(algorithm2())
>Solution :
you don’t change your counter. it will cause an infinite loop.
counter = 1
output_list = []
while counter <= len_list:
output_list.append(random.randint(min_ran,max_ran))
try:
output_list = [random.randint(min_ran,max_ran) for x in range(0,len_list)]
side note: I’d recommend using some kind of version control software such as git in order to avoid unwanted changes that cause small logical bugs.