How to make an array of words? Python - arrays

Good afternoon, I wanted to know how to make an array of letters, for example I have a list that is the alphabet:
alphabet=[chr(i) for i in range(ord('a'),ord('z')+1)]
And I want to do with this list a matrix of 5 * 5, which I have done, it has been this, but python gives me error
dimension=5
A= np.zeros((dimension,dimension))
n=0
for j in range(dimension):
for i in range(dimension):
A[i][j] = alphabet[n]
n=n+1
The error that gives me is this:
Traceback (most recent call last):
File "Cuestionario 4.py", line 217, in <module>
A[i][j] = alphabet[n]
ValueError: could not convert string to float: 'a'
Thank you for your attention

replace this
A= np.zeros((dimension,dimension))
with
A= np.chararray((dimension, dimension))
Full code should look like this
dimension=5
A= np.chararray((dimension,dimension))
n=0
for j in range(dimension):
for i in range(dimension):
A[i][j] = alphabet[n]
n=n+1

Related

Convert double for loop into recursion func

I work with two 3D arrays, which the second arr changes according to the first arr.
I try to turn double for loop into a recursive function, but the same error is repeated, RecursionErroe: maximum recursion depth exceeded in comparison.
The for loops i'm trying to convert:
def to_rec(arr):
new = arr.copy()
row_max = len(arr)
col_max = len(arr[0])
for i in range(row_max):
for j in range(col_max):
new[i, j, :] = 255- arr[i, j, :]
return new
RECURSIVE
def rec2(img, row_max, col_max, i, j, new):
if j == col_mac:
return new
else:
new[i, j, :] = 255 - img[i, j, :]
return rec2(img, row_max, col_max, i, j+1, new)
****************************************************
def rec1(img, row_max, col_max, i, j, new):
if i == row_max:
return new
else:
rec2(img, row_max, col_max, i, j, new)
return rec1(img, row_max, col_max, i+1, 0, new)
********************************************************
def to_rec(arr):
......
# The same data as in to_rac func with the for loop
......
new = rec1(arr, row_max, col_max, 0, 0, new)
return new
I can't figure out what is wrong
While this doesn't answer your question about recursion depth, I think the solution is quite simple. It seems you want to invert an image (new[i, j, 0] = 255- arr[i, j, 0]) by looping over all pixels in the image, and then manipulating the pixel value. This can be done highly efficiently using NumPy:
import numpy as np
img = load_img_data() # Replace this by your own data
new_img = 255 - np.array(img)
When your data is stored in a NumPy array, you can trivially perform scalar arithmetics (addition, multiplication, etc.) on matrices. This way you don't have to perform nested loops (or recursive operations).
The search term RecursionError: maximum recursion depth exceeded has plenty of answers on SO - the reason is simple:
you try to recuse but your function/data does not allow it:
data too big so that you would need to recurse max_depth+n times to solve it
your data (or method) will never reach the end-condition of your recursion
your function has no end condition
Your recursion is flawed and you never reach the end - hence you dive deeper and deeper and put callstack upon callstack until python raises the error to avoid a Stackoverflow from accumulated stack frames due to thousands of function calls.
Ex:
# recurses crashes every time (no end condition)
def no_end_1(k = True):
no_end_1(not k)
# recursion works if you call it with some data but not with other data
def no_end_2(i):
if i == 0:
return "Done"
no_end_2(i-1)
no_end(25) # works
no_end(-3) # crashes
def flawed_collatz_testmethod(a):
# collatz conjectur holds for numbers up to
# 2.361.183.346.958.000.000.001 (wikipedia), they converge on 1
if a%2 == 0:
new_a = a//2
else:
new_a = 3*a+1
if new_a < 1:
print ("Collatz was wrong")
else:
# will eventually end in a loop of 4-2-1-4-2-1-4-2-1-... and crash
flawed_method(new_a)
In any case .. you need to fix your function. Best way to do it is to take a small datasample, a pen and paper and draw/calculate what the function does to see why it recurses endlessly.

Adding numbers to each line in a file in haxe language

Need some help, writing a program that will read the text from a file, but will
put at the beginning of each line a number, in such a way that each line is numbered in ascending order
example:
file1
a
b
c
What I want to see:
1: a
2: b
3: c
Process:
Read contents of file into a String
Split by line ending into Array<String>
Iterate and mutate contents line by line
Join by line ending back into a String
Write back into file
Sample code for any sys target:
var arr = sys.File.getContent('file.txt').split("\n");
for(i in 0...arr.length) {
arr[i] = (i+1) + ": " + arr[i];
}
sys.File.saveContent('file.txt', arr.join("\n"));

Howto fill variant args from a loop

