Hello
Hello

Reputation: 37

Create a function in Python that generates a 2-column array counting the substring occurence in each element of a list and the length of each element?

There are two lists, string and query, both containing strings. I want to create a function that returns a 2D array showing:

For example, if we have

As:

So the function should return the array [[3, 2], [1, 3], [1, 2]]

I have tried the following:

def countstuff(string, query)
 result = []
 for i in query:
  array = [[sum(i in j for j in string], len(i)]]
  result.append(array)
 return result

But before I get to try the function, it returns SyntaxError: invalid syntax.

I can't get my head around this, please help, thank you.

Upvotes: 1

Views: 49

Answers (3)

Bibhav
Bibhav

Reputation: 1757

Simple way to do it:

string = ['om', 'om', 'omg']
query = ['om', 'omg', 'mg']

def countstuff(strings, queries):
    result=[]
    string = " ".join(strings)

    for query in queries:
        count= string.count(query)
        length = len(query)
        result.append([count,length])

    return result
        
print(countstuff(string,query))

Output:

[[3, 2], [1, 3], [1, 2]]

Upvotes: 1

Hello
Hello

Reputation: 37

Hi after fiddling some more, I found another solution, thanks everyone.

def countstuff(string, query):
    result = []
    for i in query:
        array = [sum(i in j for j in string)]
        array.append(len(i))
        result.append(array)
    return result

Upvotes: 1

nariman zaeim
nariman zaeim

Reputation: 490

def countstuff(string, query):
    result = []
    
    for i in query:
        ocr=0
        for j in string:
            ocr+=j.count(i)
        lst=[ocr,len(i)]
        result.append(lst)
    return result        
        

string = ['om', 'om', 'omg']
query = ['om', 'omg', 'mg']
print(countstuff(string,query))

have fun :)

Upvotes: 2

Related Questions