Answer the question
In order to leave comments, you need to log in
How to write a function to calculate the frequency of occurrence of a digit in a series?
There is a random series of zeros where the numbers 1 interspersed with random intervals. For example [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0 , 0, 0, 0, 1, 0, 0]
Tell me how to write a function for calculating the frequency of occurrence of the number 1. That is, for example, a unit occurs on average every 2 positions, every 5 positions, every 1.5 positions, etc.
For the [0, 1, 0, 1, 0, 1, 0, 1] series, the frequency is 2 (one in every second position), but you need to calculate the average frequency for a random series with different intervals between 1.
Perhaps there is some formula, or tell me an example code, no matter what PL, you can even use pseudocode
Answer the question
In order to leave comments, you need to log in
If understood correctly:
from typing import Optional
def freq(arr: list, digit: int = 1) -> Optional[float]:
count = 1
res = []
for x in arr:
if x == digit:
res.append(count)
count = 0
count += 1
try:
return sum(res) / len(res)
except ZeroDivisionError:
return None
a = [0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
print(a, ' --> ', freq(a))
a = [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
print(a, ' --> ', freq(a))
let arr = [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0];
let p1 = arr.reduce((acc,val)=>acc+=val,0)/arr.length; // вероятность встретить 1
let p0 = 1 - p1; // вероятность встретить 0
let ratio10 = p1/p0; // Соотношение единиц к нулям
let ratio01 = p0/p1; // Соотношение нулей к единицам
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question