I want to get the updated values of sigma1 at every iteration and I have sigma[0] = 0.021. But there is an error. I present the expected output.
sigma = []
for t in range(0, 3):
sigma[0] = 0.021
sigma1 = sigma[t] - 0.001
print(sigma1)
The error is
in <module>
sigma[0] = 0.021
IndexError: list assignment index out of range
The expected output is
[0.021, 0.02, 0.019]
Your list is empty at first, so you can't get 0 index of it.
You probably want to set an initial value for you sigma:
sigma=[0.021]
for t in range(2):
sigma.append(sigma[t]-0.001)
print(sigma)
sigma=[0.021, 0, 0]
"""
if there are n element in the list
sigma=[0] * 5
sigma[0] = 0.021
"""
# iterate over the list from 1st index to 3rd index.
for elem in range(1,3): # replace 3 with n is n numbers are there.
# update the list with the previous element minus 0.001
sigma[elem] = sigma[elem-1] -0.001
print(sigma)
Related
I'm creating a code in python that repeats 10 times, but at the end of the code I would like the data generated in it to be added to the second round for sum, in the third round to take the data generated in the two and so on....
I want the values of the variable ano2 to be added.
my code is as follows:
time = 10
while time > 0:
pls = [10, 80, 5, 0]
mass = [0.1, 1, 3, 4]
agua = 40
rep = [item * 0.1 for item in pls]
seed = [A / B if A > 0 else 0 for A, B in zip(rep, mass)]
print(seed)
seed_bank = [item * 0.60 for item in n_seed]
print(seed_bank)
if agua in range(30,50):
germ_seed = seed_bank
else:
germ_seed = (tuple (item * 0.20 for item in seed_bank))
print(germ_seed)
ano2 = [ A - B for A, B in zip (seed_bank, germ_seed)]
print(ano2)
tempo -= 1
I already tried to insert pls = [10, 80, 5, 0] + year2 but so far it didn't work, gives me the error NameError: name 'ano2' is not defined
Could you maintain a variable outside the loop to keep track of your sum/previous loops? This could also be a list of lists that if you swap your loop condition around can be indexed and used in later loops. Hope this helps!
time = 0
total = 0
l_total = []
while time < 10:
total = total + 1
time = time + 1
# List of lists
l_total.append(['I', 'Calculated', 'this!'])
# Can reference last loops list by using the time counter
if len(l_total) > 1:
print(l_total[time - 1])
def foo(x, a, b, i, j):
k = j
ct = 0
while k > i-1:
if x[k] <= b and not (x[k] <= a):
ct = ct + 1
k = k - 1
return ct
x = (11,10,10,5,10,15,20,10,7,11)
y = [10000000000000000000]
m = 0
while m < 10000000000000000000:
y[m] = m
m = m +1
print(foo(x,8,18,3,6))
print(foo(x,10,20,0,9))
print(foo(x,8,18,6,3))
print(foo(x,20,10,0,9))
print(foo(x,6,7,8,8))
# Please be careful with typos for the output of the following lines!
print(foo(y,
111112222233333, # five 1's, then five 2's, then five 3's
999998888877777, # five 9's, then five 8's, then five 7's
222223333344444, # five 2's, then five 3's, then five 4's
905003340009900023))
---------------------------------------------------------------------------
TypeError Traceback (most recent call
last) <ipython-input-17-d3d2cd54b367> in <module>()
14
15 while m < 10000000000000000000:
---> 16 y[m] = m
17 m = m +1
18
TypeError: 'int' object does not support item assignment
In python, when you write y = [10000000000000000000], you are creating an array with a single item in index 0, which has 10000000000000000000 as value. And, maybe, your idea was to define an array with 10000000000000000000 items in it?
If that is the case, what you want to do is: y = [] to initialize an array/list. In python, you don't specify the size of arrays, they are dynamic. But you need to use methods to remove or to add new items. You can change an existing item by using index, though.
If you fix that, you will still get an Exception where the arrow is pointing at, in the Traceback, because you are trying to modify the value of an index that does not exist. Since you instantiated the array as y = [10000000000000000000], you only have a value in index 0. It works the first time, because the loop starts at index 0, when it sets y[0] = 0. But when m get incremented and it tries y[1] = 1, the array does not have that index, which will raise IndexError: list assignment index out of range.
If you want to initialize an array with 10000000000000000000 items in it, you could do:
y = []
for i in range(10000000000000000000):
y.append(i)
or
y = [i for i in range(10000000000000000000)]
More about range() function: https://docs.python.org/3/library/functions.html#func-range
More about array/list: https://docs.python.org/3/tutorial/datastructures.html
Assuming that I have students’ answers in a range 0-5 in a list and the target is to convert the range to 0-10. I wrote a small python function (based on a previous post: Convert a number range to another range, maintaining ratio) to do this conversion in order to proceed to the next step of my analysis pipeline. The major problem here is that the output list doesn’t include zeros and only stores everything above zero. (It cannot pass zero from input to output).
Here is the list that I have used as INPUT :
value
1
0
0
0
0
0
0
3
and now the code with some comments :
# the appropriate libs
import pandas as pd
import csv
#read as dataframe
current_data = pd.read_csv('current.csv')
# convert it to a list
convert_to_list = current_data['value'].values.tolist()
# test the input
print(convert_to_list)
# make a function that accepts the list as an argument
def convert1to10(adf):
# initiate vars and set the ranges
OldMax = 5
OldMin = 1
NewMax = 10
NewMin = 1
NewValue = 0
# define the range
OldRange = (OldMax - OldMin)
# make new array to store the output later
new_array = []
# make a loop through the length of the list
for position in range(len(adf)):
# just set the newvalue as newmin as zero in case the input range (OldRange) is 0
if (OldRange == 0):
NewValue = NewMin
else:
# set the new range as new max - newmin
NewRange = (NewMax - NewMin)
# the new value is the current possition in the loop - the old min multiplied by the new range and divided by the old range + NewMin
NewValue = (((adf[position] - OldMin) * NewRange) / OldRange) + NewMin
# append the new value in every loop in the new_array
new_array.append(NewValue)
# return the list
return new_array
# call the funtion with the list as argument
calldef_test = convert1to10(convert_to_list)
# print the result
print(calldef_test)
And here is the output
[1.0, 5.5]
where are the zeros of the original input :
[1, 0, 0, 0, 0, 0, 0, 3]
I would like an output like :
[1.0, 0, ,0 ,0 ,0 ,0 ,0 5.5]
In if (OldRange == 0): condition you are not adding the zero in the array which you might need to add see the below code:
if (OldRange == 0):
NewValue = NewMin
new_array.append(OldRange)
else:
# set the new range as new max - newmin
NewRange = (NewMax - NewMin)
# the new value is the current possition in the loop - the old min multiplied by the new range and divided by the old range + NewMin
NewValue = (((adf[position] - OldMin) * NewRange) / OldRange) + NewMin
# append the new value in every loop in the new_array
new_array.append(NewValue)
I have simple function which returns matrix of zeros and ones. I can't understand how line: out[range(n), vec] = 1 works. Vector v can have values from 0 to 9.
import numpy as np
def one_hot_encode(vec, vals=10):
n = len(vec)
out = np.zeros((n, vals))
out[range(n), vec] = 1
return out
v = [1,2,3,1,3,5,7,8,9,1,2,3,4,5,6,7,8,9,0,1,2,3,1,3,5,7,8,9,1,2,3]
one_hot_encode(v, 10)
the line line: out[range(n), vec] = 1 is placing the one corresponding to vec values i.e. if vec has first value 1 then in out matrix first row and second column(value +1) will be assigned as 1. if 4rt value is 1 then 4rt row and second column will be assigned 1.
I have a dataset like
x y
1 0.34
2 0.3432
3 0.32
4 0.35
5 0.323
6 0.3623
7 0.345
8 0.32
9 0.31
10 0.378
11 0.34
12 0.33
13 0.31
14 0.33
15 0.34
For this dataset I want to perform a task which will go through my dataset and will count the number of occurrences above a cutoff if the length of occurrence is above M.
The cutoff and M will be system arguments.
So if the cutoff is 0.32 and M is 1 it will print out a list like
[2, 4, 3, 2]
Logic: First two values in second column are above 0.32 and the length of the is greater than M=1 hence it printed out 2 and 4,3,2 so on.
I need a help to write the argument so that if x >cutoff and length of broken is >M it will print out the length of broken frames (so the same out put as above). Any help?
The structure should look like following (I am not sure how to place the argument in place of XXX)
def get_input(filename):
with open(filename) as f:
next(f) # skip the first line
input_list = []
for line in f:
input_list.append(float(line.split()[1]))
return input_list
def countwanted(input_list, wantbroken, cutoff,M):
def whichwanted(x):
if(wantbroken): return x > cutoff
else: return x < cutoff
XXX I think here I need to add the criteria for M but not sure how?
filename=sys.argv[1]
wantbroken=(sys.argv[2]=='b' or sys.argv[2]=='B')
cutoff=float(sys.argv[3])
M=int(sys.argv[4])
input_list = get_input(filename)
broken,lifebroken=countwanted(input_list,True,cutoff,M)
#closed,lifeclosed=countwanted(input_list,False,cutoff,M)
print(lifebroken)
#print(lifeclosed)
Or maybe there is a simpler way to write it.
You are OK with using numpy, which makes life a lot easier.
First off, let's take a look at the file loader. np.loadtxt can do the same thing in one line.
y = np.loadtxt(filename, skiprows=1, usecols=1)
Now to create a mask of which values that make up your above-threshold runs:
b = (y > cutoff) # I think you can figure out how to switch the sense of the test
The rest is easy, and based off this question:
b = np.r_[0, b, 0] # pad the ends
d = np.diff(b) # find changes in state
start, = np.where(d > 0) # convert switch up to start indices
end, = np.where(d < 0) # convert switch down to end indices
len = end - start # get the lengths
Now you can apply M to len:
result = len[len >= M]
If you want to work with lists, itertools.groupby also offers a good solution:
grouper = it.groupby(y, key=lambda x: x > cutoff)
result = [x for x in (len(list(group)) for key, group in grouper if key) if x >= M]