0

I've written a code using for loop to store and check individual letters from a list to find if there are common letters as prefixes. If the list is ['flower', 'flow', 'flight'], the expected result is 'fl' but I'm only able to get just 'f' back.

I've written down every step and procedure I needed to take such as returning +1 for each time a match is found in a list and if the count matches the len of the list, the result is to be appended into the stored list. However, the code seems to be able to run only just once without iterating upon itself without making the letter check increment and running the check across the list again. I'm at a loss for what needs to be done. Below this line is my code and I would love pointers on how to optimize or write my code better!:

inp_list = ['flower', 'flow', 'flight'] #input
pre_list = []                           #Main place holder for True duplicates
temp_list = []                          #Temp Place holder for testing if True
T_Count = 0

inp_list.sort(key=len, reverse=True)    #sort longest to shortest to determine longest string

for l in range(len(inp_list[0])):       #to loop no. of times based on largest len of                 string in list
k = 0
chk_list = [inp_list[0][k]]         #set variable letter from 1st element to checklist
temp_list = pre_list + chk_list
for a in range(len(inp_list)):      #for no. of elements in list (3)
    x = len(temp_list)              #len of temp_list/x determines start:stop of which values to check (1)
    for b in range(1):              #one check on each item
        check = [inp_list[a][:x]]   #checking a item from start to x (First loop: 0th element, 0:1 = i0)
        if temp_list == check:      #if temp = check, T_Count + 1
            T_Count += 1

if T_Count == len(inp_list):           #if no. of +1 = to len of inp_list, all items matches temp
    pre_list.append(chk_list)          #therefore, add chk_list into pre_list
    k += 1                             #chk_list to move on to next letter to add into temp_list for checking
    T_Count = 0

pre_list = "".join(str(pre_list))
print(f"Current Prefix: {pre_list}")

0 Answers0