1
def value(x):

s = "Since 2012, Champion Data has boxed players in five categories, ranging from 'elite' to 'poor', based on a complicated formula assessing their most recent form. Players who have yet to debut, played only sparingly or are returning from long-term injuries (less than 10 games in two seasons) are placed in a sixth category named, appropriately, '?'. "

The aim is to sum up the indices of the different occurrences of the argument x in the text, and divide by the number of occurrences, and further divide by the length of the text. I've tried endlessly but can't seem to figure it out.

2
  • Can you add expected output too Commented Apr 2, 2015 at 12:40
  • The expected output would be a number from 0-1 indicating the distribution of the argument x Commented Apr 2, 2015 at 12:43

3 Answers 3

3

You can use enumeration to get the indices like:

indices = [i for i, j in enumerate(s) if x == j]

You can find the sum of indices as sum(indices), the number of occurrences as len(indices) and length of string as len(s)

Your final result can then be calculated as

return sum(indices)/(len(indices)*len(s))

Sign up to request clarification or add additional context in comments.

2 Comments

x (substring), not s (full text)
True. But if x could be a substring of length more than 1, we'd also need to know what happens in case x overlaps itself. Since OP didn't mention anything of that sort, I assumed x to be a character.
3

Here is your code:

import re

def count(sentence, st):
    indicies = [i.start() for i in re.finditer(st, sentence)]
    indicies_sum = sum(indicies)
    number_of_occurrences = len(indicies)
    text_len = len(sentence)
    return float(indicies_sum)/(number_of_occurrences*text_len)

1 Comment

This only finds non-overlapping occurrences of st. That may or may not matter as the original post does not specify what should happen when st can overlap itself.
1
def count(s, x):
    lx = len(x)
    slices = s.split(x)
    positions = [len(slice) + lx * n
                 for n, slice in enumerate(slices)]
    return float(sum(positions)) / len(s) / len(slices - 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.