Siddhesh Agarwal
Siddhesh Agarwal

Reputation: 189

Sort by occurence

Given a list of strings (arr) and a character/word (w), write a function s_sort(arr, w) to sort the list according to the number of times w appears in a string of the list.

arr = ['q q q', 'q', 'q q', 'a']
w = 'q'
print(s_sort(arr, w))

would give:

['q q q', 'q q', 'q', 'a']

and

arr = ['bug', 'bug bug', '#', 'bug bug bug bug']
w = 'bug'
print(s_sort(arr, w))

would give:

['bug bug bug bug', 'bug bug', 'bug', '#']

Upvotes: 1

Views: 87

Answers (3)

Shadowcoder
Shadowcoder

Reputation: 972

Try this:

arr = ['bug', 'bug bug', '#', 'bug bug bug bug']
w = 'bug'
out = sorted(arr, key=lambda item: -item.split().count(w))
print(out)  # -> ['bug bug bug bug', 'bug bug', 'bug', '#']

Upvotes: 2

Jonas Palačionis
Jonas Palačionis

Reputation: 4842

The current answers only work if you have the same word in the arr. Here is code that works for any items in the arr:

def fn(arr,w):
    ord_lst = []
    for x in arr:
        ord_lst.append(x.count(w))
    return [x for _,x in sorted(zip(ord_lst,arr),reverse=True)]

arr = ['bug', 'bug bug', '# c c c c c c c', 'bug bug bug bug']
w = 'bug'
fn(arr,w)
# ['bug bug bug bug', 'bug bug', 'bug', '# c c c c c c c']

Upvotes: 1

newbieprogrammer
newbieprogrammer

Reputation: 115

def s_sort(arr, w):
  def myFunc(e):
    return e.split(" ").count(w)
  
  arr.sort(key=myFunc, reverse=True)
  return arr

The code above should work.

Upvotes: 1

Related Questions