1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Why is my Python code returning a list of characters instead of items?

Discussão em 'Python' iniciado por Stack, Outubro 25, 2024 às 10:22.

  1. Stack

    Stack Membro Participativo

    Question:

    I'm trying to solve the following problem: given two arrays of strings list1 and list2, find the common strings with the least index sum.

    A common string is a string that appeared in both list1 and list2. A common string with the least index sum is a common string such that if it appeared at list1 and list2[j] then i + j should be the minimum value among all the other common strings. I need to return all the common strings with the least index sum.

    Here's the code that I've written so far:

    class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
    res = []
    smallest_n = float('inf')
    for i in range(len(list1)):
    if list1 in list2:
    res.append(list1)
    if len(res) == 0:
    return False
    if len(res) == 1:
    return res.pop()
    if len(res) > 1:
    for i in range(len(res)):
    n = list1.index(res) + list2.index(res)
    if n < smallest_n:
    smallest_n = n
    result = []
    for i in range(len(res)):
    n = list1.index(res) + list2.index(res)
    if n == smallest_n:
    result.append(res)
    return result


    My issue is that the code is returning a list of characters instead of items. How can I modify my code so that it returns the expected list of items instead?

    Any help would be greatly appreciated!

    I tried to return a list of the least index sum string with each item being a word, but instead, I returned the (correct) result as a list of characters of the word.

    I attempted to change the result.append(res) to result.append(str(res), but I got the same result.

    Edit: an example of an input with unexpected results would be:

    Input:
    ["Shogun","Tapioca Express","Burger King","KFC"]
    ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
    Output:
    ["S","h","o","g","u","n"]
    Expected:
    ["Shogun"]


    Edit: thank you very much for all the help, the error was using .pop() to return the only value in the list rather than the list itself.

    Continue reading...

Compartilhe esta Página