File: weighted_rr.py

package info (click to toggle)
python-roundrobin 0.0.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 116 kB
  • sloc: python: 140; makefile: 5
file content (40 lines) | stat: -rw-r--r-- 1,119 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
try:
    from math import gcd
except ImportError:
    from fractions import gcd


# python2 workaround for python3 nonlocal keyword
class Store:
    __slots__ = ('index', 'weight')

    def __init__(self, index, weight):
        self.index = index
        self.weight = weight


def weighted(dataset):
    current = Store(index=-1, weight=0)

    dataset_length = len(dataset)
    dataset_max_weight = 0
    dataset_gcd_weight = 0

    for _, weight in dataset:
        if dataset_max_weight < weight:
            dataset_max_weight = weight
        dataset_gcd_weight = gcd(dataset_gcd_weight, weight)

    def get_next():
        while True:
            current.index = (current.index + 1) % dataset_length
            if current.index == 0:
                current.weight = current.weight - dataset_gcd_weight
                if current.weight <= 0:
                    current.weight = dataset_max_weight
                    if current.weight == 0:
                        return None
            if dataset[current.index][1] >= current.weight:
                return dataset[current.index][0]

    return get_next