for the following example I need to read values from a file (no problem) and put it into the method "func (r *Regression) Train(d ...*dataPoint)" as datapoints. This works:
r.Train(
regression.DataPoint(1, []float64{1, 1, 1}),
regression.DataPoint(4, []float64{2, 2, 2}),
regression.DataPoint(9, []float64{3, 3, 3}),
)
but I would like to put it from a loop like this:
for i := 1; i <= 4; i++ {
??? regression.DataPoint(i*i, []float64{i, i, i}), ???
}
I can not use an array of dataPoint as it is only visible in that package. Here is the full source code:
https://github.com/sajari/regression (see example usage)
Thank you very much,
Maciej
From the page you linked:
Note: You can also add data points one by one.
Therefore you need:
for i := 1; i <= 4; i++ {
r.Train(regression.DataPoint(i*i, []float64{i, i, i}))
}
#Milo's answer is probably best for your particular case, but for the general case with variadic functions, you can append elements to a slice, then use the slice as the variadic argument list:
r.Train(points...)
Unfortunately the regression library is not very well-designed, as it has publicly-exposed functions that receive and return unexposed types, leaving you no way to work with them.

AS3 embedding CSV files and reading from them

So in a simple arcade/platformer game, I'm making it so I have a .csv text file set out like so:
660, 25, 0
720, 15, 1
etc..
The first number being the x coordinate, the next being the y coordinate and the last being whether the block kills you or not. Loading this data externally is not a problem and works fine but when it comes to actually running the .swf by itself obviously the .csv file is not embedded into it so I cannot access any values from it.
Therefore my question is: How can I embed a .csv file into my project and then read out 3 values per line into a multi dimensional array with each line denoting a different obstacle?
(The multi dimensional array being [obstacleID][0 for x coord/1 for y coord/2 for whether it kills or not])
How to embed a text file in Flash
then you can try:
var csv:embedded_csv = new embedded_csv();
var csvLines:Array = csv.toString().split("\n"); // \n or File.lineSeparator or \r\n
for(i=0; i<csvLines.length; i++)
{
line:Array = String(csvLines[i]).split(", ");
x = line[0];
y = line[1];
kills = line[2];
...
}

R - Loop in matrix

I have two variables, the first is 1D flow vector containing 230 data and the second is 2D temperature matrix (230*44219).
I am trying to find the correlation matrix between each flow value and corresponding 44219 temperature. This is my code below.
Houlgrave_flow_1981_2000 = window(Houlgrave_flow_average, start = as.Date("1981-11-15"),end = as.Date("2000-12-15"))
> str(Houlgrave_flow_1981_2000)
‘zoo’ series from 1981-11-15 to 2000-12-15
Data: num [1:230] 0.085689 0.021437 0.000705 0 0.006969 ...
Index: Date[1:230], format: "1981-11-15" "1981-12-15" "1982-01-15" "1982-02-15" ...
Hulgrave_SST_1981_2000=X_sst[1:230,]
> str(Hulgrave_SST_1981_2000)
num [1:230, 1:44219] -0.0733 0.432 0.2783 -0.1989 0.1028 ...
sf_Houlgrave_SF_SST = NULL
sst_Houlgrave_SF_SST = NULL
cor_Houlgrave_SF_SST = NULL
for (i in 1:230) {
for(j in 1:44219){
sf_Houlgrave_SF_SST[i] = Houlgrave_flow_1981_2000[i]
sst_Houlgrave_SF_SST[i,j] = Hulgrave_SST_1981_2000[i,j]
cor_Houlgrave_SF_SST[i,j] = cor(sf_Houlgrave_SF_SST[i],Hulgrave_SST_1981_2000[i,j])
}
}
The error message always says:
Error in sst_Houlgrave_SF_SST[i, j] = Hulgrave_SST_1981_2000[i, j] :
incorrect number of subscripts on matrix
Thank you for your help.
try this:
# prepare empty matrix of correct size
cor_Houlgrave_SF_SST <- matrix(nrow=dim(Hulgrave_SST_1981_2000)[1],
ncol=dim(Hulgrave_SST_1981_2000)[2])
# Good practice to not specify "230" or "44219" directly, instead
for (i in 1:dim(Hulgrave_SST_1981_2000)[1]) {
for(j in 1:dim(Hulgrave_SST_1981_2000)[2]){
cor_Houlgrave_SF_SST[i,j] <- cor(sf_Houlgrave_SF_SST[i],Hulgrave_SST_1981_2000[i,j])
}
}
The two redefinitions inside your loop were superfluous I believe. The main problem with your code was not defining the matrix - i.e. the cor variable did not have 2 dimensions, hence the error.
It is apparently also good practice to define empty matrices for results in for-loops by explicitly giving them correct dimensions in advance - is meant to make the code more efficient.

Resources