Addition in Dictionaries w/ Lists - python

DRAFT 1:
I am a beginner programmer and would really appreciate some help on a section of a project I am doing:
dict = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
I would like to sum up the numerical values to a variable
e.g.
total = 15
Thank you!
DRAFT 2:
Thank you for your comments. I will attach the code below:
#Ask user how many items are being checked out
item_amount = int(input("How many items will you be checking out?: "))
#Create a dictionary that creates multiple lists for our items for iteration
obj = {}
for i in range(1, item_amount + 1):
obj['l' + str(i)] = []
#For each item, prompt for name, quantity, unit price
for i in range(1, item_amount + 1):
print("ITEM {}\n".format(i))
item_name = input("Item Name: ")
item_quantity = int(input("Item Quantity: "))
item_unit_price = float(input("Unit Price: "))
item_subtotal = item_quantity * item_unit_price
print('\n')
obj['l' + str(i)] = [item_name, item_quantity, item_unit_price, item_subtotal]
#Computations
print("Item\tQuantity\tUnit Price ($)\tSubtotal")
for x, y in obj.items():
for i in range(1, item_amount + 1):
print(y[i][0]'\t'y[i][1]'\t'y[i][2]'\t'y[i][3])
print('\n')
#total =
#sales_tax = 0.8*total
#grand_total = total + sales_tax
In regards to my question, I am trying to work out total. Total is the sum of the subtotals

Use sum() built-in method:
dct = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
print(sum(v for (_, v) in dct.values()))
Prints:
15

For the draft one:
You can simple do:
dict = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
result =0
for x in dict:
result+=dict[x][1]
print (result)
to loop through all key values in the dictionary.
For the second draft you can do same the in showing the result in the end and convert numeric values to strings like this:
print(obj[x][0]+'\t'+str(obj[x][1])+'\t'+str(obj[x][2])+'\t'+str(obj[x][3]))
print('\n')
So the whole code will be:
obj = {}
for i in range(1, item_amount + 1):
obj['l' + str(i)] = []
#For each item, prompt for name, quantity, unit price
for i in range(1, item_amount + 1):
print("ITEM {}\n".format(i))
item_name = input("Item Name: ")
item_quantity = int(input("Item Quantity: "))
item_unit_price = float(input("Unit Price: "))
item_subtotal = item_quantity * item_unit_price
print('\n')
obj['l' + str(i)] = [item_name, item_quantity, item_unit_price, item_subtotal]
#Computations
print("Item\tQuantity\tUnit Price ($)\tSubtotal")
for x, y in obj.items():
for x in obj:
print(obj[x][0]+'\t'+str(obj[x][1])+'\t'+str(obj[x][2])+'\t'+str(obj[x][3]))
print('\n')
Hope I helped you. Have a nice time!!!

Related

Settling Balance in Python

