python finding high value among slices of array - python

Below are snippets of code that is giving me some problems. what i am trying to do is find every occurrence of a 356 day high. To do this i am trying code similar to the one below, but getting an exception on the "for i" line: 'builtin_function_or_method' object has no attribute 'getitem'
Quote = namedtuple("Quote", "Date Close Volume")
quotes = GetData() # arrray
newHighs = []
for i,q in range[365, len(quotes)]: #<--Exception
max = max(xrange[i-365, i].Close) #<--i know this won't work, will fix when i get here
if (q.Close > max):
newHighs.append(i,q)
Any help on fixing this would be appreciated. Also any tips on implementing this in an efficient manner (since quotes array currently has 17K elements) would also be nice.

range is a function that returns a generator (or list in python2). Thus, it must be called as a function range(365, len(quotes)), which will return all the numbers from 365 to len(quotes).
Square brackets imply indexing, like accessing items in a list. Since range is a function, not a list, it throws an exception when you try to access it.

"Range" is a function. This means you use circle brackets, not square ones. This is the same deal with "xrange" in the line below. I understand why you'd think to use the square brackets, but what "range" does is create the list using those arguments. So it's not the same as when you want elements m to n of a list.

Related

python Recursion function dought

I got an answer to my task in python.But I had a dought that
what is the difference between the empty list inside the function and outside the function?
why i am asking this because, my expected output came while i am declaring the empty list outside the function but not inside the function. Also I dont know how the output value in my list (5230) came in my output ? first three output value i know what happening in my program but last value in my list i dont know how that value came ?
my task question is
A 10-SUBSTRING OF A NUMBER IS A SUBSTRING OF ITS DIGITS THAT SUM UPTO 10 ALSO BE IN A ORDERED SEQUENCE OF THE GIVEN STRING ?
THE STRING IS '3523014'
EXPECTED OUTPUT : ['352','523','23014','5230']
MY CODE USING RECURSION.
l=[]
def ten_str(s):
x,z,p=0,1,1
for i in s:
x+=eval(i)
if x==10:
l.append(s[:z])
ten_str(s[p:])
p+=1
z+=1
return l
print(ten_str('3523014'))
If you create the empty list inside the function, then each time the function is recursively called it will create a new empty list. Strings meeting the condition will be lost when that recursive call ends, rather than being added to the global list. I find http://pythontutor.com/ helps a lot with recursion exercises.
Based on your question, a 10-substring is a set of values in the original order of the list when added sum up to 10.
5+2+3+0 = 10. Your list 3523014 contains 5230

Double variable in print function possible matrix operation

I have a simple list stated as a non-matrix. The print function calls on the variable in two manners than a location. I am unable to find materials explaining why the answer rendered is rendered when ran. I would like a walk through if possible so I can understand.
I've tried to look the solution up though I may be using improper keywords.
lst=[3,1,-2]
print(lst[lst[-1]])
I understand its a list with the variable lst containing 3,1,-2 in the 0,1,2 location left to right or -1,-2,-3 location right to left. What does the lst in brackets do that causes the answer to be 1 instead of -2?
The term lst[-1] returns -2 and now when this passed again to lst, like lst[-2] it returns second last element that is 1, if you want -2 as your answer just do print(lst[-1])

Python 3 - assignments within a loop

So, I have a large number of arrays that I need a mean value for. To try and simplify I'm attempting to use a for-loop, but I'm not sure if this is possible or if it is, how I can name the left-hand of the assignment line. I've tried:
for data in data_list:
data + _mean = np.mean(data)
This gives a syntax error; can't assign to operator. I feel like that's a lame try, but I'm very new to coding and I'm not sure what I can do on the left-hand side to make each assignment have a unique name.
Thanks for your time!
Don't try to give each value a unique name, put them in a list. You can use a list comprehension for this.
means = [np.mean(data) for data in data_list]

SyntaxError: can't assign to function call (For Loop)

Hi I am trying to create a new array from a previous array. such that in new array the first element is mean of first 20 elements from existing array. Here is my code. I am not sure why its not working.
#Averages
RPMA=[]
for i in range(9580):
for j in range (0,191600):
a=RPM.iloc[j:j+20]
RPMA(i)= a.mean()
Looks to me like you're using the wrong kind of brackets. This line:
RPMA(i)= a.mean()
...should probably be this:
RPMA[i]= a.mean()
But I'm no Python expert. I guessing that it thinks RPMA(i) is a function because you use parentheses, in which case you would be trying to assign a value to a function call, like the error says.
However trying to assign a new value past the end of the array will result in an IndexError because the array element doesn't exist, and will need to be added. What you can do instead is this:
RPMA.append(a.mean())
...which will append the data to the end of the array (i.e. adding a new element).
Thanks everyone. As suggested by most of you, I made below changes in code and now its working just fine!
RPMA=[]
for j in range (0,191600, 20):
a=RPM.iloc[j:j+19]
RPMA.append(a.mean())

Failing to understand simple error message

I've defined a function as below to try to interpolate between two sets of data. When I run it, I get the message:
for i, j in range(0, len(wavelength)):
TypeError: 'int' object is not iterable
I'm not sure what I'm doing wrong. Admittedly, I'm not very good at this.
def accountforfilter(wavelength, flux, filterwavelength, throughput):
filteredwavelength=[]
filteredflux=[]
for i in range(0, len(wavelength)):
if wavelength[i] in filterwavelength[j]:
j=filterwavelength.index(wavelength[i])
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*throughput[j])
elif wavelength[i]<filterwavelength[j]<wavelength[i+1]:
m=((throughput[j+1]-throughput[j])/(filterwavelength[j+1]-filterwavelength[j])
c=throughput[j]-(m*(wavelength[i]))
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*(m*wavelength[i]+c)
return filteredwavelength, filteredflux
range() returns a list of integers. By using for i,j in range() you are telling Python to unpack each item in range() to two values. But since those values are integers, which are a single piece of data, and thus not iterable, you get the error message.
Your code also looks a bit strange.
At first it seems like you want to loop over all combinations of wavelength/filterwavelength, which would be the same as
for i in range(len(wavelength)):
for j in range(len(filterwavelength)):
do_stuff()
but then you are modifying the j parameter inside the loop body, which I don't understand.
Regardless, there is probably a lot easier, and more clear, way to write the code you want. But from the current code it is hard to know what is expected (and should probably go in a separate question).
The problem is that the range only works with one variable like so:
for i in range(0, len(wavelength))
You try to use two variables at once so python tries to unpack an integer which is impossible. You should use the above. If you need two independent indices, use
for i in range(0, len(...))
for j in range(0, len(...))
Btw ranges always start with zero so you can save yourself some typing and use range(len(...)) instead.
You can use zip if you want.
check this: Better way to iterate over two or multiple lists at once
if you have two sets of data.
for i,j in zip(set1,set2):
print i,j

Categories