I can't get an array to print like a string normally in Scala
val a = Array("woot","yeah","ok then").sorted
for (i <- a.length-1 to 0 by -1)
println(s"$i: ${a(i)}")
val ab = ArrayBuffer(for (e <- a if e != null) yield e*3)
println(ab.mkString(" "))
For some reason, this prints:
2: yeah
1: woot
0: ok then
ArrayBuffer([Ljava.lang.String;#5034c75a)
And I was expecting it to print "yeahyeahyeah wootwootwoot ok thenok thenok then", that is, the items in the array (as strings) separated by a space. Why isn't it working and what am I doing wrong?
EDIT: ok, it was showing that because I was initializing ab to be a one-element ArrayBuffer with that array as the element instead of the elements of that inner array being separate elements of the array buffer.
If you want to print each element of the array, concatenated three times, with spaces between the entries, then it's just:
println((for (e <- a) yield e * 3).mkString(" "))
it gives:
ok thenok thenok then wootwootwoot yeahyeahyeah
(and this is the right order, because you wanted it sorted alphabetically, and o < w < y)
If you want to reverse the array before printing, you can initialize it to
val a = Array("woot","yeah","ok then").sorted.reverse
I think what you meant was
val ab = ArrayBuffer((for (e <- a if e != null) yield e*3): _*)
Some shorter answer using more functional approach:
val a = Array("woot","yeah","ok then").sorted.reverse
a.map(_ * 3).map(elem => print(elem + " ")
Edit:
If you want to have a result in some new variable you can do that:
val string = a.map(_ * 3).mkString(" ")
Related
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(map(int,input().split()))
A = numpy.array(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Can anyone tell me what I am doing wrong?
I am getting error : numpy.AxisError: axis 1 is out of bounds for array of dimension 1
Also, I want the user to input the array of n x m dimensions.
How can I add the m dimension check ?
Please help.
When you are trying to append elements in the array, you are taking the elements using the map function, a map function will always return a map object and you are just appending map objects as elements to the array. So, when you are trying to access axis=1 actually there is no axis=1 present in the array because the array contains a single row with map objects.
Here is the correct code without using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(list(map(int,input().split())))
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Here is the code using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append([int(x) for x in input().split()])
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
I have a list of strings as:
strings= ['stackasdf:5;iwantthis123jasdoverflow','iwantthistoo','asdf:5;python123jasd']
Now, I want to print strings both in between two substrings(start=asdf:5; end=123jasd) and which are not.
output expected:
iwantthis
iwantthistoo
python
What I've done is:
import re
start = 'asdf:5;'
end = '123jasd'
for i in strings:
t=i[len(start):-len(end)]
if t:
print (t)
else:
print (i)
df:5;iwantthis123jasdo
iwantthistoo
python
I'm not getting the desired output as expected.
Using a regex approach we can try:
strings = ['stackasdf:5;iwantthis123jasdoverflow','iwantthistoo','asdf:5;python123jasd']
output = [re.findall(r'asdf:5;(.*?)123jasd', x)[0] if re.search(r'asdf:5(.*?)123jasd', x) else x for x in strings]
print(output) # ['iwantthis', 'iwantthistoo', 'python']
You can just use a simple for each loop and if statement to print out the correct substring of each element in the array:
strings= ['stackasdf:5;iwantthis123jasdoverflow','iwantthistoo','asdf:5;python123jasd']
for word in strings:
if "asdf:5;" in word and "123jasd" in word:
ind1 = word.index("asdf:5;")
ind2 = word.index("123jasd")
print(word[ind1+7:ind2])
else:
print(word)
output:
iwantthis
iwantthistoo
python
Use replace function & split?
strings = ['stackasdf:5;iwantthis123jasdoverflow',
'iwantthistoo',
'asdf:5;python123jasd']
for i in strings:
c = '\n' # c may be any character that is not present in your strings
i = i.replace('asdf:5;', c).replace('123jasd', c).split(c)
print(i[0] if len(i) == 1 else i[1])
print(f'{strings = }') # to show that I am not changing the original list.
Output:
iwantthis
iwantthistoo
python
strings = ['stackasdf:5;iwantthis123jasdoverflow', 'iwantthistoo', 'asdf:5;python123jasd']
I have a string :
A="ILOVEYOUMATLAB"
and I create 2 empty array:
B1=[]
B2=[]
when i used the while loop, for the first time looping, if i want the first character from the A to store in B1 array, what command i need to write?
if in Python, i just need to used append command, but if in Matlab, what is the commend need to apply?
If you have MATLAB R2016b or newer you can use the new string class' overloaded + operator to append text in a more pythonic manner:
A = 'hi';
B = "";
B = B + A(1)
Which gives you:
B =
"h"
Here I've created A as a traditional character array ('') and B as a string array (""), mainly to avoid having to index into the string array (A{1}(1) instead of A(1)).
You can also just use traditional matrix concatenation to accomplish the task:
B = [B, A(1)];
% or
B = strcat(B, A(1));
% or
B(end+1) = A(1);
Note that 4 of these approaches will continually grow B in memory, which can be a significant performance bottleneck. If you know how many elements B is going to contain you can save a lot of IO time by preallocating the array and using matrix indexing to assign values inside your loop:
A = {'apple', 'banana', 'cucumber'};
B = char(zeros(1, numel(A)));
for ii = 1:numel(A)
B(ii) = A{ii}(1);
end
you can try strcat for concatenating strings in matlab
https://www.mathworks.com/help/matlab/ref/strcat.html
Try using arrays instead of matrices. You can assign the first letter to the first position of the B1 array like this:
>> A = 'ILOVEMATLAB';
>> B1 = {};
>> B1{1} = A(1);
>> B1{1}
ans =
I
To Loop through:
for i = 1:length(A)
B1{i} = A{i};
end
I have an array containing capital and small letters. I am trying to concatenate capital letters with the following small letters in a new array. For example, I have the following array
first_array = ["A","b","C","d","e"]
and I want to obtain the following array
["Ab","Cde"] #new array
I am trying to iterate through the first array with a code that looks like this:
new_array = []
first_array.each_with_index do |a,index|
if (a!~/^[a-z].*$/)
new_array = new_array.push "#{a}"
else
new_array[-1] = first_array[index-1] + "#{a}" #the idea is to concatenate the small letter with the previous capital letter and replace the last item in the new array
end
but it does not work. I am not sure I am tackling this issue efficiently which is why I can't resolve it. Could somebody suggest some options?
If you join as a string you can then scan to get all the matches:
first_array.join.scan(/[A-Z][a-z]*/)
=> ["Ab", "Cde"]
While I prefer #Paul's answer, you could do the following.
first_array.slice_before { |s| s.upcase == s }.map(&:join)
#=> ["Ab", "Cde"]
So, you want to split your original array when next char is uppercase, and then make strings of those subarrays? There's a method in standard lib that can help you here:
first_array = ["A","b","C","d","e"]
result = first_array.slice_when do |a, b|
a_lower = a.downcase == a
b_upper = b.upcase == b
a_lower && b_upper
end.map(&:join)
result # => ["Ab", "Cde"]
I like Sergio's answer a lot, here's what I brewed up while trying it out:
def append_if_present(lowercase, letters)
lowercase << letters.join if letters.size > 0
end
first_array = ["A","b","C","d","e"]
capitals = []
lowercase = []
letters = []
first_array.each_with_index do |l, i|
if l =~ /[A-Z]/
capitals << l
append_if_present(lowercase, letters)
letters = []
else
letters << l
end
end
append_if_present(lowercase, letters)
p capitals.zip(lowercase).map(&:join)
Here's a method that uses Enumerable#slice_when :
first_array.slice_when{ |a, b| b.upcase == b && a.downcase == a }.map(&:join)
I have 2 cell arrays which are "celldata" and "data" . Both of them store strings inside. Now I would like to check each element in "celldata" whether in "data" or not? For example, celldata = {'AB'; 'BE'; 'BC'} and data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '}. I would like the expected output will be s=3 and v= 1 for AB, s=2 and v=2 for BE, s=2 and v=2 for BC, because I just need to count the sequence of the string in 'celldata'
The code I wrote is shown below. Any help would be certainly appreciated.
My code:
s=0; support counter
v=0; violate counter
SV=[]; % array to store the support
VV=[]; % array to store the violate
pairs = ['AB'; 'BE'; 'BC']
%celldata = cellstr(pairs)
celldata = {'AB'; 'BE'; 'BC'}
data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '} % 3 AB, 2 BE, 2 BC
for jj=1:length(data)
for kk=1:length(celldata)
res = regexp( data(jj),celldata(kk) )
m = cell2mat(res);
e=isempty(m) % check res array is empty or not
if e == 0
s = s + 1;
SV(jj)=s;
v=v;
else
s=s;
v= v+1;
VV(jj)=v;
end
end
end
If I am understanding your variables correctly, s is the number of cells which the substring AB, AE and, BC does not appear and v is the number of times it does. If this is accurate then
v = cellfun(#(x) length(cell2mat(strfind(data, x))), celldata);
s = numel(data) - v;
gives
v = [1;1;3];
s = [3;3;1];