Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c53236e

Browse files
Working code
1 parent ff05862 commit c53236e

File tree

3 files changed

+163
-92
lines changed

3 files changed

+163
-92
lines changed

‎FruitStore/FStore.py

Lines changed: 41 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
import time, sys
22

3-
class FStore:
3+
class Cart:
4+
def __init__(self):
5+
self.items = {}
6+
7+
def addToCart(self,fruitName, quantity):
8+
self.items[fruitName] = quantity
9+
10+
def removeFromCart(self,itemindex):
11+
self.items.pop(itemindex)
12+
13+
def showCart(self):
14+
return self.items
415

516

17+
class FStore:
18+
619
def __init__(self, stock={}):
720
"""
821
Our constructor class that instantiates fruit store.
@@ -13,27 +26,18 @@ def displayStock(self):
1326
"""
1427
Displays the fruits currently available for purchase in the store.
1528
"""
16-
17-
# for fruits, quantity in self.stock.items():
18-
# print(" We currently have {} {} in store".format(quantity, fruits), end="\n")
19-
20-
# return None
21-
22-
# Sanjay's code
2329
for fruits, quantity in self.stock.items():
2430
print("we have " + str(quantity) + " of " + fruits)
25-
2631
return '\n'
2732

2833
def getStockFromStore(self):
2934
return self.stock
3035

3136
def listOfFruits(self):
32-
# self.Fruits = [fruits for fruits in self.stock.keys()]
33-
# return self.Fruits
34-
35-
# Sanjay's code
36-
return list(self.stock.keys())
37+
op = {}
38+
for key, value in self.stock.items():
39+
op[value['id']] = [key, value['price']]
40+
return op
3741

3842

3943
def timeDelay(self):
@@ -43,23 +47,30 @@ def timeDelay(self):
4347
def callExit(self):
4448
self.exit = sys.exit(0)
4549
return self.exit
50+
51+
def getFruitsIDs(self):
52+
fID = []
53+
for key, value in self.stock.items():
54+
fID.append(value['id'])
55+
return fID
4656

47-
def numberOfFruits(self, number):
48-
49-
# if number <= 0:
50-
# print("Number of fruits should be positive!")
51-
# return None
52-
# elif n > self.stock.values()[0]
53-
pass
54-
55-
def cart(self):
56-
# cart logic
57-
pass
58-
57+
def getAvailableCountForFruit(self, fruitID):
58+
for key,value in self.stock.items():
59+
if int(fruitID) in list(value.values()):
60+
# print("availab count is ", list(value.values())[0] )
61+
return list(value.values())[0]
5962

63+
def getFruitName(self, fruitID):
64+
for fruitName,fruitInfo in self.stock.items():
65+
if int(fruitID) in list(fruitInfo.values()):
66+
return fruitName
6067

61-
# TODO: 3 - crate a class called ShoppingCart
62-
# addToCart
63-
# ṛemoveFromCart
64-
# getListOfItemsFromCart
68+
defupdateStock(self, fruitName, quantity):
69+
fruitInfo=self.stock[fruitName]
70+
fruitInfo['availableCount'] =fruitInfo['availableCount'] -quantity
71+
# print(self.stock)
6572

73+
def getFruitPrice(self, fruitName):
74+
for fn, value in self.stock.items():
75+
if fruitName == fn:
76+
return value['price']

‎FruitStore/main.py

Lines changed: 102 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
from FStore import FStore
2+
from FStore import Cart
3+
import time
4+
import getpass
25

3-
# TODO 1 - get stock from reading a json file.
4-
dict= {'Apple':100, 'Banana': 100, 'Cherry': 100}
5-
# Write a function to read stockjson file
6-
# function should return json info which is there in the file.
6+
importjson
7+
defgetAvilableStock():
8+
stockInfo=open("C:\\Users\\sanja\\Documents\\GitHub\\Python-Data-Structure\\FruitStore\\stock.json", "r")
9+
return json.load(stockInfo)
710

8-
9-
# TODO 2 - pass the return of above function, to open your store
10-
openStore = FStore(dict) # you cannot open a store without stock.
11+
openStore = FStore(getAvilableStock())
12+
cartInstance = Cart()
1113

1214
def getUserInput(fromWhichMenu):
1315

@@ -30,77 +32,119 @@ def getUserInput(fromWhichMenu):
3032
print("That's not an int!")
3133

3234
return choice
33-
elif fromWhichMenu == "addOrRemove":
35+
elif fromWhichMenu == "addMoreItems":
3436
try:
35-
choice = input("Is there anything you want to add or remove? Y or N ").strip()
36-
if choice == "Y":
37+
choice = input("Do you want to add more items to your cart? Y or N ").strip()
38+
if choice == "Y"orchoice=="y"orchoice=="yes"orchoice=="YES":
3739
return True
3840
else:
3941
return False
4042
except ValueError:
4143
print("That's not an int!")
44+
elif fromWhichMenu == "adminStuff":
45+
try:
46+
choice = getpass.getpass("Enter admin password")
47+
if choice == "admin123":
48+
return True
49+
else:
50+
return False
51+
except ValueError:
52+
print("That's not a valid password!")
4253

4354

4455

4556
def displayMainMenu():
4657
print("""
47-
====== Fruit Shop =======
48-
1. Display available Stocks
49-
2. Buy Fruits
50-
3. Get Total
58+
1. Show available fruits
59+
2. Buy Fruits
60+
3. Show Cart
5161
4. Checkout
5262
5. Exit
63+
6. Display available Stocks (only store admin can access)
5364
""")
5465

55-
def displayFruitMenu():
56-
for i in enumerate(openStore.listOfFruits(), start=1):
57-
print(i[0], i[1])
58-
59-
def shoppingCart():
60-
pass
61-
62-
def storeOpens():
63-
# while True:
64-
cart = {}
65-
displayMainMenu()
66-
choice = getUserInput("fromMainMenu")
67-
68-
if choice == '1':
69-
openStore.displayStock()
70-
print("\n please select from above available stock", end="\n")
71-
elif choice == '2':
72-
print("\n What do you want to buy?\n")
66+
def addMoreItems():
67+
if (getUserInput("addMoreItems")):
7368
displayFruitMenu()
7469
choice = getUserInput("fruitMenu")
70+
return choice
71+
else:
72+
print("purchase done")
73+
7574

76-
if choice == '1':
77-
availableStock = openStore.getStockFromStore()
78-
count = int(getUserInput("numbers"))
79-
80-
if count <= availableStock['Apple']:
81-
cart['Apple'] = count
82-
availableStock['Apple'] = availableStock['Apple'] - count
83-
print(availableStock)
84-
85-
print("Here's your items in cart , ", cart)
86-
# wannaBuyMore = getUserInput("addOrRemove")
87-
# if (wannaBuyMore):
88-
# fruitChoice = getUserInput("fruitMenu")
89-
90-
# else:
91-
# print("Done")
92-
93-
94-
elif choice == '2':
95-
pass
96-
elif choice == '3':
97-
pass
75+
def displayFruitMenu():
76+
for i in enumerate(openStore.listOfFruits(), start=1):
77+
print(i[0], i[1])
9878

99-
elif choice == 5:
100-
pass
79+
def billFormat(billObj):
80+
for fruitName, price in billObj.items():
81+
print(fruitName + " - " + str(price))
82+
83+
print("Total Bill amount to pay " + str(sum(billObj.values())) + " Rupees \n")
84+
85+
86+
def checkOutCart():
87+
billMap = {}
88+
cartItems = cartInstance.showCart()
89+
for fn,count in cartItems.items():
90+
fruitPrice = openStore.getFruitPrice(fn)
91+
billMap[fn] = fruitPrice * count
92+
billFormat(billMap)
93+
94+
def showAvailableFruits():
95+
availableFruits = openStore.listOfFruits()
96+
print("Here's the available fruits, happy purchasing\n")
97+
for id, fruit in availableFruits.items():
98+
print(str(id) + " - " + fruit[0] + "(each " + fruit[0] + " cost " + str(fruit[1]) + " Rupees)")
99+
100+
def buyFruit(fruitId):
101+
if int(fruitId) in openStore.getFruitsIDs():
102+
fruitCount = int(getUserInput("numbers"))
103+
if fruitCount <= openStore.getAvailableCountForFruit(fruitId):
104+
cartInstance.addToCart(openStore.getFruitName(fruitId), fruitCount)
105+
openStore.updateStock(openStore.getFruitName(fruitId), fruitCount)
106+
107+
print(str(fruitCount) + " " +openStore.getFruitName(fruitId) + " added to your cart \n")
108+
else:
109+
print("The count you entered is either exceeding or we nearing out of stock soon")
101110
else:
102-
print("Invalid input. Please enter number between 1-5 ")
111+
print("ID which's entered isn't matching with any fruits which we have!")
103112

104113

105114
if __name__ == "__main__":
106-
storeOpens()
115+
116+
while True:
117+
displayMainMenu()
118+
userChoice = getUserInput("fromMainMenu")
119+
120+
if userChoice == '1':
121+
showAvailableFruits()
122+
elif userChoice == '2':
123+
showAvailableFruits()
124+
choice = getUserInput("fruitMenu")
125+
buyFruit(choice)
126+
if(getUserInput("addMoreItems")):
127+
showAvailableFruits()
128+
choice = getUserInput("fruitMenu")
129+
buyFruit(choice)
130+
# getUserInput("addMoreItems")
131+
else:
132+
displayFruitMenu()
133+
elif userChoice == '3':
134+
cartItems = cartInstance.showCart()
135+
print("Currently you have below items in your cart, ")
136+
for itemName, itemCount in cartItems.items():
137+
print(itemName + "-" + str(itemCount))
138+
elif userChoice == '4':
139+
checkOutCart()
140+
141+
print("Enjoy Shopping at Ram's Fruit Store!\n")
142+
break
143+
elif userChoice == '5':
144+
break
145+
elif userChoice == '6':
146+
if(getUserInput("adminStuff")):
147+
openStore.displayStock()
148+
break
149+
else:
150+
print("Invalid input. Please enter number between 1-6 ")

‎FruitStore/stock.json

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
11
{
2-
"Apple": 100,
3-
"Banana": 70,
4-
"Cherry": 23,
5-
"orange": 254
2+
"Apple": {
3+
"availableCount": 100,
4+
"id" : 1001,
5+
"price": 12
6+
},
7+
"Banana": {
8+
"availableCount": 67,
9+
"id" : 1002,
10+
"price": 15
11+
},
12+
"Cherry": {
13+
"availableCount": 23,
14+
"id" : 1005,
15+
"price": 30
16+
},
17+
"orange": {
18+
"availableCount": 76,
19+
"id" : 1009,
20+
"price": 10
21+
}
622
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /