Home > Software engineering >  How to accept data from a frequency table in python
How to accept data from a frequency table in python

Time:10-29

I need help on how to get a list of data from two different inputs, a value input and a frequency input. I think i could do it by creating a dictionary and adding the values and frequencies to it in the form {v:f,v:f,v:f} etc., but I don't know how to do that.

e.g.

values = First, enter or paste the VALUES, separated by spaces: frequencies = Now enter the corresponding FREQUENCIES separated by spaces:

It should take each number - separated by spaces - and add it in to the dictionary so say if values = 1 2 3 4 5 and frequencies = 5 4 3 2 1 the dictionary should be {1:5,2:4,3:3,4:2,5:1} meaning 1 appears 5 times, 2 appears 4 times, 3 appears 3 times, 4 appears 2 times, and 5 appears once. and a list from that should be [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]

I tried mucking around with for loops and i think i will have to use one or two but im not sure how

CodePudding user response:

you can do this by Counter

from collections import Counter
lst = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]
print(Counter(lst))

>>> Counter({1: 5, 2: 4, 3: 3, 4: 2, 5: 1})

CodePudding user response:

do you need something like this?

dictionary = dict(zip(list(input('values = First, enter or paste the VALUES, separated by spaces: ').split(' ')),list(input('frequencies = Now enter the corresponding FREQUENCIES separated by spaces: ').split(' '))))

dictionary = [k for k,v in dictionary.items() for _ in range(v)]

print(dictionary)   #[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5] if you input '1 2 3 4 5' and '5 4 3 2 1'
  • Related