This question already has answers here:
Iterate through adjacent pairs of items in a Python list [duplicate]
(5 answers)
Closed 1 year ago.
lx = [92770.0, 90204.9, 89437.3, 88868.4, 88298.8, 87505.0, 86792.7, 85938.7, 84652.2, 82803.4, 80174.3, 76559.3, 71584.5]
Lx = []
I want Lx to be a list containing the average of every two adjacent numbers in lx.
eg Lx = [(92770.0 + 90204.9)/2, (90204.+89437.3)/2, etc.....
Please help
lx = [92770.0, 90204.9, 89437.3, 88868.4, 88298.8, 87505.0, 86792.7, 85938.7, 84652.2, 82803.4, 80174.3, 76559.3, 71584.5]
Lx = [sum(x) / 2 for x in zip(lx, lx[1:])]
print(Lx)
Prints:
[91487.45, 89821.1, 89152.85, 88583.6, 87901.9, 87148.85, 86365.7, 85295.45, 83727.79999999999, 81488.85, 78366.8, 74071.9]
Here is the solution
lx = [92770.0, 90204.9, 89437.3, 88868.4, 88298.8, 87505.0, 86792.7, 85938.7, 84652.2, 82803.4, 80174.3, 76559.3, 71584.5]
Lx = []
for i in range(len(lx)-1):
Lx.append((lx[i]+lx[i+1])/2)
print(Lx)
A solution using numpy broadcasting would be:
result = (np.array(lx[:-1])+np.array(lx[1:]))/2
How about this ? sorry for noob way
for i in range(len(lx)-1):
Lx.append((lx[i] + lx[i+1]) / 2)
Related
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.
This question already has answers here:
Multidimensional cumulative sum in numpy
(3 answers)
Closed 2 years ago.
Suppose I have a 2D numpy array like below
dat = np.array([[1,2],[3,4],[5,6],[7,8])
I want to get a new array with each row equals to the sum of its previous rows with itself, like the following
first row: [1,2]
second row: [1,2] + [3,4] = [4,6]
third row: [4,6] + [5,6] = [9,12]
forth row: [9,12] + [7,8] = [16,20]
So the array would be like
dat = np.array([[1,2],[4,6],[9,12],[16,20])
np.cumsum is what you are looking for:
dat = np.array([[1,2],[3,4],[5,6],[7,8]])
result = np.cumsum(dat, axis=0)
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
The following code gives an AssertionError in the last line.
However both values are printed as 10.0833333333.
p = [0,1,2,3,4,6,2,2,4,1,2,4]
cell11 = p[0:3]
cell12 = p[3:6]
cell21 = p[6:9]
cell22 = p[9:12]
x11 = sum(cell11)/float(3)
x12 = sum(cell12)/float(3)
x21 = sum(cell21)/float(3)
x22 = sum(cell22)/float(3)
x1dot = (x11+x12)/float(2)
x2dot = (x21+x22)/float(2)
xdot1 = (x11+x21)/float(2)
xdot2 = (x12+x22)/float(2)
xdotdot = (x1dot+x2dot)/float(2)
assert(xdotdot == (xdot1+xdot2)/float(2))
n=3
x11diff = ((x11-xdotdot) - (x1dot-xdotdot) - (xdot1-xdotdot))**2
x12diff = ((x12-xdotdot) - (x1dot-xdotdot) - (xdot2-xdotdot))**2
x21diff = ((x21-xdotdot) - (x2dot-xdotdot) - (xdot1-xdotdot))**2
x22diff = ((x22-xdotdot) - (x2dot-xdotdot) - (xdot2-xdotdot))**2
ssaxb = n*(x11diff+x12diff+x21diff+x22diff)
print str(ssaxb)
print str(10+(1/float(12)))
assert(ssaxb == 10+(1/float(12)))
Are ssaxb and 10+(1/float(12)) somehow stored as slightly different values?
As pointed out by #Chris_Rands printing the values will give you the reason why assert statement is failing as float values are different
import numpy as np
print(ssaxb, 10+(1/float(12))) #(10.08333333333333, 10.083333333333334)
assert(np.isclose(ssaxb, 10+(1/float(12))))
assert(round(ssaxb,7),round(10+(1/float(12)),7))
This question already has answers here:
Union of multiple ranges
(5 answers)
Closed 7 years ago.
I'm trying to remove overlapping values from a collection of ranges.
The ranges are represented by a string like this:
499-505 100-115 80-119 113-140 500-550
I want the above to be reduced to two ranges: 80-140 499-550. That covers all the values without overlap.
Currently I have the following code.
cr = "100-115 115-119 113-125 80-114 180-185 500-550 109-120 95-114 200-250".split(" ")
ar = []
br = []
for i in cr:
(left,right) = i.split("-")
ar.append(left);
br.append(right);
inc = 0
for f in br:
i = int(f)
vac = []
jnc = 0
for g in ar:
j = int(g)
if(i >= j):
vac.append(j)
del br[jnc]
jnc += jnc
print vac
inc += inc
I split the array by - and store the range limits in ar and br. I iterate over these limits pairwise and if the i is at least as great as the j, I want to delete the element. But the program doesn't work. I expect it to produce this result: 80-125 500-550 200-250 180-185
For a quick and short solution,
from operator import itemgetter
from itertools import groupby
cr = "499-505 100-115 80-119 113-140 500-550".split(" ")
fullNumbers = []
for i in cr:
a = int(i.split("-")[0])
b = int(i.split("-")[1])
fullNumbers+=range(a,b+1)
# Remove duplicates and sort it
fullNumbers = sorted(list(set(fullNumbers)))
# Taken From http://stackoverflow.com/questions/2154249
def convertToRanges(data):
result = []
for k, g in groupby(enumerate(data), lambda (i,x):i-x):
group = map(itemgetter(1), g)
result.append(str(group[0])+"-"+str(group[-1]))
return result
print convertToRanges(fullNumbers)
#Output: ['80-140', '499-550']
For the given set in your program, output is ['80-125', '180-185', '200-250', '500-550']
Main Possible drawback of this solution: This may not be scalable!
Let me offer another solution that doesn't take time linearly proportional to the sum of the range sizes. Its running time is linearly proportional to the number of ranges.
def reduce(range_text):
parts = range_text.split()
if parts == []:
return ''
ranges = [ tuple(map(int, part.split('-'))) for part in parts ]
ranges.sort()
new_ranges = []
left, right = ranges[0]
for range in ranges[1:]:
next_left, next_right = range
if right + 1 < next_left: # Is the next range to the right?
new_ranges.append((left, right)) # Close the current range.
left, right = range # Start a new range.
else:
right = max(right, next_right) # Extend the current range.
new_ranges.append((left, right)) # Close the last range.
return ' '.join([ '-'.join(map(str, range)) for range in new_ranges ]
This function works by sorting the ranges, then looking at them in order and merging consecutive ranges that intersect.
Examples:
print(reduce('499-505 100-115 80-119 113-140 500-550'))
# => 80-140 499-550
print(reduce('100-115 115-119 113-125 80-114 180-185 500-550 109-120 95-114 200-250'))
# => 80-125 180-185 200-250 500-550
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