This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 5 months ago.
I want to make a summation of the collected data from a while loop because I want to calculate Youtube video duration to divide them into days. I want to make something which collects the final answer from each loop and makes a summation process of them. How can I do that?
My code is:
while True:
def youtube_calculater(x):
return x * 60
a = youtube_calculater(float(input("enter minutes: ")))
def sum_operation(y):
return a + y
b = sum_operation(float(input("enter seconds: ")))
def final_operation(n):
return n / 60
s = final_operation(b)
print(s)
You could store every calculated s inside a list (I named it s_list in the example) and then use sum() to calculate the sum of all the entries.
s_list = []
while True:
def youtube_calculater(x):
return x * 60
a = youtube_calculater(float(input("enter minutes: ")))
def sum_operation(y):
return a + y
b = sum_operation(float(input("enter seconds: ")))
def final_operation(n):
return n / 60
s = final_operation(b)
s_list.append(s)
print(s)
print(sum(s_list))
If you dont care about every entry in the list. You can just create a variable sum_s the same way and always add s to the sum using sum_s += s.
Related
I have done the Recursive function in Python that works:
def Rec(n):
if (n<=5):
return 2*n
elif (n>=6):
return Rec(n-6)+2*Rec(n-4)+4*Rec(n-2)
print (Rec(50))
But I can't think of an iterative one
I am sure I will need to use a loop and possibly have 4 variables to store the previous values, imitating a stack.
For your particular question, assuming you have an input n, the following code should calculate the function iteratively in python.
val = []
for i in range(6):
val.append(2*i)
for i in range(6,n+1):
val.append( val[i-6] + 2*val[i-4] + 4*val[i-2] )
print(val[n])
I get this answer:
$ python test.py
Rec(50) = 9142785252232708
Kist(50) = 9142785252232708
Using the code below. The idea is that your function needs a "window" of previous values - Kn-6, Kn-4, Kn-2 - and that window can be "slid" along as you compute new values.
So, for some value like "14", you would have a window of K8, K9, ... K13. Just compute using those values, then drop K8 since you'll never use it again, and append K14 so you can use it in computing K15..20.
def Rec(n):
if (n<=5):
return 2*n
elif (n>=6):
return Rec(n-6)+2*Rec(n-4)+4*Rec(n-2)
def Kist(n):
if n <= 5:
return 2 * n
KN = [2*n for n in range(6)]
for i in range(6, n+1):
kn = KN[-6] + 2 * KN[-4] + 4 * KN[-2]
KN.append(kn)
KN = KN[-6:]
return KN[-1]
print("Rec(50) =", Rec(50))
print("Kist(50) =", Kist(50))
This question already has answers here:
How can I return two values from a function in Python?
(8 answers)
Closed 6 years ago.
I'm trying to get some help in returning values from "year_calc" function below (Python 3.5). In essence, the code works for returning "b" as I need a new starting value for "b" to be passed to "year_calc" for each iteration - I can get that to work just fine. However, I want the "total_cost" value from each year_calc iteration to be returned and added up until finished. Note the "grand_total" under the while loop. I realize this doesn't work as stated - just adding it so it may add clarity to what I'm attempting to accomplish. I am just not sure how to pull a specific value which is being returned. Any insight?
def main():
archive_total = float(input('Enter archive total (GB): '))
transfer_rate = float(input('Enter transfer rate (Gbps): '))
days_to_transfer = ((((archive_total*8/transfer_rate)/60)/60)/24)
xfer_per_day = archive_total/days_to_transfer
day_cost = xfer_per_day * 0.007 / 30
days = 365
total_days = 0
sum = 0
b = xfer_per_day * 0.007 / 30
total_years = 1
grand_total = 0.0
total_cost = 0.0
while total_years < years_to_transfer + 1:
b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
total_years += 1
grand_total += total_cost
def year_calc(day_cost,days,total_days,sum,b,total_years,total_cost):
while total_days < days -1:
b += day_cost
sum += b
total_days += 1
total_cost = sum + day_cost
print('Year',total_years,'cost: $', format(sum + day_cost, ',.2f'))
return (b, total_cost)
main()
year_calc, as with any function that returns multiple items, will return its values in a tuple. Therefore, you can just change this line:
b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
to this one:
b, total_cost = year_calc(day_cost, days, total_days, sum,b,total_years)
This works because of how Python handles multiple assignment:
>> a, b = 1,2
>> print a
1
>> print b
2
As an aside, you should try to avoid using builtin names like sum for your variables. And I'm not sure what years_to_transfer is - do you define that elsewhere in your code?
If I understand correctly your description correctly, this implements what you want:
def main():
# ...
total_cost = 0.0
while total_years < years_to_transfer + 1:
b, total_cost = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
# ...
def year_calc(day_cost,days,total_days,sum,b,total_years,total_cost):
# ...
return (b, total_cost)
main()
Hmm, seems a bit like trying to code VBA in Python... :-)
Ok, first: I don't think you want to pass total_cost to the function year_calc, as you do not depend on any value you get. So remove it from the definition line:
def year_calc(day_cost,days,total_days,sum,b,total_years):
...
Next: you calculate a new value for total_cost and return a tupple from the function. That's pretty correct.
Now, when callin year_calc you should remove the total_cost variable from calling the function. But you should remember that you return a tupple, so assign the value to a tupple:
(b, total_cost) = year_calc(day_cost, days, total_days, sum,b,total_years)
Bottom line: there are no ref variables (or output variables, ...) to be sent in a function in python. Put in the parameters, nothing more. If you want to return 2 different calculations, return a tupple, but assign the value also to a tupple. Much cleaner.
My program is meant to calculate the standard deviation for 5 values given by the users. There is an issue with my code when getting the input in a for loop. Why is that?
givenValues = []
def average(values):
for x in range(0, 6):
total = total + values[x]
if(x==5):
average = total/x
return average
def sqDiff(values):
totalSqDiff = 0
sqDiff = []
av = average(values)
for x in range(0,6):
sqDiff[x] = (values[x] - av)**2
totalSqDiff = totalSqDiff + sqDiff[x]
avSqDiff = totalSqDiff / 5
SqDiffSquared = avSqDiff**2
return SqDiffSquared
for counter in range(0,6):
givenValues[counter] = float(input("Please enter a value: "))
counter = counter + 1
sqDiffSq = sqDiff(givenValues)
print("The standard deviation for the given values is: " + sqDiffSq)
There are several errors in your code.
Which you can easily find out by reading the errormessages your code produces:
in the Function average
insert the line total = 0
you are using it before asigning it.
List appending
Do not use for example
sqDiff[x] = (values[x] - av)**2
You can do this when using dict's but not lists! Since python cannot be sure that the list indices will be continuously assigned use sqDiff.append(...) instead.
Do not concatenate strings with floats. I recommend to read the PEP 0498
(https://www.python.org/dev/peps/pep-0498/) which gives you an idea on how string could/should be formated in python
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 7 years ago.
Given below is my code for the kadane's algorithm in Python 2.7 for returning the maximum sub array. Although, i'm getting the correct maximum sum(MSS variable) ,for the given example list,
it's returning the wrong sub array. Could someone please explain to me why ?
A = [-2,1,-3,4,-1,2,1,-5,4]
M = max(A)
L = len(A)
if(M < 0):
print M
ans = []
subans = []
MSS,subsum,i = 0,0,0
while(i<L):
subans.append(A[i])
subsum = sum(subans)
if(subsum<0):
subans=[]
i+=1
else:
if(subsum>MSS):
MSS=subsum
ans=subans
i+=1
else:
i+=1
print ans
Your issue is because when you do -
ans=subans
You are just storing the reference of subans to ans , when you change something within subans, the changes also reflect in ans (as they are the same reference).
You need to store a copy of subans in ans , instead of the direct reference.
Example -
ans = []
subans = []
MSS,subsum,i = 0,0,0
while(i<L):
subans.append(A[i])
subsum = sum(subans)
if(subsum<0):
subans=[]
i+=1
else:
print('subsum - ' + str(subsum))
print('MSS - ' + str(MSS))
if(subsum>MSS):
MSS=subsum
ans=list(subans) #more ways to do this, like subans[:] also works, and copy.copy(subans) , etc.
i+=1
else:
i+=1
Trying to iterate through a number string in python and print the product of the first 5 numbers,then the second 5, then the third 5, etc etc. Unfortunately, I just keep getting the product of the first five digits over and over. Eventually I'll append them to a list. Why is my code stuck?
edit: Original number is an integer so I have to make it a string
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
print (product_of_digits(a))
Let me list out the mistakes in the program.
You are iterating over d for nothing. You don't need that.
s += 1 is not part of the while loop. So, s will never get incremented, leading to infinite loop.
print (product_of_digits(a)) is inside the function itself, where a is not defined.
To find the product of all the consecutive 5 numbers, you cannot loop till the end of d. So, the loop should have been while s <= (len(d)-5):
You have initialized k, but used it nowhere.
So, the corrected program looks like this
def product_of_digits(number):
d, s = str(number), 0
while s <= (len(d)-5):
print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4]))
s += 1
product_of_digits(123456)
Output
120
720
You can also use a for loop, like this
def product_of_digits(number):
d = str(number)
for s in range(len(d) - 4):
print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4]))
There are a few problems with your code:
1) Your s+=1 indentation is incorrect
2) It should be s+=5 instead (assuming you want products of 1-5, 6-10, 11-15 and so on otherwise s+=1 is fine)
def product_of_digits(number):
d = str(number)
s = 0
while s < (len(d)-5):
print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 5 (see point 2)
print (product_of_digits(124345565534))
numpy.product([int(i) for i in str(s)])
where s is the number.