用代码解决刘谦春晚魔术

相信很多人都看过文字解释了,来一段代码看看

import random

def step_move_one(length, array):
    while length > 0:
        length -= 1
        array = array[1:] + array[:1]
    return array

def step_firstN_to_middle(firstN, array):
    if firstN < 0 or firstN > len(array):
        return "Error: firstN is out of array"
    firstN_items = array[:firstN] # delete the former N
    remained_array = array[firstN:]
    if len(remained_array) > 0:
        random_position = random.randint(1, len(remained_array) - 1)
    else:
        random_position = 0
    array = remained_array[:random_position] + firstN_items + remained_array[random_position:]
    return array

def trying():
    array = ["A", "B", "C", "D"]
    random.shuffle(array)
    print(f"1.打乱:{array}")
    array += array
    print(f"2.复制列表拼在一起:{array}")
    array = step_move_one(random.randint(2, 99), array)
    print(f"3.根据名字依次移动N项到末尾:{array}")
    array = step_firstN_to_middle(3, array)
    print(f"4.取前三张插入到中间任意位置:{array}")
    star = array[0]
    array = array[1:]
    print(f"5.取值:{star},剩余的列表:{array}")
    array = step_firstN_to_middle(random.randint(1, 3), array)
    print(f"6.取前N张卡片插入到中间随机位置:{array}")
    array = array[random.randint(1, 2):] # male:1 and female:2
    print(f"7.丢掉前N张卡片后:{array}")
    array = step_move_one(7, array)
    print(f"8.依次移动首张牌到末尾,重复7次:{array}")
    while len(array) > 1:
        array = array[1:] + array[:1]; print(f"9.好运留下来:{array}")
        array.pop(0); print(f"9.烦恼丢出去:{array}")
    print(f"10.结束辣: 之前存的牌:{star}, 现在的牌:{array[0]}")

trying()

image

posted @ 2024-02-10 17:13  诩言Wan  阅读(89)  评论(0编辑  收藏  举报