Kurumi3
Kurumi3

Reputation: 61

How to compare strings in two lists and create a third of the matches?

How to compare the value in a string list with another value in a string list and if I do succeed in comparing with 2 of the lists, how can I store a new value in a new list if the value in the string lists is matches?

def start_game():
    food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
    random_food_list = [random.choices (food_list, k = 4)]
    player_guess_list = []
    correct_guess_list = []

    for i in range(1,5):
        player_guess = input("food" + str(i) + ":").lower()
        if player_guess not in food_list:
            print("Invalid foods, Restart Again")
            start_game()
        else:
            player_guess_list.append(player_guess)
    print(player_guess_list) # For review
    print(random_food_list) # For review

For example:

User input list = [salad, steak, noodles, rice]
randomized list = [salad, rice, salad, rice]
correct_guess_list = [O,X,X,O]

Output

Correct food in correct place: 2
Correct food in wrong place: 2

Upvotes: 1

Views: 120

Answers (4)

habrewning
habrewning

Reputation: 1069

The question is quite unclear. The example looks like you want to compare two lists and create a third list that stores where the first two lists are identical.

This can be done this way:

user_input_list = ["salad", "steak", "noodles", "rice"]
randomized_list = ["salad", "rice",  "salad",   "rice"]
  
new_list = list(map(lambda x, y : 'O' if x == y else 'X', \
                    user_input_list,                      \
                    randomized_list))
   
correct_food_in_correct_place = new_list.count('O')
correct_food_in_wrong_place = new_list.count('X')

print(new_list)
print(correct_food_in_correct_place)
print(correct_food_in_wrong_place)

The lambda function is not required. You may prefer the same with a regular function:

user_input_list = ["salad", "steak", "noodles", "rice"]
randomized_list = ["salad", "rice",  "salad",   "rice"]

def matches(x,y):
  return 'O' if x == y else 'X'

new_list = list(map(matches, user_input_list, randomized_list))
   
correct_food_in_correct_place = new_list.count('O')
correct_food_in_wrong_place = new_list.count('X')

print(new_list)
print(correct_food_in_correct_place)
print(correct_food_in_wrong_place)

The good of this last solution is that it is very explicit and intuitive that you have divided the problem into a smaller problem: You first implement the mechanism for a single element. You give this a name, which makes it easier to understand and to test. Once this works, you can combine it to work with lists. You can do this by hand with a loop as you did. But the sort of situations, where you want to apply something to all elements of a list and generate a new list is very common. So Python gives you the map function, which does this for you.

Whether you you prefer list comprehensions (as in the other answer) or the map function is your choice. Unless there are no other requirements I recommend the solution that is easier to read for you.

Upvotes: 3

martineau
martineau

Reputation: 123473

You can do what you by using a single list comprehension of the values in the two list zipped together.

food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
#random_food_list = random.choices(food_list, k = 4)
random_food_list = ['salad', 'rice', 'salad', 'rice']  # Hardcode for testing.

correct_guess_list = ['O' if f1.lower() == f2.lower() else 'X'
                        for f1, f2 in zip(food_list, random_food_list)]

print(correct_guess_list)  # -> ['O', 'X', 'X', 'O']

correct_food_in_correct_place = correct_guess_list.count('O')
correct_food_in_wrong_place = correct_guess_list.count('X')

print(f'Correct food in correct place: {correct_food_in_correct_place}')  # -> 2
print(f'Correct food in wrong place: {correct_food_in_wrong_place}')  # -> 2

Upvotes: 4

Sanket Wagh
Sanket Wagh

Reputation: 166

One problem I see in your anser is you are creating a list of list rather than list to compare with in the first place random.choices (food_list, k = 4) returns a list so no need to enclose it in square brackets. Now both the types will be list and you can use indexing to compare values from both list.

import random
def start_game():
    food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
    random_food_list = random.choices (food_list, k = 4)
    player_guess_list = []

    correct_guess_list = []

    for i in range(1,5):
        player_guess = input("food" + str(i) + ":").lower()
        if player_guess not in food_list:
            print("Invadlid foods, Restart Again")
            start_game()
        else:
            player_guess_list.append(player_guess)

    print(player_guess_list) # For review
    
    print(random_food_list) # For review
    for i in range(0 , len(random_food_list)):
        if random_food_list[i] == player_guess_list[i]:
            correct_guess_list.append(random_food_list[i])
    print(correct_guess_list)
start_game()

Upvotes: 2

Raed Ali
Raed Ali

Reputation: 587

I made the correct guesses list using a list comprehension:

correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
                          player_guess_list]

Full code:

import random


def start_game():
    food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
    random_food_list = random.choices(food_list, k=4)
    player_guess_list = []
    correct_guess_list = []
    correct_guesses = 0

    for i in range(1, 5):
        player_guess = input("food" + str(i) + ":").lower()
        if player_guess not in food_list:
            print("Invalid foods, Restart Again")
            start_game()
        else:
            player_guess_list.append(player_guess)
            if player_guess_list[i-1] == random_food_list[i-1]:
                correct_guesses += 1
        print(player_guess_list)  # For review
        print(random_food_list)  # For review
    correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
                          player_guess_list]
    print(correct_guess_list)
    print(f"Food in correct place: {correct_guesses}")
    print(f"Food in incorrect place: {4 - correct_guesses}")


start_game()

Upvotes: 2

Related Questions