Home > Software engineering >  Trying to match a range value within a list to user input
Trying to match a range value within a list to user input

Time:09-12

I'm trying to match the input value to a range value in a list. Like I have a list of games and a range of how many players per game. I'm trying to take the user input and return a game that falls in that category based on the range values in its list. If the user inputs 3 I'd like to print the options that all have a 3 within their range but this doesn't output anything. I'm assuming the if-statement output is false but I don't know how to correct it.


   
    games = [['Game 1' , 'short' , list(range(2,6))],['Game 2' , 'short' , list(range(2,7))],['Game 3' , 'long' , list(range(5,10))]]

    players = input('players?\n\n')

    options=[]
    for game in games:
        if game[2] == int((players)):
            options.append(game[0])
            print(options)

CodePudding user response:

Try this:

games = ['short', list(range(2,6))]
players = input('players\n')
for game in games[1]:
    if int(players) == game:
        print('yes')

Other simplest way to get same:

games_range = range(2,6)
players = int(input('players\n'))

if players in games_range:
    print("yes")

CodePudding user response:

A quick fix to your code includes two steps:

  1. Think about how you will add another game in your list.

    • Right now game first gets the value short and then the value [2,3,4,5]
    • One fix would be to make games a list of lists or a list of tuples e.g. games = [('short', list(range(2, 6))), ('shorter',list(range(2,4)))]
  2. Think about how you read the number of players.

    • Right now players is of type string
    • One fix would be to make an integer right after reading it e.g. players = int(input('players\n'))
  3. Think about how you check if a number is in a range

    • number == list_of_numbers will always be false
    • One fix would be to check if number in list_of_numbers:


This should be a comment but I don't have enough rep yet

This will get your code working, but then you can think of others ways to make it do what you want. Like, do you need to store the whole range of players or just the minimum and maximum values and check that the number given is between them? Or, will you print that there is a game that can be played with that many people, or print the names of the games?

CodePudding user response:

EDIT (OP's Code change)

Use in and list comprehension:

games = [['Game 1', 'short', list(range(2, 6))], ['Game 2', 'short', list(range(2, 7))],
         ['Game 3', 'long', list(range(5, 10))]]

players = input('players?\n\n')
options = [game[0] for game in games if int(players) in game[2]]
print(options)

# players? 6
# ['Game 2', 'Game 3']

# players? 5
# ['Game 1', 'Game 2', 'Game 3']

# players? 7
# ['Game 3']

# players? 2
# ['Game 1', 'Game 2']
  • Related