Home > Mobile >  Python, how to find patterns of different length and to sum the number of match
Python, how to find patterns of different length and to sum the number of match

Time:02-03

I have a list like that:hg = [['A1'], ['A1b'], ['A1b1a1a2a1a~'], ['BT'], ['CF'], ['CT'], ['F'], ['GHIJK'], ['I'], ['I1a2a1a1d2a1a~'], ['I2'], ['I2~'], ['I2a'], ['I2a1'], ['I2a1a'], ['I2a1a2'], ['I2a1a2~'], ['IJ'], ['IJK'], ['L1a2']]

For example, if we look at :['A1'] ['A1b'] ['A1b1a1a2a1a~']

I want to count how many time the pattern 'A1','A1b' and 'A1b1a1a2a1a~' occurs. Basically, A1 appears 3 times (A1 itself, A1 in A1b and A1 in A1b1a1a2a1a) and A1b two times (A1b itself and A1b in A1b1a1a2a1a) and A1b1a1a2a1a one time. Obviously, I want to do that for the entire list. However, if in the list we have for example E1b1a1, I don't want to count a match of A1 in E1b1a1. So what I did is:

dic_test = {}                   
for i in hg:
   for j in hg:
      if ''.join(i) in ''.join(j):
         if ''.join(i) not in dic_test.keys():
            dic_test[''.join(i)]=1
         else:
            dic_test[''.join(i)] =1
print (dic_test)

output:{'A1': 3, 'A1b': 2, 'A1b1a1a2a1a~': 1, 'BT': 1, 'CF': 1, 'CT': 1, 'F': 2, 'GHIJK': 1, 'I': 12, 'I1a2a1a1d2a1a~': 1, 'I2': 7, 'I2~': 1, 'I2a': 5, 'I2a1': 4, 'I2a1a': 3, 'I2a1a2': 2, 'I2a1a2~': 1, 'IJ': 3, 'IJK': 2, 'L1a2': 1}

However, as explained above, there is one issue. For example, F should be equal at one and not 2. The reason is because with the code above, I look for F anywhere in the list. But I don't know how to correct that!

There is a second thing that I don't know how to do: Based on the output: {'A1': 3, 'A1b': 2, 'A1b1a1a2a1a~': 1, 'BT': 1, 'CF': 1, 'CT': 1, 'F': 2, 'GHIJK': 1, 'I': 12, 'I1a2a1a1d2a1a~': 1, 'I2': 7, 'I2~': 1, 'I2a': 5, 'I2a1': 4, 'I2a1a': 3, 'I2a1a2': 2, 'I2a1a2~': 1, 'IJ': 3, 'IJK': 2, 'L1a2': 1}

I would like to sum the values of the dic based on shared pattern: example of the desired output{A1b1a1a2a1a~: 6, 'BT': 1,'CF': 1, 'CT': 1, 'F': 1, 'GHIJK': 1, 'I1a2a1a1d2a1a~': 13, I2a1a2:35, 'IJK': 5, 'IJK': 5}:

For example, A1b1a1a2a1a = 6 it's because it is made by A1 which has a value of 3, A1b with a value of 2 and the value of A1b1a1a2a1a equal at 1. I don't know how to do that. Any helps will be much appreciated!

Thanks

CodePudding user response:

  1. You count 'F' twice because you are iterating over the product of hg and hg so that the condition if ''.join(i) in ''.join(j) happens twice for 'F'. I solved that by checking the indexes.

  2. You mentioned in the comment that the pattern should be at the beginning of the string so in doesn't work here. You can use .startswith() for that.

