Найти - Пользователи
Полная версия: Помощь с задачкой
Начало » Python для новичков » Помощь с задачкой
1 2
hewonders
Привет!
Подскажите, пожалуйста, с задачей:
Stocking Out

Now you need your compute_bill function to take the stock/inventory of a particular item into account when computing the cost.

Ultimately, if an item isn't in stock, then it shouldn't be included in the total. You can't buy or sell what you don't have!
Instructions

Make the following changes to your compute_bill function:

While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.

?
Hint

If you're buying a banana, check if it's in stock (larger than zero). If it's in stock, add the cost of a banana to your bill. Finally, decrement the stock of bananas by one!

По условиям задачи если искомый фрукт находится в инвентаре (stock), то есть больше 0, то тогда он добавляется к общему счету (функция compute_bill) и вычитается из общего stock'а нужного объекта (банан, яблоко и т.п.).

Мой код выглядит так:

 shopping_list = ["banana", "orange", "apple"]
stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
# Write your code below!
def compute_bill(food):
    total = 0
    for item in food:
        if stock(item) > 0:
            total = prices[item] + total
        return stock[item] - 1
    return total
   

на что выдается ошибка:


Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: ‘dict’ object is not callable


ZerG
Покажите как вы вызываете функцию
hewonders
К примеру например:
     compute_bill("banana")

вызовет ошибку:

Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: ‘dict’ object is not callable
Stepan_M
hewonders
 return stock[item] - 1
stock это же словарь, вроде бы в нем нельзя брать элементы по индексам?
Может, нужно
 return stock(item) - 1
hewonders
И при квадратный и при круглых скобках
 # Write your code below!
def compute_bill(food):
    total = 0
    for item in food:
        if stock(item) > 0:
            total = prices[item] + total
        return stock(item) - 1
    return total
  

ошибка одна и та же:
Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: ‘dict’ object is not callable
ZerG
 if stock[item] > 0:
hewonders
Имелось в виду в
  return stock(item) - 1
оставить круглые а в
  if stock[item] > 0:
квадратные?

Если так, то не помогло)

Пробовал в двух IDE.

Если вызвать функцию, например compute_bill(“banana”),
то будет ошибка
Traceback (most recent call last):
File “CUsers/fomichevll/AppData/Local/Programs/Python/Python35/ввввввввв.py”, line 25, in <module>
compute_bill(“banana”)
File “CUsers/fomichevll/AppData/Local/Programs/Python/Python35/ввввввввв.py”, line 21, in compute_bill
if stock > 0:
KeyError: ‘b’

в другом:
File “python”, line 25
compute_bill(“banana”)
^
IndentationError: unindent does not match any outer indentation level
ZerG
 # -*- coding: utf-8 -*-
stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
item = 'pear'
# print(stock(item)) # Это не метод словаря - будет ошибка
print(stock[item]) # 
Другими словами, при обращении к словарю
  d = {'a': 'b'}
нужно использовать соответствующий метод
 print(d['a'])
b
hewonders
Если изменить код по аналогии, то получается:

 def compute_bill(food):
    total = 0
    for item in food:
        if (stock[item]) > 0:
            total = (prices[item]) + total
        return (stock[item]) - 1
    return total

Ошибка:
Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in -1 instead of the correct 7

Если выполнить функцию compute_bill(“banana”)

то ошибка
Oops, try again. Your code looks a bit off. See the console window for the error. Check the Hint if you need help!
а в console window:

Traceback (most recent call last):
File “python”, line 25, in <module>
File “python”, line 21, in compute_bill
KeyError: ‘b’
ZerG
Пользуйтесь оператором print() для отладки вашего кода

 # -*- coding: utf-8 -*-
def compute_bill(food):
    total = 0
    for item in food:
        print(item)
compute_bill('pear')

Результатом будет
p
e
a
r

This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB