I am trying to make a program that finds the maximum integer of a list, and the margin between the highest number and the second highest number. I want it to return these tuple values:
>>>max_margin([5,6,4,3])
(6, 1)
>>>max_margin([8, -2, 8, -3])
(8, 0)
>>>maxmargin([2])
(2, None)
>>>maxmargin([])
(None, None)
I have made code which accomplishes this, but It's not the best way to go about it. Here it is:
def max_margin(int_list):
if not int_list:
return None, None
else:
maxnum = nextval = int_list[0]
bymargin = None
for i in intlist:
if i > nextval:
nextval = i
if i > maxnum:
tmp = nextval
nextval = maxnum
maxnum = tmp
bymargin = maxnum - nextval
if maxnum == i and nextval == i:
maxnum = i
nextval = i
bymargin = maxnum - nextval
if len(int_list) <= 1:
maxnum = maxnum
bymargin = None
return maxnum, bymargin
Is there a better way to write this?