Python:使用列表中的item作为函数参数

时间:2017-01-13 03:54:29

标签: python

我必须对此puzzle进行编程并解决它(我使用的是100个硬币而不是26个),而且目前我所有的都是:

def flip():
    if (coin == 0):
        coin = 1
    if (coin == 1):
        coin = 0

def move():
    table_one.remove(coin)
    table_two.append(coin)

def CoinPuzzle():
    table_one = [[1]*20 + [0]*80]
    table_two = []
    #Move 20 coins from table_one to table_two
    #Flip all 20 coins in table_two
    #Both tables should have an equal number of 1s

我很难将单个硬币对象与列表中的项目链接,以便我可以执行翻转和移动功能。我是Python的新手,有人可以指导我如何做到这一点吗?

新编辑:如果我有这样的输入,我应该如何修改代码:

L=[0]*100
for i in random.sample(range(100),20):
   L[i]=1
[L1,L2]=tables(L)

2 个答案:

答案 0 :(得分:3)

这是一个小的python实现:

import random
heads_count = 20
total_coins = 100

table_one = [True] * heads_count + [False] * (total_coins-heads_count)
table_two = []

def flip(table, coin):
    table[coin] = not table[coin]

def move_random():
    coin = random.randint(0, len(table_one)-1)
    table_two.append(table_one[coin])
    del table_one[coin]

for i in range(heads_count):
    move_random()

for i in range(heads_count):
    flip(table_two, i)

print(sum(table_one))
print(sum(table_two))

答案 1 :(得分:2)

这是斯蒂芬的版本的替代品。为了使输出更容易阅读,我将使用原始拼图中的数字。

我们使用heads_count函数在一个步骤中随机化table_one中的硬币顺序,然后使用切片将table_two个硬币从from random import seed, shuffle # seed the randomizer so we get repeatable results seed(42) total_coins = 26 heads_count = 10 # Put all the coins in table_one and randomize their order table_one = [1] * heads_count + [0] * (total_coins - heads_count) shuffle(table_one) print('Initial') print('Table one:', table_one, sum(table_one), len(table_one)) # move heads_count coins to table_two table_one, table_two = table_one[heads_count:], table_one[:heads_count] #flip all the coins in table_two table_two = [1 - coin for coin in table_two] print('Final') print('Table one:', table_one, sum(table_one), len(table_one)) print('Table two:', table_two, sum(table_two), len(table_two)) 移动到{{} 1}}。为了翻转硬币,我们使用1 - 0 = 1和1 - 1 = 0的事实。

Initial
Table one: [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1] 10 26
Final
Table one: [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1] 8 16
Table two: [1, 1, 1, 0, 0, 1, 1, 1, 1, 1] 8 10

<强>输出

table_one, table_two = table_one[heads_count:], [1 - coin for coin in table_one[:heads_count]]

我们甚至可以将最后两个步骤合并为一个语句:

{{1}}