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

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}")

Related

getting the total of 3rd items on a list [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 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)

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.

python not understanding simple math question [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 3 years ago.
Improve this question
I am making mortgage calculator, I have provided information for variables p, i, n, but get error in the equation.
p[i(1 + i) ^ n] / [(1 + i) ^ n – 1]
What you shared is not valid python code. Here is an example of code that will accomplish what you are asking:
# define function:
def CalculateMortgage(p, i, n):
# calculate numerator:
numerator = p * (i *(1+i) ** n)
# calculate denominator:
denominator = ((1+i) ** n - 1)
# calculate mortgage:
mortgage = numerator/denominator
# return result:
return mortgage
# set variables:
p = 1
i = 1
n = 1
# call function:
mortgage = CalculateMortgage(p, i, n)
# print result:
print('Your mortgage is: ' + str(mortgage))

Difference Between Rows and fill Columns [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 8 years ago.
Improve this question
I have a text file that contains:
Week OrangeTotal ODifference AppleTotal ADifference
1 2 - 3 -
2 5 ? 4 ?
3 10 ? 10 ?
4 50 ? 100 ?
I would like it to skip the first line since it's the start of the new year, but fill in the column next to it with the subtraction of that row and the row below.
It should be:
Week OrangeTotal ODifference AppleTotal ADifference
1 2 - 3 -
2 5 3 4 1
3 10 5 10 6
4 50 40 100 90
import os
def main():
name = 'log.txt'
tmpName = 'tmp.txt'
f = open(name, 'r')
tmp = open(tmpName, 'w')
titleLine = f.readline().strip()
tmp.write(titleLine+'\n')
prevLine = f.readline().strip()
tmp.write(prevLine+'\n')
prevLine = prevLine.split('\t')
for line in f:
line = line.split('\t')
line[2] = str(int(line[1]) - int(prevLine[1]))
line[4] = str(int(line[3]) - int(prevLine[3]))
prevLine = line
displayLine=''
for i in range(len(line)-1):
displayLine += line[i]+'\t'
displayLine += line[len(line)-1]
tmp.write(displayLine+'\n')
f.close()
tmp.close()
os.remove(name)
os.rename(tmpName, name)
main()
so far I think it may be easier for you to work with each line in a for loop like for lines in ds[1:]: loop. it is also important to note that readlines produces an array of the lines of the file.
So ds[0] ='Week OrangeTotal ODifference AppleTotal ADifference'
so you need to loop over the lines
old=0 # this is to store the last value
done = list()
for i in range(1, len(ds), 1): #[range()][1]
l=0 # we define l here so that the garbage collector does not decide we no longer need it
if(old!=0): #if this is not the first one
l = ds[i].split()
# [split()][2] gets rid of whitespace and turns it into a list
for v in range(1, 3, 2):
#we skip the first value as that is the week and then next as that is the answer
ds[v+1] = ds[v] - old[v] #here is where we do the actual subtraction and store the value
old = l #when we are done we set the row we finished as old
done[i] = l.join(" ")
print(str(done[i]))
what you do with this from here is your decision
import os
import sys
ds = open("Path.txt",'r').readlines()
a = list()
b = list()
for words in ds[1:]:
a.append(words)
for words in ds:
b.append(words)
for lines in a:
again = int(lines)
for words in b:
bse = int(words)
print bse-again

Should I do anything to make my code more pythonic? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
This is a very simple piece of code that I wrote but if there is a way to make it more pythonic then I would love to know. Thanks!
def money():
current_salary = float(input("What is your current salary? "))
years = int(input("How many years would you like to look ahead? ")) + 1
amount_of_raise = float(input("What is the average percentage raise you think you will get? "))
amount_of_raise = amount_of_raise * 0.01
while years > 1:
years = years - 1
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
print('Looks like you will be making', new_salary,' in ', years,'years.')
money()
Extended assignment operators
amount_of_raise = amount_of_raise * 0.01
years = years - 1
x = x * y can be shortened to x *= y. Same thing for -.
amount_of_raise *= 0.01
years -= 1
Iteration and counting
while years > 1:
years = years - 1
Counting down causes your printouts to display backwards. I would count up. The Pythonic way to count uses range:
for year in range(1, years + 1):
print('Looks like you will be making', new_salary,' in ', years,'years.')
Computing new salary
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
I'd probably just simplify that to:
current_salary += current_salary * amount_of_raise
Or even better is to give a 5% raise by multiplying by 1.05. In code that is:
current_salary *= 1 + amount_of_raise

Categories

Resources