dondakeshimoの丸太

データサイエンス/Webアプリケーション/

なんかルールは平等でも貧富の差って生まれるらしいのでPythonに本当か聞いてみた

ツイートでこんなの見かけました。

ちょっと実装してみました。

コード

import numpy as np
import sys
from tqdm import tqdm


def release_coin(people):
    random = np.random.rand() * 6 + 0.5
    random = np.round(random)

    if random == 1:
        people["person1"] -= 1
    elif random == 2:
        people["person2"] -= 1
    elif random == 3:
        people["person3"] -= 1
    elif random == 4:
        people["person4"] -= 1
    elif random == 5:
        people["person5"] -= 1
    elif random == 6:
        people["person6"] -= 1
    else:
        print("error")
        print(random)

    return people


def get_coin(people):
    random = np.random.rand() * 6 + 0.5
    random = np.round(random)

    if random == 1:
        people["person1"] += 1
    elif random == 2:
        people["person2"] += 1
    elif random == 3:
        people["person3"] += 1
    elif random == 4:
        people["person4"] += 1
    elif random == 5:
        people["person5"] += 1
    elif random == 6:
        people["person6"] += 1
    else:
        print("error")
        print(random)

    return people


def validation(people):
    total = sum(people.values())

    if total == 600:
        return True
    else:
        return False


def main(loop_num):
    people = {"person1": 100,
              "person2": 100,
              "person3": 100,
              "person4": 100,
              "person5": 100,
              "person6": 100}

    for _ in tqdm(range(loop_num)):
        people = release_coin(people)
        people = get_coin(people)
        val = validation(people)

        if val:
            continue
        else:
            print("error")
            print(people)

    print(people)


if __name__ == "__main__":
    arg = int(sys.argv[1])
    main(arg)

辞書型にした理由は謎です。
乱数生成で +0.5をしばらく忘れていて痛い目にあった以外はすんなり行った気がします。

結果

% python static_disparity.py 1000000
100%|████████████████████████████████████████████████████| 1000000/1000000 [00:15<00:00, 64672.29it/s]
{'person1': 312, 'person2': 21, 'person3': 125, 'person4': -240, 'person5': -383, 'person6': 765}

% python static_disparity.py 1000000
100%|████████████████████████████████████████████████████| 1000000/1000000 [00:15<00:00, 64060.44it/s]
{'person1': 602, 'person2': -757, 'person3': -302, 'person4': 853, 'person5': -183, 'person6': 387}

% python static_disparity.py 1000000
100%|████████████████████████████████████████████████████| 1000000/1000000 [00:18<00:00, 53485.54it/s]
{'person1': -225, 'person2': -295, 'person3': -51, 'person4': -68, 'person5': 696, 'person6': 543}

まじで貧富の差が生まれていた。 一度きりの人生大変だと感じました。