Just wanted to know let's say
Person 1: Paid 66USD
Person 2: Paid 0USD
Person 3: Paid 33USD
How do I program it in a way that it sends a table that tells person 2 has to pay 33USD TO person 1 to settle an equal balance amongst all members?
print('How many people in total')
people_num = int(input())
#Get the name list of everyone
name_list = []
for num in range(0,people_num):
print("What are their names?")
name_list.append(input())
print(name_list)
#get the amount everyone paid
amount = []
for name in name_list:
print("How much did " + name + " pay?")
amount.append(float(input()))
total_amount = sum(amount)
print(total_amount)
#create empty dictionary to calculate how much one person has to pay or receive
owe = []
for x in amount:
owe.append(round(x - (total_amount/people_num),2))
info = {}
for name, amt_owe in zip(name_list,owe):
info[name] = amt_owe
print(info)```
Here is a solution
def find_transactions(info):
for i in info.keys():
# find a negative balance : user A
if info[i] < 0:
for j in info.keys():
# find a positive balance : user B
if info[j] > 0 and i != j:
# user A will pay user B
x = abs(info[i])
if x > info[j]:
x = abs(info[j])
# change values of balances of user A and B
info[j] = info[j]-x
info[i] = info[i]+x
print(f"{i} pay {x} to {j}")
return info
Let's try with different values
people_num = 3
name_list = ["a", "b", "c"]
amount = [66, 0, 33]
in : info = {'a': 33.0, 'b': -33.0, 'c': 0.0}
out :
b pay 33.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}
amount = [66, 33, 33]
in : info = {'a': 22.0, 'b': -11.0, 'c': -11.0}
out :
b pay 11.0 to a
c pay 11.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}
The simple solution to this would be to count person's balance iterating through a list.
def process_transaction(from_user, to_user, amount):
if from_user['balance'] >= amount:
to_user['balance'] += amount
from_user['balance'] -= amount
print("Transaction success")
else:
print("Transaction failed")
bob = {"balance":100}
alice = {"balance":50}
process_transaction(bob, alice, 50)
print(bob)
print(alice)
does this help you ?
def info():
return {_name: _amount for _name, _amount in zip(name_list, amount)}
def equal_balances(_info):
# Make the transaction between sender and receiver
def transaction(payment_amount):
# print(f"balance before payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")
_info[receiver] += payment_amount
_info[sender] -= payment_amount
print(f"{sender} pay {round(payment_amount, 2)} to {receiver}")
# print(f"balance after payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")
medium_amount = total_amount / people_num # get medium amount
# get hwo pay hwo
print(f'The medium amount is: {round(medium_amount, 2)}')
for sender in _info:
if _info[sender] > medium_amount:
for receiver in _info:
if _info[sender] > medium_amount > _info[receiver]:
receiver_need = medium_amount - _info[receiver]
if _info[sender] - receiver_need < medium_amount:
transaction(_info[sender] - medium_amount)
elif _info[sender] >= receiver_need:
transaction(receiver_need)
elif _info[sender] - receiver_need == medium_amount:
transaction(_info[sender] - medium_amount)
return _info
people_num = int(input('How many people in total? '))
# Get the name list of everyone
name_list = []
for num in range(0, people_num):
name_list.append(input('What are their names? '))
print(name_list)
# get the amount everyone paid
amount = []
for name in name_list:
amount.append(float(input(f'How much did {name} pay? ')))
total_amount = sum(amount)
print(total_amount)
people_info = info()
print(people_info)
people_info = equal_balances(people_info)
print(people_info)

How to add all the random generated number that was loop few times

i wanted to add all the ramdom chose item price together into another variable
import random
number_of_thing= random.randrange(0,7)
button = [True,False]
#shopping
shopping = ['shirt', 'dress','hat','jeans','water','hoodie','suit']
price = [10,20,30,40,50,60,70]
for i in range(number_of_thing):
item = random.choice(shopping)
print(f"{i + 1}. {item}")
item_tag=shopping.index(item)
item_price=price[item_tag]
print(item_price)
total_price = 0
for i in range(number_of_thing):
item = random.choice(shopping)
print(f"{i + 1}. {item}")
item_tag=shopping.index(item)
item_price=price[item_tag]
total_price += item_price
print(total_price)

How can i use ModelName.objects.aggregate(Sum('field_name')) here?

I need to use Sum() instead of
if name in ingredients.keys():
ingredients[name] += units
else:
ingredients[name] = units
but I have no idea how, because I have a long chain of relations. Here is my code:
def shopping_list_ingredients(request):
shopping_list = ShoppingList.objects.filter(user=request.user).all()
ingredients = {}
for item in shopping_list:
for x in item.recipe.recipe_ingredient.all():
name = f'{x.ingredient.title} ({x.ingredient.unit})'
units = x.count
if name in ingredients:
ingredients[name] += units
else:
ingredients[name] = units
download = []
for key, units in ingredients.items():
download.append(f'{key} - {units} \n')
return download
def shopping_list_ingredients(request):
shopping_list = ShoppingList.objects.filter(user=request.user).all()
ingredients = {}
for item in shopping_list:
#if item.recipe.recipe_ingredient.all().ingredient.unit is dict
values = item.recipe.recipe_ingredient.all().ingredient.unit.values()
total = sum(values)
#if it's list
total = sum(item.recipe.recipe_ingredient.all().ingredient.unit)

How can I fix this "ValueError: not enough values to unpack (expected 3, got 2)"?

Please help me with my assignment!
My goal is that the user can choose whose grade he/she wants to see in a certain subject. The output should be something like this:
Name: Mary , Math Grade: 98
This is what I have so far:
N = int(input("Please enter number of students: "))
while (N < 2 or N > 10):
N = int(input("Please only enter 2 - 10 students: "))
name = []
math_grade = []
science_grade = []
while (N != 0):
name.append(input('Enter name:'))
math_grade.append(input('Enter grade in math:'))
science_grade.append(input('Enter grade in science:'))
N = N - 1
record = []
record.append(name)
record.append(math_grade)
record.append(science_grade)
Class_Record = {}
for name, math_grade, science_grade in record:
Class_Record[name] = {"name": name, "math grade": math_grade, "science grade": science_grade }
I keep getting the value error at that point. I also don't know how to print it to get what I want.
If you can help me fix the error and tell me how I can print my desired output, I would be really grateful!!!
The problem is how you've organized the record list.
This line of code expects each item in record to be a sub-list with three items: name, math grade, and science grade.
for name, math_grade, science_grade in record
So it's expecting record to be something like this:
record = [
["Jim", "B", "C"],
["Mary", "A", "B"],
]
But instead, you made record to be a sub-list of names, then a sub-list of math grades, then a sub-list of science grades:
record = [
["Jim", "Mary"],
["B", "A"],
["C", "B"]
]
So when the code pulls the first item in record, it's a list of only two items, where you told it to expect three. (If you had three students, the code would have "worked", but not the way you wanted.)
So you either have to change how you put things into record to match how you're pulling them out, or change how you're pulling them out.
In fact, it seems like record is just a temporary variable that is only used to build Class_Record. If that's true, you could just build Class_Record directly:
Class_Record = {}
while (N != 0):
name = input('Enter name:')
math_grade = input('Enter grade in math:')
science_grade = input('Enter grade in science:')
Class_Record[name] = {'math_grade': math_grade, 'science_grade': science_grade)
N = N - 1
N = int(input("Please enter number of students: "))
while (N < 2 or N > 10):
N = int(input("Please only enter 2 - 10 students: "))
Class_Record = []
while (N != 0):
name = input('Enter name:')
math_grade = input('Enter grade in math:')
science_grade = input('Enter grade in science:')
temp = {'name': name, 'math grade': math_grade, 'science grade': science_grade}
Class_Record.append (temp)
N = N - 1
print (Class_Record)
You can change your code like below
N = int(input("Please enter number of students: "))
while (N < 2 or N > 10):
N = int(input("Please only enter 2 - 10 students: "))
Class_Record={}
while (N != 0):
name = input('Enter name:')
math_grade = input('Enter grade in math:')
science_grade = input('Enter grade in science:')
Class_Record[name]={"name": name, "math grade": math_grade, "science grade": science_grade}
N = N - 1
print(Class_Record)

Trying to sort data in a specific format by 3 types

So I am having issues with sorting data in the format:
Name, Score1, Score2, Score3 stored in a text file.
For example:
Zac, 0, 0, 0
Zac, 0, 0, 0
Zac, 0, 0, 0
Zac, 0, 0, 0
I need to sort it by alphabetical, highest score and average score but I am unsure on how to do this.
Could someone help me out or give me some pointers as I'm not sure where to start?
Here is the task:
Task 3
The teacher wants to use the results from students taking these quizzes to log their performance. The system should store the last three scores for each student. The teacher would like to be able to output the results of the quiz for a particular class, sorted:
• in alphabetical order with each student’s highest score for the tests
• by the highest score, highest to lowest
• by the average score, highest to lowest.
And my code so far:
import random
import csv
User = input("Student (s) / Teacher (t):")
if User == "s" or "S":
classList = []
Name = input("What is your name? ")
Class = int(input("Please enter your class: "))
CompletedTimes = int(0)
while CompletedTimes <= 2:
NumberQuestion = 0
Score = int(0)
while NumberQuestion < 10:
Symbol = random.randrange (1, 4)
if Symbol == 1:
number1 = random.randrange(1, 25)
number2 = random.randrange(1, 25)
SetQuestion = (number1 * number2)
print (number1, "x", number2)
while True:
try:
Answer = int(input("Answer: "))
break
except ValueError:
print("Enter a number")
if Answer == SetQuestion:
print ("Correct. +1")
Score = (Score + 1)
NumberQuestion = (NumberQuestion + 1)
else:
print ("incorrect")
NumberQuestion = (NumberQuestion + 1)
if Symbol == 2:
number1 = random.randrange(1, 25)
number2 = random.randrange(1, 25)
SetQuestion = (number1 + number2)
print (number1, "+", number2)
while True:
try:
Answer = int(input("Answer: "))
break
except ValueError:
print("Enter a number")
if Answer == SetQuestion:
print ("Correct. +1")
Score = (Score + 1)
NumberQuestion = (NumberQuestion + 1)
else:
print ("incorrect")
NumberQuestion = (NumberQuestion + 1)
elif Symbol == 3:
number1 = random.randrange(1, 25)
number2 = random.randrange(1, 25)
SetQuestion = (number1 - number2)
print (number1, "-", number2)
while True:
try:
Answer = int(input("Answer: "))
break
except ValueError:
print("Enter a number")
if Answer == SetQuestion:
print ("Correct. +1")
Score = (Score + 1)
NumberQuestion = (NumberQuestion + 1)
else:
print ("incorrect")
NumberQuestion = (NumberQuestion + 1)
classList.append(Score)
print ("Your final score is: ", Score)
CompletedTimes = (CompletedTimes + 1)
classList = str(classList)
classList = str(classList)[1:-1]
Class = str(Class)
Class = (Class+'.csv')
thefile = open(Class, 'w')
thefile.write(Name + ',')
thefile.write(classList)
thefile.close()
elif User == "t" or 'T':
CONTINUE CODE HERE
Assuming that your file is named "data.csv" and has the following text:
Zac, 0, 0, 0
Zac, 4, 5, 6
Zac, 0, 0, 0
Zac, 1, 2, 3
Al, 1, 2, 3
Then we can construct our code:
import csv # import csv reader
with open("data.csv", 'r') as f: # open the file
reader = csv.reader(f) # read the data
lines = [[l[0], float(l[1][1:]), float(l[2][1:]), float(l[3][1:]) for l in reader]
# sort the list
sorted(lines, key = lambda x: (x[0], max(x[1:3]),sum(x[1:3])/float(len(x[1:3]))))
# [['Al', 1.0, 2.0, 3.0],
# ['Zac', 0.0, 0.0, 0.0],
# ['Zac', 0.0, 0.0, 0.0],
# ['Zac', 1.0, 2.0, 3.0],
# ['Zac', 4.0, 5.0, 6.0]]
Because your file isn't perfectly formatted csv (there is a space in between the commas), we have to do some extra parsing. This is the breakdown of what happens at lines=:
reader contains each line from your file so we can iterate through it
for l in reader says, for each line in reader, do some action
The outermost brackets indicate that we want to store the result of these actions in a list
The innermost brackets indicate that for each line in reader, we want to build a list that holds the data from the line
In order to do math operations, we have to convert the strings to int or float types
i[0] access the first element which is the name
i[1] is the second element which is currently a string - ' 0'
i[1][1:] says given the second element, take everything from the second element to the end of the string which is '0'
float([1][1:]) says given the string '0', convert it to a float type
Then we sort the list. First, it will sort on the names, then on the max score, then on the average.
Sort list by multiple attributes
I would have an object like this:
class Grade(object):
def __init__(self, name, score1, score2, score3):
self.name = name
self.score1 = score1
self.score2 = score2
self.score3 = score3
#property
def average(self):
return float(self.score1 + self.score2 + self.score3) / 3.0
#property
def highest(self):
return max([self.score1, self.score2, self.score3])
def __repr__(self):
return "<Grade({}, [{}, {}, {}]) object at 0x{:08X}>".format(self.name, self.score1, self.score2, self.score3, id(self))
def __str__(self):
return "Grade({}, [{}, {}, {}])".format(self.name, self.score1, self.score2, self.score3)
x = Grade("Bob", 85, 92, 90)
y = Grade("Alice", 80, 75, 95)
grades = [x, y]
alphabetical = sorted(grades, key=lambda g: g.name)
highest_score = sorted(grades, key=lambda g: g.highest, reverse=True)
average_score = sorted(grades, key=lambda g: g.average, reverse=True)
def display(l):
print([str(item) for item in l])
display(alphabetical) # => ['Grade(Alice, [80, 75, 95])', 'Grade(Bob, [85, 92, 90])']
display(highest_score) # => ['Grade(Alice, [80, 75, 95])', 'Grade(Bob, [85, 92, 90])']
display(average_score) # => ['Grade(Bob, [85, 92, 90])', 'Grade(Alice, [80, 75, 95])']

Categories

Resources