I'm trying to use recursion to find the closest numbers in a list. I made a program that runs correctly without any errors but I want to know if there's a better way to write my program while still using recursion.
This is my program:
deff = -1
num1 = 0
num2 = 0
def closest(List):
global deff, num1, num2
deff1 = -1
if deff == -1:
deff = max(List) - min(List)
deff1 = max(List) - min(List)
if len(List) == 1:
deff = -1
return [num1, num2]
if abs(List[0] - List[1]) <= deff:
deff = abs(List[0] - List[1])
num1 = List[0]
num2 = List[1]
return closest(List[1:])
This is my Tester Program:
from recursion import *
allPassed = True
def closestMain():
global allPassed
testCases = [(1, [3, 7, 67, 68, 210, 215], [67, 68]),
(2, [3, 7, 67, 168, 210, 215], [3, 7]),
(3, [3, 47, 67, 168, 210, 215], [210, 215]),
(4, [3, 7], [3, 7]),
(5, [3, 3, 3, 3, 3, 3], [3, 3]),
(6, [1, 2, 3, 4, 5, 6], [5, 6]),
(7, [5, 10, 100, 105, 305, 310], [305, 310]),
(8, [5, 10, 15], [10, 15])]
for num, L, expected in testCases:
result = closest(L)
if result != expected:
print(f'Closest Test {num} Failed. Expected {expected} got {result}')
allPassed = False
def main():
closestMain()
if allPassed:
print('All tests passed')
main()
Again no errors, the program works fine, just trying to see if there's a better way to do it using recursion.