I first created a dictionary from the items but sorted(That's important for your second question about summing the values). They all start with the value of 1. Then I iterated over the the items, increased the value only if they are not in the same position.

For the second part of your question, because they are sorted, only the previous items can be at the beginning of the next items. So I got the pairs with .popitem() which hands the last pair (in Python 3.7 and above) and check its previous ones until the dictionary is empty.

hg = [['A1'], ['A1b'], ['A1b1a1a2a1a~'], ['BT'], ['CF'], ['CT'], ['F'], ['GHIJK'], ['I'], ['I1a2a1a1d2a1a~'], ['I2'], ['I2~'], ['I2a'], ['I2a1'], ['I2a1a'], ['I2a1a2'], ['I2a1a2~'], ['IJ'], ['IJK'], ['L1a2']]

# create a sorted dicitonary of all items each with the value of 1.
d = dict.fromkeys((item[0] for item in sorted(hg)), 1)

for idx1, (k, v) in enumerate(d.items()):
    for idx2, item in enumerate(hg):
        if idx1 != idx2 and item[0].startswith(k):
            d[k]  = 1

print(d)
print("-----------------------------------")

# last pair in `d`
k, v = d.popitem()
result = {k: v}
while d:
    # pop last pair in `d`
    k1, v1 = d.popitem()

    # get last pair in `result`
    k2, v2 = next(reversed(result.items()))

    if k2.startswith(k1):
        result[k2]  = v1
    else:
        result[k1] = v1

print({k: result[k] for k in reversed(result)})

output:

{'A1': 3, 'A1b': 2, 'A1b1a1a2a1a~': 1, 'BT': 1, 'CF': 1, 'CT': 1, 'F': 1, 'GHIJK': 1, 'I': 11, 'I1a2a1a1d2a1a~': 1, 'I2': 7, 'I2a': 6, 'I2a1': 5, 'I2a1a': 4, 'I2a1a2': 3, 'I2a1a2~': 2, 'I2~': 2, 'IJ': 2, 'IJK': 1, 'L1a2': 1}
-----------------------------------
{'A1b1a1a2a1a~': 6, 'BT': 1, 'CF': 1, 'CT': 1, 'F': 1, 'GHIJK': 1, 'I1a2a1a1d2a1a~': 12, 'I2a1a2~': 27, 'I2~': 2, 'IJK': 3, 'L1a2': 1}

I think you made a mistake for your expected result and it should be like this, but let me know if mine is wrong.

CodePudding user response:

@S.B helped me to better understand what I wanted to do, so I did some modifications to the second part of the script.

I converted the dictionary "d" (re-named "hg_d") into a list of list:

hg_d_to_list = list(map(list, hg_d.items()))

Then, I created a dictionary where the keys are the words and the values the list of the words that matches with startswith() like:

nested_HGs = defaultdict(list)
for i in range(len(hg_d_to_list)):
   for j in range(i 1,len(hg_d_to_list)):
       if hg_d_to_list[j][0].startswith(hg_d_to_list[i][0]):
           nested_HGs[hg_d_to_list[j][0]].append(hg_d_to_list[i][0])

nested_HGs defaultdict(<class 'list'>, {'A1b': ['A1'], 'A1b1a1a2a1a': ['A1', 'A1b'], 'I1a2a1a1d2a1a~': ['I'], 'I2': ['I'], 'I2a': ['I', 'I2'], 'I2a1': ['I', 'I2', 'I2a'], 'I2a1a': ['I', 'I2', 'I2a', 'I2a1'], 'I2a1a2': ['I', 'I2', 'I2a', 'I2a1', 'I2a1a'], 'I2a1a2~': ['I', 'I2', 'I2a', 'I2a1', 'I2a1a', 'I2a1a2'], 'I2~': ['I', 'I2'], 'IJ': ['I'], 'IJK': ['I', 'IJ']})

Then, I sum each key and the value(s) associated to the dictionary "nested_HGs" based on the values of the dictionary "hg_d" like:

HGs_score = {}
for key,val in hg_d.items():
    for key2,val2 in nested_HGs.items():
        if key in val2 or key in key2:
            if key2 not in HGs_score.keys():
                HGs_score[key2]=val
            else:
                HGs_score[key2] =val

HGs_score {'A1b': 5, 'A1b1a1a2a1a': 6, 'I1a2a1a1d2a1a~': 12, 'I2': 18, 'I2a': 24, 'I2a1': 29, 'I2a1a': 33, 'I2a1a2': 36, 'I2a1a2~': 38, 'I2~': 20, 'IJ': 13, 'IJK': 14}

Here, I realized that I don't care about the key with a value = at 1.

To finish, I get the key of the dictionary that has the highest value :

final_HG_classification = max(HGs_score, key=HGs_score.get)

final_HG_classification=I2a1a2~

It looks like it's working! Any suggestions or improvements are more than welcome. Thanks in advance.

  • Related