List Comparison Issue

The main issue I am having with this code is I need to compare a randomized list of people, so that it is like, this person vs this person, but it cannot be the same person because I don’t want the person to ‘fight themselves’ if you will. I just need to figure out how to reorient my code, so that it is always two different people fighting from the list given.

import random

def boxerOptions ():
  boxers = ['James', 'Albert', 'Walli', 'Jimmy', 'Tyson', 'Echo', 'Will', 'Brownman', 'Walter', 'Luke', 'Dominic']
  firstBoxer = random.randrange(0,len(boxers))
  secondBoxer = random.randrange(0, len(boxers))
  print ("\n"+ boxers[firstBoxer] + " vs " +  boxers[secondBoxer])
  return firstBoxer 
  return secondBoxer
boxerOptions()
1 Like
import random

def boxerOptions ():
  boxers = ['James', 'Albert', 'Walli', 'Jimmy', 'Tyson', 'Echo', 'Will', 'Brownman', 'Walter', 'Luke', 'Dominic']
  firstBoxer = random.randrange(0,len(boxers))
  secondBoxer = random.randrange(0, len(boxers))
  if firstBoxer != secondBoxer:
    print ("\n"+ boxers[firstBoxer] + " vs " +  boxers[secondBoxer])
    return firstBoxer 
    return secondBoxer
boxerOptions()

As a quick side note, I’d look at how you’re using return. Currently your first one returns firstBoxer and so the second one never has a chance to run. Perhaps use a tuple?

def foo():
  return (1, 2)

print(foo()) # prints (1, 2)

My first instinct would be to use .pop() to remove the first boxer from the list so he’s not paired with himself.

import random

def pair(boxers):
  helper = lambda boxers: boxers.pop(random.randrange(0, len(boxers)))
  return (helper(boxers), helper(boxers))

boxers = ['James', 'Albert', 'Walli', 'Jimmy', 'Tyson', 'Echo', 'Will', 'Brownman', 'Walter', 'Luke', 'Dominic']

boxer1, boxer2 = pair(boxers)
print(f"{boxer1} will fight {boxer2}")
print(boxers)

However there may be an issue with this. Running the code you’ll notice that boxers was modified by the function, and is short the two boxers. This can be remedied by either passing a copy of boxers to the function with list(), or copying it in the function:

def pair(boxers):
  boxers = list(boxers)
  helper = lambda boxers: boxers.pop(random.randrange(0, len(boxers)))
  return (helper(boxers), helper(boxers))
1 Like

The improvement works, but whenever a duplicate is found, it just freezes. I can reload more, but is there any way I could have a different string of two people printed if there is a duplicate?

1 Like

Ok, thank you so much! I will try and work on this more, but I needed to figure out how to do this.

1 Like