2024 年春晚刘谦魔术第二部分的简单 python 实现(测试)

非常简单方便的python,非常简单的代码,不到百行,仅此纪念龙年春晚。

import random
import sys

DEBUG = "--debug" in sys.argv


def debug(*args, **kwargs):
    if DEBUG:
        print(*args, **kwargs)


def proxy(val):
    color = random.choice(["spades", "hearts", "diamonds", "clubs"])
    if not 0 < val < 10:
        val = {0: "A", 10: "J", 11: "Q", 12: "K"}[val]
    return f"{color}_{val}"


def get_random_cards():
    cards = []
    for _ in range(4):
        val = proxy(random.randint(0, 12))
        while val in cards:
            val = proxy(random.randint(0, 12))
        cards.append(val)
    debug(cards)
    return cards


def cut_cards(cards):
    for i in range(len(cards)):
        cards.append(f"{cards[i]}_down")
        cards[i] = f"{cards[i]}_up"
    debug(cards)
    return cards


def choice_insert(cards, cnt):
    rand_idx = random.randint(cnt + 1, len(cards) - 2)
    cards[rand_idx:rand_idx] = cards[:cnt]
    del cards[:cnt]
    debug(cards)
    return cards


def move(cards):
    cards.append(cards[0])
    del cards[0]
    debug(cards)


def liuqian_magic(inputs):
    # 0->n: up->down
    cards = cut_cards(get_random_cards())
    # m1
    cards += cards[: inputs["name_len"]]
    del cards[: inputs["name_len"]]
    debug(cards)
    # m2
    choice_insert(cards, 3)
    # d1
    actual = cards[0].rsplit("_", 1)[0]
    del cards[0]
    debug(cards)
    # m3
    choice_insert(cards, inputs["region"] + 1)
    # d2
    del cards[: inputs["sex"] + 1]
    # j z q j d s k -> cnt: 7
    for _ in range(7):
        move(cards)
    lucky = True
    while len(cards) != 1:
        if lucky:
            move(cards)
        else:
            del cards[0]
        lucky = not lucky
    expected = cards[0].rsplit("_", 1)[0]
    debug(expected, actual)
    return expected == actual


def main():
    inputs = {
        "sex": random.randint(0, 1),
        "region": random.randint(0, 2),
        "name_len": random.randint(2, 8),
    }
    debug(inputs)
    assert liuqian_magic(inputs)


if __name__ == "__main__":
    times = DEBUG and 3 or 1000
    for _ in range(times):
        main()
``

你可能感兴趣的:(python)