J
J
jamesStr2021-10-20 14:29:39
Programming
jamesStr, 2021-10-20 14:29:39

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

4 answer(s)
G
Griboks, 2021-10-20
@Griboks

In python, this is very easy to do.
len(x)/x.count(1)

V
Vladimir Kuts, 2021-10-20
@fox_12

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))

# [0, 0, 0, 0, 1, 0, 0, 0, 0, 1] --> 5.0
# [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0] --> 3.142857142857143

G
Grigory Boev, 2021-10-20
@ProgrammerForever

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; // Соотношение нулей к единицам

I
ikutin666, 2021-10-20
@ikutin666

here in js

const getPeriodicity=(arr)=>
{
  let counter=0;
  let summ=0;
  let len=0
  for(let i in   arr)
  {
    let e=arr[i];
    
    if(e===1)
    {
      counter+=2;
    }
    else if(+i!==0){
      summ+=counter;
      len++;
      counter=0;
    }
  }
  return summ/len;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question