Dilraj
Dilraj

Reputation: 1

How can you check if a list with string values is similar to another list?

I’m trying to write an algorithm that takes a sample order (string) and extract food name and quantity size from it.

The issue I’m running into is, if the sample order contains plural version of the food my algorithm does not count it as a match. For example, if it’s searching for banana and it finds bananas doesn’t consider it as banana.

Look how my code can get the correct output for sample_order1 but not sample_order2

sample_order1 = 'Can I have a mango and three banana'
sample_order2 = 'Can I have a mango and three bananas'
output for sample_order1 = {'mango': 'one', 'banana': 'three'} <- correct
output for sample_order2 = {'mango': 'one'} <- incorrect (should be the same output as sample_order1 )

Here is my code:

# List of items served in the restraunt
food_names = ['banana', 'orange', 'apple', 'mango']

# Sample orders
sample_order1 = 'Can I have a mango and three banana'
sample_order2 = 'Can I have a mango and three bananas'

number = ['one', 'two', 'three', 'four', 'five']
final = {}


def order_format(sample_order, num_list, final_output):
    prev_pointer = 0
    current_pointer = 0
    so_fixed = sample_order.split()

    for num in range(0, len(so_fixed)):
        # checks if current word is in list of food names
        if so_fixed[current_pointer] in food_names:
            # if numbers from 0 - current pointer identify food or last identified food to current identified food
            # has a number anywhere in front of food
            for i in range(prev_pointer,current_pointer):
              if so_fixed[i] in num_list:
                new_quantity = so_fixed[i]
                # {found food : quantity of order}
                final_output[so_fixed[current_pointer]] = new_quantity
              else:
                # {found food : default quantity of 1}
                final_output[so_fixed[current_pointer]] = "one"
            prev_pointer = current_pointer
            current_pointer += 1
        else:
            current_pointer += 1
    return final_output


if any(word in sample_order1 for word in food_names):
    order_format(sample_order1, number, final)
    print(final)
# clear final{}
final = {}
if any(word in sample_order2 for word in food_names):
    order_format(sample_order2, number, final)
    print(final)

Upvotes: 0

Views: 65

Answers (1)

Faraaz Kurawle
Faraaz Kurawle

Reputation: 1160

Your Problem is your program does not detect the pural of the words right?

to slove that problem you can use for-loop and if statements to and the purals

Heres the code:

for i in range(len(food_names)):
    if food_names[i] in sample_order2 or f"{food_names[i]}s" in sample_order2 or f"{food_names[i]}es" in sample_order2 or f"{food_names[i]}'s" in sample_order2 or f"{food_names[i]}'es" in sample_order2:
        # You can place your code here

Upvotes: 2

Related Questions