Home > Software design >  Yield a list of matching elements from 2 different lists
Yield a list of matching elements from 2 different lists

Time:11-16

I have a (somewhat long) list of words. And a function 1 (linsok(lista, elem)) which asks the user for a word, and if the user-inputted word exists in the list, we get a confirmation in the form of exists/does not exist.

I then have a 2nd function which for any word in the list will create 4 variations of it (creating 4 concatenations of each word) and append these new words to another list. This function will come in handy in my third function, which I am having trouble constructing.

My third function will compare the words in my original list, to the list of my concatenated words. If any word in the concatenated list exists in my orginal list, the function should yield these matches in a list (in the form of [original word, concatenated word] where both are present in the original list). All with the caveat that this third function is to include a function call for the 1st function which asks for user input of a word and produces a confirmation of the word's existence.

I have tried to write the function in the form of for item1 in list 2 and for item2 in list 2 but honestly in pretty lost as to how to construct the function. Especially how/where I am to insert my function call to the first function.

This is the code as it stands now:

`

########## UPPGIFT 1 ##########

#fil = open('ordlista.txt')

lista = open('ordlista.txt').read().split()


#print(lista[::100])


########## UPPGIFT 2 #########

def linsok(lista, elem):            #function 1 which returns whether or not a word is present in list
   if elem in lista:
       print(elem   ' exists')
       return True
   else:
       print(elem   ' exists not')
       return False


########## UPPGIFT 3 ##########

def kupering(ord):                   #function which concatenates the words in question
    nylista = []
    if ord in lista:
        for i in range(len(ord)):
            nylista.append((ord[i:len(ord)]   ord[:i]))
        #nylista=nylista[1:]
        #print(nylista)
        return nylista


#def linsok_kup(lista):                 #funtion 3 which i have trouble with






# def main():
#     while elem := input('Ditt ord: '):
#         linsok(lista,elem)                  #u2
# 
# #where i would insert my 3rd function
# 
# if __name__ == '__main__':
#     main()

`

CodePudding user response:

Your explanation is a little unclear but here goes.

Assuming concantenation as in your function is correct.

cat -> [(catc),(catca),(catcat)]

You can simply use a dict to save a lot of time.

def kupering(ord,mydict):
    nylista = []
    if ord in lista:
        for i in range(min(len(ord),3)):
            nylista.append(ord[i:len(ord)]   ord[:i])
            try:
                mydict[ord[i:len(ord)]   ord[:i]].append(ord) #child has not been made before
            except:
                mydict[ord[i:len(ord)]   ord[:i]] = [ord] #concantenated word has been made before
return nylista, mydict #we return your 'list' and also our 'dict of children and their parents'

The dict now contains all your 'root' words and their children.

This then forces the condition that if the child exists, yield result IFF parent exists.

def new_function(user_input, mydict,lista):
    test = linsok(user_input,lista) #use your function to see if word exist
    if test == True:
       #I guess we want if this is true
       eval = mydict[user_input] 
       if len(eval)==0: #Case were it doesnt exist in 'concantenated words"
           print("I do not exist in children")
           return None #leave the fucntion with nothing
       outputs = []
       for word in eval: #alternate case is if it does exist
            result = linsok(lista,word) #do parent of word exist in lista
            if result == True:
                print([eval,user_input]) #if yes we add to our outputs
                output.append([eval,user_input])
       return output
                
    else:
         return None
   #Covers scenario where a child can have multiple parents I think. abab -> ababa,ababab... , aba -> abab, ababa,ababab....

CodePudding user response:

From your description, I'm not sure what the result of linsok() in the third functions is used for.

I also assume that all the words in lista are at least four characters long, since a word with less than four characters would not give 4 variations.

lista = ["hello", "dogs", "cars", "scar"]
concact_lst = kupering("cars")

def third_func(concact_lst):
    user_input = input("Enter word: ")
    word_exists = linsok(lista, user_input)
    
    result = []
    for i in range(len(concact_lst)):
        for j in range(len(lista)):
            if concact_lst[i] == lista[j]:
                result.append([lista[j], concact_lst[i]])
    return result

print(third_func(concact_lst))

output: [['cars', 'cars'], ['scar', 'scar']]

  • Related