Home > Software engineering >  Number of occurrences in Python using dictionary
Number of occurrences in Python using dictionary

Time:10-24

I have the following exercise:

Text is given in a single line. For each word of the text count the number of its occurrences before it. For simplicity, we assume there are no numbers, punctuation, or special symbols in the input. Consecutive words are separated from each other by one or more spaces.

The exercise is asking explicitly to use dictionaries.

Input:

the block on the block on the block on the floor

Output:

0 0 0 1 1 1 2 2 2 3 0

The code so far:

my_words={} 
s = input()
nums_str = s.split()

count=0
for x in nums_str:
  my_words.update({count:0})
  count= count 1
the block on the block on the block on the floor
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0}

This prints out a dictionary with a number as index for each words and a zero.

The idea is use use it to record the position of each word before itself.

This is what I do not understand how to record the position of each word before itself.

CodePudding user response:

In order to achieve this, you need to get the values of counter after each iteration. Also, to make this code reusable everywhere, you can create a function out of it, as follows:

def dynamic_counter(sequence, delimiter=' '):
    word_dict, count_list = {}, []
    for word in sequence.split(delimiter):
        count_list.append(word_dict.get(word, 0))
        word_dict[word] = word_dict.get(word, 0)   1
    return count_list


sentence = "the block on the block on the block on the floor"
print(*dynamic_counter(sentence))

CodePudding user response:

A dictionary alone won't do the trick. If you add a list you can gather the current wordcount there.

The idea is to check if the word is in the dictionary. If not then add it and set the value to 0. If it is there then increase the value by 1. Then use the current added or updated value.

s = 'the block on the block on the block on the floor'

words = {}
counts = []
for word in s.split():
    if word not in words:
        words[word] = 0
    else:
        words[word]  = 1
    counts.append(words[word])

print(counts)

Result: [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 0]


If you don't need to gather the output for further tasks you can drop the list and just print the current value.

s = 'the block on the block on the block on the floor'
words = {}
for word in s.split():
    if word not in words:
        words[word] = 0
    else:
        words[word]  = 1
    print(words[word], end=' ')

Same approach with a dictionaries get method and a default value. (You can see a similar approach in mousetail's answer)

words = {}
for word in s.split():
    words[word] = words.get(word, -1)   1
    print(words[word], end=' ')

CodePudding user response:

Solution with simple dict:

words = input().split()
count = {}
for word in words:
    print(count.get(word, 0), end=" ") # print earlier words
    count[word]=count.get(word, 0)   1 # increase the counter

CodePudding user response:

It's not clear why you have to use a dictionary. Without the aid of a dictionary, you can just do this:

mystring = 'the block on the block on the block on the floor'
mywords = mystring.split()
outlist = [mywords[:i].count(w) for i, w in enumerate(mywords)]
print(outlist)

If you need a dictionary in the format shown in your question then:

mystring = 'the block on the block on the block on the floor'
mywords = mystring.split()
mydict = {k: v for k, v in enumerate([mywords[:i].count(w) for i, w in enumerate(mywords)])}
print(mydict)

CodePudding user response:

This is the solution from the university, the code is quite simple. The exercise is about learning dictionaries, so it is recommended to use it.

words = input().split()

d = {}

for word in words:
  if word in d:
    d[word] =1
  else:
    d[word] = 0
  print(d[word], end = " ")

  • Related