根据ID创建购买功能



你好StackOverflow社区,

我有一个python脚本,它生成一个随机的";用户"价格";,以及";id";。现在,我希望能够使用id购买其中一个用户。我试图在其中添加一个列表和索引,但这让我有点困惑,没有奏效。下面是我的python脚本草稿

import random 
import string
inventory = []
money = 25
def removeFromInventory(itemname, itemvalue):
print(null)
def addToInventory(itemname, itemvalue):
print(null)

def listOffers(budget):
if budget > money:
print("You cant afford your budget")
else:
for a in range(10):
uid = str(str(random.randint(1,10)) + random.choice(string.ascii_letters))
user = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(3,4)))
print("User:" + str(user) + " ID:" + str(uid) + " Price:" + str(random.randint(5, budget)))

def purchaseUser(inventory, itemId, cash=money):
ival = inventory[itemId].get("value")
iname = inventory[itemId].get("itemname")
subPrice = ival *.3 + ival
total = subPrice * .25 + subPrice

if cash < total:
print("Error: Insufficient Funds")
else:
addtoInventory(iname, ival)

期望行为:Create a user, price, and id at random类似:{"User": "axf", "Price": 10, "ID": "1a"}

希望这有帮助:

from collections import Counter
import random
import string
from typing import Dict, NamedTuple, NewType

ItemId = NewType('ItemId', str)

class Item(NamedTuple):
id: ItemId
name: str
price: int

all_items: Dict[ItemId, Item] = {}
inventory: Dict[ItemId, int] = Counter()
money = 25

def remove_from_inventory(id: ItemId) -> None:
inventory[id] -= 1

def add_to_inventory(id: ItemId) -> None:
inventory[id] += 1

def list_offers(budget: int) -> None:
if budget > money:
print("You cant afford your budget")
return
for _ in range(10):
item_id = ItemId(
str(random.randint(1, 10))
+ random.choice(string.ascii_letters)
)
item_name = ''.join(
random.choice(string.ascii_letters)
for _ in range(random.randint(3, 4))
)
item_price = random.randint(5, budget)
print(f"Item: {item_name} ID: {item_id} Price: {item_price}")
# Collisions are unlikely but possible!  Consider the uuid module.
all_items[item_id] = Item(item_id, item_name, item_price)

def purchase_item(item_id: ItemId, cash: int = money) -> None:
item = all_items[item_id]
total_price = item.price * 1.3 * 1.25
if cash < total_price:
print("Error: Insufficient Funds")
return
print(f"Buying {item.name} for a total price of {total_price}")
add_to_inventory(item_id)

一般的想法是将项目存储在一个以id为关键字的字典中。一旦你有了那个字典(我把它命名为all_items),你就可以简单地使用id来引用每个条目,而不需要提供它的名称和值;我在这里实现了inventory作为一个计数器,它跟踪每个项目的数量(按其ItemId),而不是项目列表。