簡體   English   中英

為什么教科書中的這個定義返回 2 個值?

[英]why do this defition in textbook return 2 values?

在這篇文章中,我將按順序做 3 件事:

A 介紹問題

B 在教科書中顯示這個問題的答案

C 顯示我的疑問


A 介紹問題

問題是這樣的:


(1) 制作一個包含一系列 10 個數字和五個字母的列表或元組。 從列表中隨機選擇 select 四個數字或字母,並打印一條消息,說任何匹配這四個數字或字母的彩票中獎;

(2) 制作一個包含一系列 10 個數字和 5 個字母的列表或元組。 從列表中隨機選擇 select 四個數字或字母,並打印一條消息,說明任何匹配這四個數字或字母的彩票都會中獎。


B 在教科書中顯示這個問題的答案

此答案代碼來自教科書:


(1)

from random import choice

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']

winning_ticket = []
print("Let's see what the winning ticket is...")

# We don't want to repeat winning numbers or letters, so we'll use a
#   while loop.
while len(winning_ticket) < 4:
    pulled_item = choice(possibilities)

    # Only add the pulled item to the winning ticket if it hasn't
    #   already been pulled.
    if pulled_item not in winning_ticket:
        print(f"  We pulled a {pulled_item}!")
        winning_ticket.append(pulled_item)

(2)

from random import choice

def get_winning_ticket(possibilities):
    """Return a winning ticket from a set of possibilities."""
    winning_ticket = []

    # We don't want to repeat winning numbers or letters, so we'll use a
    #   while loop.
    while len(winning_ticket) < 4:
        pulled_item = choice(possibilities)

        # Only add the pulled item to the winning ticket if it hasn't
        #   already been pulled.
        if pulled_item not in winning_ticket:
            winning_ticket.append(pulled_item)

    return winning_ticket


def make_random_ticket(possibilities):
    """Return a random ticket from a set of possibilities."""
    ticket = []
    # We don't want to repeat numbers or letters, so we'll use a while loop.
    while len(ticket) < 4:
        pulled_item = choice(possibilities)

        # Only add the pulled item to the ticket if it hasn't already
        #   been pulled.
        if pulled_item not in ticket:
            ticket.append(pulled_item)

    return ticket

def check_ticket(played_ticket, winning_ticket):
    # Check all elements in the played ticket. If any are not in the 
    #   winning ticket, return False.
    for element in played_ticket:
        if element not in winning_ticket:
            return False

    # We must have a winning ticket!
    return True

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = get_winning_ticket(possibilities)

plays = 0
won = False

# Let's set a max number of tries, in case this takes forever!
max_tries = 1_000_000

while not won:
    new_ticket = make_random_ticket(possibilities)
    won = check_ticket(new_ticket, winning_ticket)
    plays += 1
    if plays >= max_tries:
        break

if won:
    print("We have a winning ticket!")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")
    print(f"It only took {plays} tries to win!")
else:
    print(f"Tried {plays} times, without pulling a winner. :(")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")

print(check_ticket(new_ticket, winning_ticket))


C 顯示我的疑問我的問題在於這一段:

plays = 0
won = False

# Let's set a max number of tries, in case this takes forever!
max_tries = 1_000_000

while not won:
    new_ticket = make_random_ticket(possibilities)
    won = check_ticket(new_ticket, winning_ticket)
    plays += 1
    if plays >= max_tries:
        break

if won:
    print("We have a winning ticket!")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")
    print(f"It only took {plays} tries to win!")
else:
    print(f"Tried {plays} times, without pulling a winner. :(")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")

我想知道為什么它首先定義won=False ,然后在if not won (為什么不說 if True?)它定義won = check_ticket(new_ticket,winning_ticket)可以返回 False 或 True,最后說if won ??? 如果 False,這是否意味着? 為什么不這么說?

而且,我想知道為什么我對這個問題的代碼不起作用:



from random import choice

possibilities=['1','2','3','4','5','6','7','8','9','10','a','b','c','d','e']

def make_winning_ticket(possibilities):
    winning_ticket=[]
    while len(winning_ticket)<4:
        new_number=choice(possibilities)
        if new_number not in winning_ticket:
          winning_ticket.append(new_number)
    return winning_ticket

def make_new_ticket(possibilities):
     new_ticket=[]
     while len(new_ticket)<4:
        new_number=choice(possibilities)
        if new_number not in new_ticket:
          new_ticket.append(new_number)
     return new_ticket

play=0
max_try=100000

def check_ticket(new_ticket,winning_ticket):
    while play<max_try:
        for element in new_ticket:
            if new_ticket not in winning_ticket:
             play+=1
             make_new_ticket(possibilities)
             
    print(play)
 


make_winning_ticket(possibilities)
make_new_ticket(possibilities)
check_ticket(winning_ticket,new_ticket)

感謝您的耐心等待:)

我想知道為什么它首先定義won=False ,然后在if not won (為什么不說 if True?)它定義won = check_ticket(new_ticket,winning_ticket)可以返回 False 或 True ,最后說 if韓元??? 如果 False,這是否意味着? 為什么不這么說?

不,它的意思是:

  • 首先,我們有一個 while 循環,它不斷檢查“我們”是否贏了。 這個決定(獲勝或未獲勝)保存在變量won中。
  • 為了能夠正確進入while循環,條件( not won )必須為真,所以won必須為False。 所以是這樣設置的。
  • 在 while 循環之后,我們檢查我們是否贏了。 它清楚地表明: if won:意味着“如果我們贏了”。

而且,我想知道為什么我對這個問題的代碼不起作用:

老實說,我並沒有嘗試遵循它的每一行,但似乎是最大的問題之一:你丟棄了函數的返回值。

如果我們有一個 function,比如說

def f(x):
    y = 2 * x
    return y

這樣做是不夠的

f(10)

然后期望我們做了一些有用的事情: y變量完全在 function 內。 為了獲得它的價值,我們必須做

y = f(10) # y will be 20

甚至(與函數內部的名稱完全不同):

y1 = f(10) # y1 will be 20
y2 = f(15) # y2 will be 30

所以在你的例子中,你至少應該做

winning_ticket = make_winning_ticket(possibilities)
new_ticket = make_new_ticket(possibilities)
check_ticket(winning_ticket, new_ticket)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM