0

I am new to Python. I tried to come up with "Root Identification" from the list of data. But it doesn't work. Here is code that I have tried:

listData=["blackish", "blacken","blacked"]

The output I expect is:

root = [black] and suffixLi = ["ish", "en", "ed"] 

Rest of the code:

def root():
    i=0
    j=0
    string = ""
    for word in listData:
        for i in range(len(min(listData, key=len))-1):
            print(len(min(listData, key=len)))
            if (listData[i][j]==listData[i+1][j]):
                string=string+listData[i][j]
                print(listData[i][j])
                print(string)
            i=i+1
            j=j+1
    print(string)  
Logan Wayne
  • 6,001
  • 16
  • 31
  • 49
  • Could you edit your question to include the current output? – Rick Smith Sep 14 '15 at 22:55
  • Please ask a clear question. Provide the complete code and the output you got. What else did you try? For instance, what print statements or debugging trace did you use, and what did you get from that? – Prune Sep 14 '15 at 22:56
  • you are looking for the longest common prefix? – Padraic Cunningham Sep 14 '15 at 23:39
  • Sure to find the longest common prefix. If there is a unique word that has no common prefix, it identifies and lists in another list. – Marc Madebo Sep 15 '15 at 04:56
  • Ex. ["Working", "Worked", "Works", "Doing"] Then it finds the common prefix among the common words and finds the different word with no common prefix. – Marc Madebo Sep 15 '15 at 04:57

2 Answers2

0

In the if statement, the index i+1 is out of range. Correct your loop limit two lines earlier; you can't run "i" any farther than list_length-2, but you're trying to run it all the way to 6.

Also, you're incrementing i inside the loop that already controls its value; I think you're confused on how to handle loop indices.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

Presuming you want trying to find the common prefix:

def root_pre(l):
    root = ""
    for t in zip(*l):
        if not all(t[0] == s for s in t):
            break
        root += t[0]
    ln = len(root)
    pres = [s[ln:] for s in listData]
    return root, pres

print(root_pre(listData))
('black', ['ish', 'en', 'ed'])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thank you. It works. But one more thing to give suggesion: – Marc Madebo Sep 15 '15 at 03:45
  • What if I have a data like listData=["blackish", "blacken","blacked", "Cut"] and to produce : Prefix = ["blackish", "blacken","blacked"] and diff=[cut]. Thank you again!!!!!!! – Marc Madebo Sep 15 '15 at 04:01