import numpy as np
x=['a', 'b']
x=np.repeat(x,3)
x[0]="apple"
Why does my code produce ['a' 'a' 'a' 'b' 'b' 'b'] instead of ["apple" 'a' 'a' 'b' 'b' 'b']?
When you use numpy.repeat() your list will contain type numpy.str_ instead of str.
numpy.str_ is NumPy datatype used for arrays containing fixed-width byte strings. Check type(x[0]) and type ("apple") to see the difference.
Related
I have the following code for Arduino (C++). This is for a checksum consisting of 2 characters forming a base 16 value between 0 and 255. It takes int outputCheckSum and converts it to char outputCheckSumHex[3].
itoa (outputCheckSum, outputCheckSumHex, 16)
if (outputCheckSum < 16) { //Adds a 0 if CS has fewer than 2 numbers
outputCheckSumHex[1] = outputCheckSumHex[0];
outputCheckSumHex[0] = '0';
}
Since the output of itoa would be "X" instead of "0X" in the event of X having fewer than 2 characters, the last 3 lines are to move the characters one step back.
I now have plans to scale this up to a CS of 8 characters, and I was wondering whether there exists a function in C++ that can achieve that before I start writing more code. Please let me know if more information is required.
You should be able to use memmove, it's one of the legacy C functions rather than C++ but it's available in the latter (in cstring header) and handles overlapping memory correctly, unlike memcpy.
So, for example, you could use:
char buff[5] = {'a', 'b', 'c', '.', '.'};
memmove(&(buff[2]), &(buff[0], 3);
// Now it's {'a', 'b', 'a', 'b', 'c'} and you can replace the first two characters.
Alternatively, you could use std::copy from the algorithm header but, for something this basic, memmove should be fine.
You can use memmove in <cstring> for this. It does not check for terminating null characters, but instead copies num bytes (third argument) and works with overlapping regions as well.
void* memmove(void* destination, const void* source, size_t num);
I am trying to get numpy array of mixed datatypes (int, float, string):
import numpy as np
l1=['car',10,4.5]
arr=np.array(l1, dtype='|S5, i4, f8')
I am getting this error:
ValueError: invalid literal for long() with base 10: 'car'
Please help
Thanks in advance.
This works:
import numpy as np
l1= [('car',10,4.5),('train',1000,5000)]
arr=np.array(l1, dtype='|S5,i4,f8')
print(arr)
Output:
[('car', 10, 4.5e+00) ('train', 1000, 5.0e+03)]
You need to put each row inside the list as tuples so it works. For only car this works:
l1= [('car',10,4.5), ]
arr=np.array(l1, dtype='|S5,i4,f8')
I'm trying to make my own version of an "Autocorrect" program that checks for words that are similar to a given word. To accomplish this, I need to look at distances between letters on a standard keyboard, so that I have a metric for how "close" a word is to another word.
In my program I've started to write an array
const char[3]* KEY_DISTS[] = { "aa0", "ab5", "ba5", "ac3", "ca3", "ad2", "da2" ,... };
which is supposed to mean "The distance between 'a' and 'a' is 0, the distance between 'a' and 'b' is 5, the distance between 'b' and 'a' is 5, " etcetera.
That information I will next put in a map that maps pairs of characters to integers, but I'm wondering whether it's written correctly so far and whether you have any suggestions for me.
const char[3]* KEY_DISTS[]
should mean "A constant array of pointers to character arrays of size 3", right?
The declaration matching the title would be:
const char (*arr[])[4] = { &"aa0" };
Note that "arr" is an array of four chars (it includes terminating '\0') and that you need to take the address of string literal (which are lvalues and have static storage duration, so this is fine).
Sounds like you could have a 2D array instead:
const char arr[][4] = { "aa0" };
I'm messing around with an Arduino board for the first time.
I have an array declared like this (I know don't judge me), it's for storing each character of the LCD as a sort of cache:
char* lcd_characters[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
Then later on I'm trying to write to a specific slot of the array, like this, to save that letter to it:
new_char = String(message.charAt(i));
...blah blah blah...
lcd_characters[pos] = new_char; << error here
However it is giving me this error:
error: cannot convert 'String' to 'char*' in assignment
The funny thing is when I do this (below) it do assign the letter to it, however I have a var which is a single letter but can't assign it.
lcd_characters[pos] = "H";
Can someone help me out please. Thanks. I'm brand new to C and been ok so far.
Basically I want an array of characters and then I want to write on the array positions with a new value.
Why does it even matter what type of string I'm writing to that array position, I should be able to write a number or boolean there too and call it later. Is there something wrong with the way the array is declared initially?
Edit:
I tried...
lcd_characters[pos] = new_char.c_str();
however that's giving me the similar error:
invalid conversion from 'const char*' to 'char'
Wtf? All I want to do is say this array position equals this new value. That's it. I've done this a million times in javascript, ruby, python (even php) etc. I just want to go, this array... x[12] equals my letter in new_char !!!! Ahh.
A few remarks:
Are you using C or C++? String is a C++ class, but you are creating a an array of c strings (char *).
You are creating an array of strings (char* var[] equals to char**), but your naming suggests you want an array of characters. A c string is basically an array of characters, so stick with that (char * or char []).
I would recommend you go for only C code in this case:
char lcdChars[4] = {' ', ' ', ' ', ' '}; // init with spaces
lcdChars[2] = 'x'; // write x to position 3
Note: A string in C++ can output a C string (char *) by calling stringInstance.c_str().
Consider these two strings:
wchar_t* x = L"xy\x588xla";
wchar_t* y = L"xy\x588bla";
Upon reading this you would expect that both string literals are the same except one character - an 'x' instead of a 'b'.
It turns out that this is not the case. The first string compiles to:
y = {'x', 'y', 0x588, 'x', 'l', 'a' }
and the second is actually:
x = {'x', 'y', 0x588b, 'l', 'a' }
They are not even the same length!
Yes, the 'b' is eaten up by the hex representation ('\xNNN') character.
At the very least, this could cause confusion and subtle bugs for in hand-written strings (you could argue that unicode strings don't belong in the code body)
But the more serious problem, and the one I am facing, is in auto-generated code. There just doesn't seem to be any way to express this: {'x', 'y', 0x588, 'b', 'l', 'a' } as a literal string without resorting to writing the entire string in hex representation, which is wasteful and unreadable.
Any idea of a way around this?
What's the sense in the language behaving like this?
A simple way is to use compile time string literal concatenation, thus:
wchar_t const* y = L"xy\x588" L"bla";