I am new to python and have been trying to add values that I get from iterating over a list of dictionaries.
I keep running into 'builtin_function_or_method' object is not iterable' error message or unsupported type. Any help would be much appreciated.
here is my code:
def inventory(acct_info, months_subscribed, add_free_months, video_on_demand):
print(acct_info)
for info in acct_info:
print('-')
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
acct_all_total = [int(acct_all_total)]
print(f"Total for {info.get('name')} is: {acct_all_total} ")
acct_info = [{'name': 'acct_1', 'months_subscribed' : 2 , 'ad_free_months' : 3 , 'video_on_demand' : 1} ,
{'name': 'acct_2', 'months_subscribed' : 1 , 'ad_free_months' : 2 , 'video_on_demand' : 2},
{'name': 'acct_3', 'months_subscribed' : 2 , 'ad_free_months' : 1 , 'video_on_demand' : 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
inventory(acct_info, months_subscribed, ad_free_months, video_on_demand)
acct_all_total = 0
main()
Output so far is :
User acct_1 has months subscribed total of : $ 14
User acct_1 total ad free is : 6
User acct_1 total video on demand is : 27.99
Total for acct_1 is: [47]
-
User acct_2 has months subscribed total of : $ 7
User acct_2 total ad free is : 4
User acct_2 total video on demand is : 55.98
Total for acct_2 is: [66]
-
User acct_3 has months subscribed total of : $ 14
User acct_3 total ad free is : 2
User acct_3 total video on demand is : 83.97
Total for acct_3 is: [99]
What i am trying to sum up is the total for all of the users. I manage to get a total for each user, but i then want add the totals of that. Thank you.
You can take into consideration modifying your code a little bit your code.
I would move out the for loop from your function to make it do just one thing: do the inventory for a given account.
The following code is just an example, but it provides an alternative solution for your question.
def inventory(info, months_subscribed, add_free_months, video_on_demand):
acct_all_total = 0 # here you init the total value to 0
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
# acct_all_total = [int(acct_all_total)]
print(f"Total for {info.get('name')} is: {acct_all_total} ")
return acct_all_total
Please note I also commented the # acct_all_total = [int(acct_all_total)]
Then you can call it
acct_info = [{'name': 'acct_1', 'months_subscribed': 2, 'ad_free_months': 3, 'video_on_demand': 1},
{'name': 'acct_2', 'months_subscribed': 1, 'ad_free_months': 2, 'video_on_demand': 2},
{'name': 'acct_3', 'months_subscribed': 2, 'ad_free_months': 1, 'video_on_demand': 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
acct_all_total = 0
for acct in acct_info:
acct_all_total+=inventory(acct, months_subscribed, ad_free_months, video_on_demand)
print("Tot:",acct_all_total)
Output:
User acct_1 has months subscribed total of : $ 14
User acct_1 total ad free is : 6
User acct_1 total video on demand is : 27.99
Total for acct_1 is: 47
User acct_2 has months subscribed total of : $ 7
User acct_2 total ad free is : 4
User acct_2 total video on demand is : 55.98
Total for acct_2 is: 66
User acct_3 has months subscribed total of : $ 14
User acct_3 total ad free is : 2
User acct_3 total video on demand is : 83.97
Total for acct_3 is: 99
Tot: 212
Edited to reflect comments.
If you want to get the largest of your total, you have to change the code a bit. Consider to use the built-in function max() https://docs.python.org/3.8/library/functions.html#max and sum() https://docs.python.org/3.8/library/functions.html#sum.
max() returns the largest item in an iterable or the largest of two or more arguments. sum() sums all the element in an iterable. So, let's use an iterable in our code
tot = list()
for acct in acct_info:
# here, we gonna append each total
tot.append(inventory(acct, months_subscribed, ad_free_months, video_on_demand))
print("all the values:",tot)
print("the largest is:",max(tot)) # here we extract the largest item of the list
print("Total:",sum(tot)) # here we sum all the element of the list tot
Output:
all the values: [47, 66, 99]
the largest is: 99
Total: 212
I modified your inventory function, now it contains a list before the loop start and it holds all the totals of the users that you are printing at the bottom of the loop, at the end using the sum function the grand total of all users can be calculated
def inventory(acct_info, months_subscribed, add_free_months, video_on_demand):
print(acct_info)
all_users_collection = []
for info in acct_info:
print('-')
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
acct_all_total = [int(acct_all_total)]
all_users_collection.append(int(acct_all_total))
print(f"Total for {info.get('name')} is: {acct_all_total} ")
acct_info = [{'name': 'acct_1', 'months_subscribed' : 2 , 'ad_free_months' : 3 , 'video_on_demand' : 1} ,
{'name': 'acct_2', 'months_subscribed' : 1 , 'ad_free_months' : 2 , 'video_on_demand' : 2},
{'name': 'acct_3', 'months_subscribed' : 2 , 'ad_free_months' : 1 , 'video_on_demand' : 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
inventory(acct_info, months_subscribed, ad_free_months, video_on_demand)
acct_all_total = 0
print('Total for all users is', sum(all_users_collection))
The other approach can be to use a single variable and increment for every total of a user at the end you will get total of all users
Related
I am really new to python and have been working on this with the help of others.
I am trying to figure out the right way to go about finding the max of the list acct_all_total.
Everything else works if I remove the part w/ the max function.
erros i get: TypeError: 'int' object is not iterable.
Or I get 0 as a result.
def inventory(info, months_subscribed, add_free_months, video_on_demand):
acct_all_total = 0
acct_max = 0
# here you init the total value to 0
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : $ {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is $ : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
# acct_all_total = [int(acct_all_total)]
print(f"Total for {info.get('name')} is: {acct_all_total} ")
# acct_max = (max(acct_all_total)) #if I use these hashtag parts I get the type error mentioned above.
# if int(acct_all_total) > int(acct_all_total):
# acct_max = int(acct_all_total)
# print(f" User {info.get('name')} max value is: {acct_max} ")
return acct_all_total ; acct_max
acct_info = [{'name': 'acct_1', 'months_subscribed': 2, 'ad_free_months': 3, 'video_on_demand': 1},
{'name': 'acct_2', 'months_subscribed': 1, 'ad_free_months': 2, 'video_on_demand': 2},
{'name': 'acct_3', 'months_subscribed': 2, 'ad_free_months': 1, 'video_on_demand': 3}]
acct_max = 0
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
acct_all_total = 0
for acct in acct_info:
print("--")
acct_all_total+=inventory(acct, months_subscribed, ad_free_months, video_on_demand)
for acct in acct_info: #when I try it this way I get 0 as a result
if int(acct_all_total) > int(acct_all_total):
acct_max = acct_all_total
print("Total for all accounts:",acct_all_total)
Example of Output:
User acct_1 has months subscribed total of : $ 14
User acct_1 total ad free is : $ 6
User acct_1 total video on demand is $ : 27.99
Total for acct_1 is: 47
--
User acct_2 has months subscribed total of : $ 7
User acct_2 total ad free is : $ 4
User acct_2 total video on demand is $ : 55.98
Total for acct_2 is: 66
--
User acct_3 has months subscribed total of : $ 14
User acct_3 total ad free is : $ 2
User acct_3 total video on demand is $ : 83.97
Total for acct_3 is: 99
Total for all accounts: 212
0
To get the biggest number in a list you can sort it first and then get the first or last item in the list.
obj = [1, 6, 9, 123, 64, 12]
obj.sort() # Sorts the list into this: [1, 6, 9, 12, 64, 123]
print(obj[-1]) # [-1] Returns the last item in the list
Make sure the list does not contain strings as the sort function will not sort strings mixed with integers or floats.
Note that your "acct_all_total" is not a list, a list is defined with [] (insert a reference to docs or other basic explanation).
Edit:
I would like to clarify that you're probably better off researching a bit more about the different types of objects there are in python, how to use them and when to use which one.
Below is a text-based Python implementation algorithm about a task. The task is,
"Tickets can be purchased for a single passenger or a group of passengers. When making purchase, checks that the number of tickets for the required train journeys up and down a mountain is available. If the tickets are available, calculate the total price including any group discount. Update the screen display and the data for the totals."
This is the description of this task.
"An electric mountain railway makes four return trips every day. In each trip the train goes up the mountain at 9,11,13 and 15. The train returns from the top of the mountain at 10,12,14, and 16. Each train has 6 coaches with 80 seats. Passenger can only buy a return tickets; all tickets must be bought on the day of travel. The cost is $25 for the journey up and $25 for the journey down. Groups of between 10 and 80 passenger inclusive get a free ticket for every 10th passenger, provided they all travel together. Passenger must book their return train journey, as well as the departure train journey, when they buy their tickets. Passengers can return on the next trian down the mountain or a later train. The last train from the top of the mountain has two extra coaches on it.
The train times are displayed on a large screen, together with the number of tickets still available for each train. Every time a ticket is booked the display is updated. When a train is full, the word 'Closed' is displayed instead of the number of tickets available
When the ticket for 15 o'clock is 0 and when I try to book the ticket for 16 o'clock as there are extra tickets available it asks to enter the appropriate number of tickets rather than allowing me to book the ticket.
Could you please tell me why am I getting this error? Would you be able to fix the error, please? Thank you in advance!
FYI, I'm a beginner in this field trying to learn the basic.
train_up_time = [9,11,13,15]
train_down_time = [10,12,14,16]
train_up_ticket =[480]*4
train_down_ticket =[480,480,480,640]
train_up_money =[0.00]*4
train_down_money = [0.00]*4
cost = 25.00
index_up = 0
index_down = 0
ticket_cost = 0
ticket_counter = 0
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t", train_up_ticket[ i ], "\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t", train_down_ticket[ i ], "\t\t\t", train_down_money[ i ])
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1. : " ))
while selling_ticket == 1:
time_up = int(input("What time would you like to buy for 9 11 13 15? : "))
while time_up != 9 and time_up != 11 and time_up != 13 and time_up != 15 :
print("Error! please select the appropraite time from the available.")
time_up = int(input("What time would you like buy for 9 11 13 15? : "))
time_down = int(input("What time would you like to return 10 12 14 16? : "))
while time_up > time_down or ( time_down != 10 and time_down != 12 and time_down != 14 and time_down != 16) :
print("Error! please select the appropraite time (you must not select the time below the departure)." )
time_down = int(input("What time would you like to return 10 12 14 16? : "))
for count in range(0,4):
if time_up == train_up_time[ count ]:
index_up = count
if time_down == train_down_time[ count]:
index_down = count
for i in range(0, 4):
if train_up_ticket [ index_up ] == "CLOSED":
train_up_ticket [ index_up ] = 0
if train_down_ticket[ index_down ] == "CLOSED" :
train_down_ticket[ index_down ] = 0
num_ticket = int(input("How many tickets would you like to buy? : "))
while num_ticket > train_up_ticket[ index_up ] or num_ticket > train_down_ticket [ index_down ] :
print("Error! Please recheck the availability of the trian ticket")
num_ticket = int(input("How many tickets would you like to buy? : "))
print("Every 10th passenger is FREE!")
train_up_ticket [ index_up ] = train_up_ticket [ index_up ] - num_ticket
train_down_ticket[ index_down ] = train_down_ticket[ index_down ] - num_ticket
if num_ticket >= 10:
ticket_cost = cost * (num_ticket - (num_ticket/10))
else:
ticket_cost = cost * num_ticket
print("Your trip cost: ", "$", ticket_cost)
print("You need to pay for both ways")
print("Therefore, your total trip cost including the discount is : ", "$", ticket_cost*2 )
train_up_money[ index_up ] = train_up_money[ index_up ] + ticket_cost
train_down_money[ index_down ] = train_down_money[ index_down ] + ticket_cost
if train_up_ticket [ index_up ] == 0:
train_up_ticket [ index_up ] = "CLOSED"
if train_down_ticket[ index_down ] == 0:
train_down_ticket[ index_down ] = "CLOSED"
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t", train_up_ticket[ i ], "\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t", train_down_ticket[ i ], "\t\t\t", train_down_money[ i ])
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1. : " ))
There is a problem here:
while num_ticket > train_up_ticket[ index_down ] or num_ticket > train_down_ticket [ index_down ] :
I think it should be index_up for the first comparison.
I do not think there is any logical issue in the code. Here is the sample log from your program:
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 15
What time would you like to return 10 12 14 16?: 16
How many tickets would you like to buy?: 480
Every 10th passenger is FREE!
Your trip cost: $ 10800.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 21600.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 480 0.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 480 0.0
16 160 10800.0
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 9
What time would you like to return 10 12 14 16?: 16
How many tickets would you like to buy?: 160
Every 10th passenger is FREE!
Your trip cost: $ 3600.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 7200.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 320 3600.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 480 0.0
16 CLOSED 14400.0
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 9
What time would you like to return 10 12 14 16?: 14
How many tickets would you like to buy?: 320
Every 10th passenger is FREE!
Your trip cost: $ 7200.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 14400.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 CLOSED 10800.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 160 7200.0
16 CLOSED 14400.0
Would you like buy ticket for trip ? Enter 1 else -1:
I fix some line indentation and you can check my code:
train_up_time = [9,11,13,15]
train_down_time = [10,12,14,16]
train_up_ticket =[480]*4
train_down_ticket =[480,480,480,640]
train_up_money =[0.00]*4
train_down_money = [0.00]*4
cost = 25.00
index_up = 0
index_down = 0
ticket_cost = 0
ticket_counter = 0
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1: "))
while selling_ticket == 1:
time_up = int(input("What time would you like to buy for 9 11 13 15?: "))
while time_up != 9 and time_up != 11 and time_up != 13 and time_up != 15 :
print("Error! please select the appropraite time from the available.")
time_up = int(input("What time would you like buy for 9 11 13 15?: "))
time_down = int(input("What time would you like to return 10 12 14 16?: "))
while time_up > time_down or ( time_down != 10 and time_down != 12 and time_down != 14 and time_down != 16) :
print("Error! please select the appropraite time (you must not select the time below the departure)." )
time_down = int(input("What time would you like to return 10 12 14 16?: "))
for count in range(0,4):
if time_up == train_up_time[ count ]:
index_up = count
if time_down == train_down_time[ count]:
index_down = count
for i in range(0, 4):
if train_up_ticket [ index_up ] == "CLOSED":
train_up_ticket [ index_up ] = 0
if train_down_ticket[ index_down ] == "CLOSED" :
train_down_ticket[ index_down ] = 0
# print("time_up: {}, time_down: {}".format(time_up, time_down))
# print("index_up: {}, index_down: {}".format(index_up, index_down))
# print("train_up_ticket: {}, train_down_ticket: {}".format(train_up_ticket, train_down_ticket))
num_ticket = int(input("How many tickets would you like to buy?: "))
while num_ticket > train_up_ticket[ index_up ] or num_ticket > train_down_ticket[ index_down ]:
print("Error! Please recheck the availability of the trian ticket")
num_ticket = int(input("How many tickets would you like to buy?: "))
print("Every 10th passenger is FREE!")
train_up_ticket[ index_up ] = train_up_ticket[ index_up ] - num_ticket
train_down_ticket[ index_down ] = train_down_ticket[ index_down ] - num_ticket
# print("train_up_ticket: {}, train_down_ticket: {}".format(train_up_ticket, train_down_ticket))
if num_ticket >= 10:
ticket_cost = cost * (num_ticket - (num_ticket/10))
else:
ticket_cost = cost * num_ticket
print("Your trip cost: ", "$", ticket_cost)
print("You need to pay for both ways")
print("Therefore, your total trip cost including the discount is : ", "$", ticket_cost*2 )
train_up_money[ index_up ] = train_up_money[ index_up ] + ticket_cost
train_down_money[ index_down ] = train_down_money[ index_down ] + ticket_cost
if train_up_ticket [ index_up ] == 0:
train_up_ticket [ index_up ] = "CLOSED"
if train_down_ticket[ index_down ] == 0:
train_down_ticket[ index_down ] = "CLOSED"
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t\t", train_up_ticket[ i ], "\t\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t\t", train_down_ticket[ i ], "\t\t\t\t", train_down_money[i])
# print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n")
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1: "))
I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.
Here is my code:
tourist_attractions = []
distance = []
entry_cost = []
for i in range(3):
tourist_attractions.append (input("Enter Tourist place: "))
tourist_distance =(int(input("Enter distance: ")))
if tourist_distance > 50:
print("Invalid Entry")
continue
if tourist_distance <= 50:
distance.append(tourist_distance)
cost = (float(input("Enter cost: ")))
if cost > 100:
print("cost must be between 1-100")
continue
if cost > 0 or cost <= 100:
entry_cost.append(cost)
print()
for line in tourist_attractions:
print("Place:", line)
for line in distance:
print("Distance:", line)
for line in entry_cost:
print("Cost:", line)
print()
number_of_places_to_visit = int(input("Total number of places to visit: "))
x = 1
while x <= number_of_places_to_visit:
select_tourist_place = input("select tourist place, 0-3: ")
x = x + 1
if select_tourist_place == "0":
print(tourist_attractions[0], distance[0], entry_cost[0])
elif select_tourist_place == "1":
print(tourist_attractions[1], distance[1], entry_cost[1])
elif select_tourist_place == "2":
print(tourist_attractions[2], distance[2], entry_cost[2])
elif select_tourist_place == "3":
print(tourist_attractions[3], distance[3], entry_cost[3])
elif select_tourist_place == "4":
print(tourist_attractions[4], distance[4], entry_cost[4])
print("total cost: " , sum(entry_cost))
Result I am getting:
Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20
Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0
Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost: 50.0
>>>
I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?
print("total cost: " , sum(entry_cost))
definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.
I want to write a bill program where i want the cgst, sgst from the bill as output. All was going fine but i got stuck on a problem. I want separate names of product from the result of dataframe's output but i am getting only the name of only one product but the amount was sum of two...
Here's my code:
import pandas as pd
count = 0
num = int(input("Type number of items: "))
while count < num:
count += 1
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = pd.DataFrame({
'Item ': [item],
'Price': [SP],
'CGST': [cgst],
'SGST': [sgst],
'Amount payable': [amount],
})
print(data)
what i am getting is this example output:
Type number of items: 2
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 2341
Enter GST rate: 34
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1234567
Enter GST rate: 15
Item Price CGST SGST Amount payable
0 iphone 1234567 92592.525 92592.525 1419752.05
```
What i want the output to be:
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0
As you can see, i am getting only name samsung not iphone and samsung saparatley
In each iteration of your loop you are creating a new data frame with only this loops data and overwitting any data that was in the last data frame. So when you finish your loops and print the dataframe all thats in it is the data from the last iteration of the loop since you created a new dataframe on each iteration.
Instead you could create the data frame before the loop and then just append to the data frame on each iteration of the loop
import pandas as pd
items = []
columns = ['Item', 'Price', 'CGST', 'SGST', 'Amount payable']
df = pd.DataFrame(columns=columns)
num = int(input("Type number of items: "))
for _ in range(num):
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = [item, SP, cgst, sgst, amount]
df_row = dict(zip(columns, data))
df = df.append(df_row, ignore_index=True)
print(df)
OUTPUT
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0
I need to read in the scores from a file of students quizzes, and return the highest score out of the 3 attempts.I need to use hash/dictionary in python. Here is what I have so far.
STD_ID = {}
ATTEMPTS = {}
SCORE= {}
f= open("std_attempt_score.txt", "r")
line = f.readline()
for line in f:
line = line.rstrip()
ents = line.split("\t")
did = ents[1]
if did in STD_ID:
ATTEMPTS[did] += 3
SCORE[did] += int(ents[2])
else:
STD_ID[did] = ents[2]
ATTEMPTS[did] = 3
SCORE[did] = int(ents[2])
for key in STD_ID:
print("Avg score for Student", key, "=",SCORE)
Text data in file.
FILE
STD_ID ATT_NUM SCORE
S23Y 1 85
S03X 1 80
S34Z 1 19
S54M 1 23
S34Z 2 25
S01X 1 79
S03X 2 10
S23Y 2 09
S34Z 3 92
S54M 2 96
S23Y 3 74
S54M 3 65
S03X 3 54
My results are as follows:
Avg score for Student 1 = {'1': 286, '2': 140, '3': 285}
Avg score for Student 2 = {'1': 286, '2': 140, '3': 285}
Avg score for Student 3 = {'1': 286, '2': 140, '3': 285}
If you don't need to store the score for each attempt then why not just replace the value if it's higher than the currently recorded attempt?
students = {}
f = open("std_attempt_score.txt", "r")
line = f.readline()
for line in f:
line = line.rstrip()
ents = line.split(",")
student_id = ents[0]
attempt_score = int(ents[2])
score = students.setdefault(student_id, attempt_score)
if attempt_score > score:
students[student_id] = attempt_score
for student_id, score in students.items():
print("Highest score for Student", student_id, "=", score)
Issues with the given code :
Loop starts with a text header which is not checked before going to if else statements for student_id checks .Printing the same value of SCORE at the end of code.no average is taken in script.
Fixed code
Here is a sample code
STD_ID = {}
ATTEMPTS = {}
SCORE= {}
f= open("std_attempt_score.txt", "r")
line = f.readline()
for line in f:
line = line.rstrip()
entss = " ".join(line.split())
ents = entss.split(" ")
did = ents[0]
if not line.startswith("STD_ID"): # check for the header you definitely want to skip this line
if did in STD_ID :
ATTEMPTS[did] += 1
SCORE[did].append(int(ents[2])) #polulate student_id with marks
else:
STD_ID[did] = [ents[0]] #Start Dictionary with student ID and marks
ATTEMPTS[did] = 1
SCORE[did] = [int(ents[2])]
for key in sorted(STD_ID):
if len(SCORE[key]) < 3:
dumValues = [0] * (3 - len(SCORE[key]))
SCORE[key] = SCORE[key] + dumValues # add 0's in un-attempted quizzes.
print("Student ID {0} Score Summary : \n".format(key))
print("Top 3 Quiz : ", sorted(SCORE[key], reverse=True)[:3])
print("Avg score of top 3 quiz : " , sum(sorted(SCORE[key], reverse=True)[:3]) / 3)
print("Quiz With Highest Marks out of 3 Top Quizzes : ", sorted(SCORE[key], reverse=True)[0])
print("Total Marks in 3 Attempts : ", sum(sorted(SCORE[key], reverse=True)[:3]), "\n\n")
Sample Output:
Student ID S01X Score Summary :
Top 3 Quiz : [79, 0, 0]
Avg score of top 3 quiz : 26.333333333333332
Quiz With Highest Marks out of 3 Top Quizzes : 79
Total Marks in 3 Attempts : 79
Student ID S03X Score Summary :
Top 3 Quiz : [80, 54, 10]
Avg score of top 3 quiz : 48.0
Quiz With Highest Marks out of 3 Top Quizzes : 80
Total Marks in 3 Attempts : 144
Student ID S23Y Score Summary :
Top 3 Quiz : [85, 74, 9]
Avg score of top 3 quiz : 56.0
Quiz With Highest Marks out of 3 Top Quizzes : 85
Total Marks in 3 Attempts : 168
Student ID S34Z Score Summary :
Top 3 Quiz : [92, 25, 19]
Avg score of top 3 quiz : 45.333333333333336
Quiz With Highest Marks out of 3 Top Quizzes : 92
Total Marks in 3 Attempts : 136
Student ID S54M Score Summary :
Top 3 Quiz : [96, 65, 23]
Avg score of top 3 quiz : 61.333333333333336
Quiz With Highest Marks out of 3 Top Quizzes : 96
Total Marks in 3 Attempts : 184