getting the total of 3rd items on a list [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to write a program that adds only the third item in a list with dictionaries. Please help me. Here is my code so far.
# SalesManager Code
# pseudo sales list
sales = {"Meat Loaf": [50, 69, 19],
"Mineral Water": [5, 15, 10]
}
for key, value in sales.items():
total = total + value[2]
print(total)

Define total outside the loop:
total = 0
for key, value in sales.items():
total = total + value[2]
print(total)
print(total) # 29

you can use below one liner code to achieve this:
print(sum(v[2] for v in sales.values()))

You first need to declare your variable total:
sales = {"Meat Loaf": [50, 69, 19],
"Mineral Water": [5, 15, 10]
}
total = 0
for key, value in sales.items():
total = total + value[2]
print(total)

Related

HankerRank Problem: Unable to get a query from the array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
def compute_scores(history, queries):
scores = []
for q in queries:
score = helper(history, q)
scores.append(score)
return scores
def helper(history, query, level = 1):
points = 10
for match in history:
if match[0] == query:
if len(match) == 1:
points = points
else:
for opponent in match[1:]:
opponent_score = helper(history, opponent, level)
points += int(0.2 * level * opponent_score)
level += 1
return points
history = [[1], [2, 5, 4], [3], [4], [5, 3, 1]]
queries = [2, 1, 5]
print(compute_scores(history, queries))
It passes the first test and produces the following output in a array: 17 10 16. It failed the other test cases. Not sure why. Please help!

In Python, how can I make it so the first 2 elements of a list are added together, then the first 4, then the first 6, and so on? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am making a game where two players take turns adding a number 1 to 10 to the running total. The player who adds to get 100 wins. I stored the inputs of the players in a list, and at the end of the game, I want to display the total after every turn. The list is in the format:
allTurns = [player1move1, player2move1, player1move2, player2move2, ...]
How can I add only the first 2 elements and display them, then add only the first 4 elements and display them, and then the first 6, and so on?
for i in range(0, len(list)):
if i % 2 == 0:
print(sum(list[:i+1]))
Or
sums = []
for i in range(0, len(list)):
if i % 2 == 0:
sums.append(sums[-1] + list[i-1] + list[i])
Try this:
allTurns = [1,2,3,6,12,23]
out = []
for n in range(len(allTurns)):
if n % 2 is 1:
out.append(allTurns[n] + allTurns[n-1])
if len(allTurns) % 2 is 1:
out.append(allTurns[-1])
print(out)
I've coded it so that it could work for any situation, and not just yours.
Try this:
allTurns = [1,2,3,6,12,23,4]
out = []
for n in allTurns:
if allTurns.index(n) % 2 is 0:
i = 0
for a in range(allTurns.index(n)+2):
try:
i=i+allTurns[a]
except IndexError:
pass
out.append(i)
print(out)
This is probably as simple as it can get.

How to find the sum of average in file handling [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So..I need some help for this project. I'm starting to learn a bit about python and our discussion is about File Handling. I made the correct execution but the problem here is that I need to find the sum and the average of the given loop.
def num3():
ifile = open(r'sales.txt','w')
no_days = 7
for count in range(1, no_days+1):
print('List of Sales in Php')
sales = float(input('Day' +str(count)+ ':\tPhp'))
ifile.write(str(sales)+'\n')
ifile.close()
num3()
This should work:
def num3():
with open('sales.txt','w') as fp:
no_days = 7
print('List of Sales in Php')
total = 0
for count in range(1, no_days+1):
sales = float(input('Day' +str(count)+ ':'))
total += sales
total = total
average = total/no_days
fp.write(f'Total Value: {total}\nAverage Value: {average}')
num3()
you need to accomulate the sales in a sperate variable. and then divide it by no_days:
ifile = open(r'`enter code here`sales.txt', 'w')
no_days = 7
total_sales = 0
for count in range(1, no_days + 1):
print('List of Sales in Php')
sales = float(input('Day' + str(count) + ':\tPhp'))
total_sales += sales
ifile.write(str(sales) + '\n')
ifile.close()
print(f"sum={total_sales}")
print(f"average={total_sales / no_days}")

Print the day of the week provided the month and date (Eg. Month: 5, Day: 18 ) (Given Month:1 and Day: 1 is “Monday”) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I don't want to use the weekday function for this as it is simplified due to the conditions.
Something like this.
weekday = {
"Mon": 0,
"Tue": 1,
"Wed": 2,
"Thu": 3,
"Fri": 4,
"Sat": 5,
"Sun": 6
}
def wd(s, k):
s = list(weekday.values())[list(weekday.keys()).index(s)]
k %= 7
result = (s + k) % 7
return result
for key, value in weekday.items():
if value == wd('Sat', 1):
print(key)
Is this what you need?
import datetime
import calendar
my_date = datetime.date(2020,5,19)
print(calendar.day_name[my_date.weekday()])
prints the name of the day..

How to multiply a value each month? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I just started taking classes of python and I am trying to make a code in where the value of the first month = 1 and multiply its value by 2 next month, and then by 3 next month, and 2 next month and so on. Until it reaches 6 months. I am using this code but it only gives me Month 1 = 1 which is the initial value.
P = 1
count = 12
print ("month 1: ",P)
for month in range(count-1):
if month %2 == 0:
P = P*2
else:
P = P*3
print:("month", month+2 ,":",P)
Change
print:("month", month+2 ,":",P)
to
print("month", month+2 ,":",P)
I'm not sure why python didn't complain about the colon. You can actually put anything there
weird: ("month", month+2 ,":",P)
And it won't complain. Awesome mistake, thanks!
Remember that range(count-1) will return numbers between 0 and 11 (the last number is non-inclusive)
Your logic could be like this:
(a) A counter that starts at 1 (cnt)
(b) A loop that watches for the counter to reach 6, then exits
(c) A running total (month_val or some such)
cnt = 1
month_val = 1
while cnt < 7:
month_val = month_val * cnt
print(month_val)
cnt += 1
The above assumes that you retain the new value of month_num -- but re-reading your question, you might just want to print the values 1 to 6, in which case the month_num value should just remain 1 all the time:
cnt = 1
month_val = 1
while cnt < 7:
print(month_val * cnt)
cnt += 1
You can define a dictionary for your problem like
month_values={}
for i in range(1,7):
if i == 1:
month_values['Month'+str(i)]=1
elif i%2 == 0:
month_values['Month'+str(i)]=i*2
elif i%2 == 1:
month_values['Month'+str(i)]=i*3
print(month_values)
prints
{'Month1': 1, 'Month2': 4, 'Month3': 9, 'Month4': 8, 'Month5': 15, 'Month6': 12}

Categories

Resources