import random def find_max(list): max = list[0] # first entry for cur in list[1:]: # from 2nd entry on if max < cur: max = cur return max # finds max using tournament strategy def find_max2(list): # variable descriptions: # pairings: list of indexes of competitors in current round; # consecutive pairs of these compete in the round. # winners: list of indexes of winners in current round pairings = range(0,len(list)) num_cmps = len(pairings)/2 print list while num_cmps >= 1: winners = [] winners_vals = [] print "Round of", num_cmps*2 for i in range(0,num_cmps): idx1 = pairings[2*i] idx2 = pairings[2*i+1] if list[idx1] > list[idx2]: winners.append(idx1) winners_vals.append(list[idx1]) else: winners.append(idx2) winners_vals.append(list[idx2]) print "pairings: ", pairings print "winners: ", winners print "data: ", winners_vals pairings = winners num_cmps = num_cmps/2 return list[winners[0]] # finds max and 2nd max using tournament strategy def find_max_max2(list): # variable descriptions: # pairings: list of indexes of competitors in current round; # consecutive pairs of these compete in the round. # winners: list of indexes of winners in current round # losers: a dictionary of indexes of who lost to whom pairings = range(0,len(list)) num_cmps = len(pairings)/2 # how many comparisons for this round losers = {} for i in range(0,len(list)): losers[i] = [] print list while num_cmps >= 1: winners = [] winners_vals = [] # only used for output for debugging print "Round of", num_cmps*2 for i in range(0,num_cmps): idx1 = pairings[2*i] idx2 = pairings[2*i+1] if list[idx1] > list[idx2]: winners.append(idx1) winners_vals.append(list[idx1]) losers[idx1].append(idx2) else: winners.append(idx2) winners_vals.append(list[idx2]) losers[idx2].append(idx1) print "pairings: ", pairings print "winners: ", winners print "data: ", winners_vals pairings = winners num_cmps = num_cmps/2 # now index of winner is in winners[0] # now find 2nd max print losers[winners[0]] max2list = losers[winners[0]] max2idx = max2list[0] for idx in max2list[1:]: if list[idx] > list[max2idx]: max2idx = idx return (list[winners[0]],list[max2idx]) # creates a random list def random_list(n, min=0, max=9): list = [] # empty list for i in range(n): list.append( random.randint(min, max) ) return list def main(): #data = [ 1, 3, -5, 7, 0, -2, 2, 6 ] data = random_list(8) print data print "max, max2 are: \n", find_max_max2(data) #for i in range(1,len(data)-1): # cur = data[i] # for j in range(i-1,0): main()