Как использовать переменную, чтобы определить, какой индекс в списке использовать - PullRequest
1 голос
/ 09 мая 2020

В последнее время я тестировал свою программу, и каждый раз, когда я ее тестировал, у меня появлялось одно и то же сообщение об ошибке: IndexError: индекс списка вне допустимого диапазона. Код:

def NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers):
    x = random.randint(0, NoOfBuyers)
    SelectedBuyer = Buyers[x]
    if CurrentOffer < MaximumPrice[x]:
        CurrentOffer = CurrentOffer + random.randint(1, 500)
        print(str(SelectedBuyer) + " renewed their offer and are now willing to pay £" + 
        str(CurrentOffer) + " for " + str(AuctionedItem))
        x = random.randint(0, NoOfBuyers)
        NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers)
        time.sleep(3)

И единственная строка, которая сбивается каждый раз, - это '' 'SelectedBuyer = Buyers [x]' ''. Как решить эту проблему?

Ответы [ 2 ]

0 голосов
/ 11 мая 2020

Я попытался понять ваш код и придумал другую реализацию:

import random
import time

buyers = (
    ("Peggy Carter", 10000),
    ("Phil Coulson", 7500),
    ("Edwin Jarvis", 5000),
    ("Justin Hammer", 2300),
    ("Darcy Lewis", 1750),
    ("Christine Everhart", 6490),
)

auctioned_item = "The Tesseract"
current_offer = random.randint(1, 5000)
print(f"The starting price for {auctioned_item} is £{current_offer}")
current_buyer = None

def auction_rounds(current_offer, buyers):
    current_buyer = None
    outbid = False
    while not outbid:
        (next_buyer, next_maximum) = random.choice(buyers)
        while next_buyer == current_buyer:
            (next_buyer, next_maximum) = random.choice(buyers)
        outbid = current_offer > next_maximum
        if not outbid:
            current_buyer = next_buyer
            yield (current_buyer, current_offer)
            next_offer = random.randint(current_offer, min(current_offer + 500,
                                                           next_maximum))
            current_buyer, current_offer = next_buyer, next_offer
    else:
        print(f'This is too much for {next_buyer}')

for (current_buyer, current_offer) in auction_rounds(current_offer, buyers):
    print(f"{current_buyer} is offering to pay £{current_offer}",
          "for", auctioned_item)
    #time.sleep(3)

if current_buyer is None:
    print("The first buyer wasn't even able to pay the starting price")
else: 
    print(f"Sold! The auction item ({auctioned_item}) is awarded to {current_buyer} for £{current_offer}")

Надеюсь, это что-то вроде того, что вы искали.

0 голосов
/ 09 мая 2020

Кажется, что в списке покупателей нет элемента в позиции x, вы можете проверить его с помощью

Buyers[x] if len(Buyers) >= x else #some value if it's not in the len()

или

x = random.randint(0, len(Buyers) - 1)

Чтобы сгенерировать случайное число, которое в длина списка покупателей. Возможно, вам придется сделать то же самое для MaximumPrice

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...