Oracle 11G repeats output_put.put_line twice. How to solve this? - string

My loop is given me twice the results. As I only want it one time. What should I do?
for i in 1..length(newStudentNumber) loop
character := SUBSTR(newStudentNumber, i, 1);
newStudentNumber := newStudentNumber || case character
when 'A' then '16'
when 'B' then '17'
when 'C' then '18'
when 'D' then '19'
when 'E' then '20'
when 'F' then '21'
when 'G' then '22'
when 'H' then '23'
when 'I' then '24'
when 'J' then '25'
when 'K' then '26'
when 'L' then '27'
when 'M' then '28'
when 'N' then '29'
when 'O' then '30'
when 'P' then '31'
when 'Q' then '32'
when 'R' then '33'
when 'S' then '34'
when 'T' then '35'
when 'U' then '36'
when 'V' then '37'
when 'W' then '38'
when 'X' then '39'
when 'Y' then '40'
when 'Z' then '41'
else character
end;
end loop;
dbms_output.put_line(newStudentNumber);
I hope I am not too vague with this question
Thanks in advance

Inside your loop you are appending the possibly-converted character to the same string variable you are looping over, newStudentNumber. If you don't want both the old and new value then you need a second variable which you populate in the loop.
-- new variable, which has to be declared
convertedStudentNumber := null;
for i in 1..length(newStudentNumber) loop
character := SUBSTR(newStudentNumber, i, 1);
convertedStudentNumber := convertedStudentNumber || case character
...
else character
end;
end loop;
dbms_output.put_line(convertedStudentNumber);
Now the two variables have different values, one starting TUE..., the other starting 353620....

Related

Unable to append to array element

I'm trying to append a string to the end of an array element by using the following function:
def spread(farm):
#writing potential fruit spread
for y in range(0,len(farm[0])):
for x in range(0,len(farm[0])):
#if this current space is a tree, write the potential spaces accordingly
if farm[y][x] == "F" or farm[y][x] == "W" or farm[y][x] == "G" or farm[y][x] == "J" or farm[y][x] == "M":
for b in [-1,0,1]:
#making sure the y-coord is within the bounds of the farm
if y+b >= 0 and y+b < len(farm[0]):
for a in [-1,0,1]:
#making sure the x-coord is within the bounds of the farm and the selected space is not a tree
if x+a >= 0 and x+a < len(farm[0]) and farm[y+b][x+a] != "F" and farm[y+b][x+a] != "W" and farm[y+b][x+a] != "G" and farm[y+b][x+a] != "J" and farm[y+b][x+a] != "M":
#if space is blank, write over the space outright
if farm[y+b][x+a] == "_":
farm[y+b][x+a] = farm[y][x].lower()
else:
#wherein my troubles lie :(
farm[y+b][x+a] = farm[y+b][x+a] + farm[y][x].lower()
return farm
with the following input, an array (in farm):
[['_' '_' '_' 'F' '_' '_' '_']
['_' '_' '_' 'W' '_' '_' '_']
['_' '_' '_' '_' '_' '_' '_']
['_' '_' '_' 'J' '_' '_' '_']
['_' '_' '_' '_' '_' '_' '_']
['_' 'G' '_' '_' '_' 'F' '_']
['W' '_' '_' '_' '_' '_' 'G']]
What the function is supposed to do is to simulate spreading fruit trees. Every tree (represented by a capital letter) will spread to the adjacent squares (represented by a lowercase character or underscore). However, the very last line handles the case in which the selected array element is not an underscore. What is supposed to happen is that it will append the string to the end of the array element instead of replacing it, but instead appends nothing. The output is supposed to look something like this:
[['_' '_' 'fw' 'F' 'fw' '_' '_']
['_' '_' 'fw' 'W' 'fw' '_' '_']
['_' '_' 'wj' 'wj' 'wj' '_' '_']
['_' '_' 'j' 'J' 'j' '_' '_']
['g' 'g' 'jg' 'j' 'jf' 'f' 'f']
['gw' 'G' 'g' '_' 'f' 'F' 'fg']
['W' 'gw' 'g' '_' 'f' 'fg' 'G']]
But instead it outputs this:
[['_' '_' 'f' 'F' 'f' '_' '_']
['_' '_' 'f' 'W' 'f' '_' '_']
['_' '_' 'w' 'w' 'w' '_' '_']
['_' '_' 'j' 'J' 'j' '_' '_']
['g' 'g' 'j' 'j' 'j' 'f' 'f']
['g' 'G' 'g' '_' 'f' 'F' 'f']
['W' 'g' 'g' '_' 'f' 'f' 'G']]
What am I doing wrong?
As noted, Numpy has its own string type, which limits the length of the contained text, so that the data can be stored in a neat "rectangular" way without indirection. (This means for example that Numpy can simply do math to calculate where any element will be, rather than chasing pointers for multiple indices.)
It is possible to work around this by explicitly specifying dtype=object when we create the array. This means that Numpy will store pointers to Python objects in its internal representation; this loses a lot of the benefits, but may still allow you to write overall faster and more elegant code depending on the task.
Let's try to implement that here. My first suggestion will be to use empty '' strings for the empty spots on the farm, rather than '_'; this removes a bunch of special cases from our logic (and as we all know, "special cases aren't special enough to break the rules").
Thus, we start with:
farm = np.array([
['', '', '', 'F', '', '', ''],
['', '', '', 'W', '', '', ''],
['', '', '', '', '', '', ''],
['', '', '', 'J', '', '', ''],
['', '', '', '', '', '', ''],
['', 'G', '', '', '', 'F', ''],
['W', '', '', '', '', '', 'G']
], dtype='object')
The primary way that Numpy helps us here is that it can efficiently:
Apply operatiors and functions to each element of the array elementwise.
Slice the array in one or more dimensions.
My approach is as follows:
Create a function that tells us what saplings get planted from the local tree.
Use Numpy to create an array of all the saplings that get planted from their corresponding trees, across the farm.
Create a function to plant saplings at a location offset from their source trees, by slicing the sapling array and "adding" (+, but it's string concatenation of course) the new saplings to a corresponding slice of the farm.
Iterate over the directions that the saplings can be planted, to do all the planting.
So, let's go through that....
The first step is pretty straightforward:
# Determine the saplings that will be planted, if any, from a given source plot.
# Handling the case where multiple trees are already present, is left as an exercise.
def sapling_for(plot):
return plot.lower() if plot in 'FGJMW' else ''
Now we need to apply that to the entire array. Applying operators like + is automatic. (If you have two arrays x and y with the same number of dimensions and the same size in each dimension, you can just add them with x + y and everything is added up elementwise. Notice that x * y is not "matrix multiplication", but element-wise multiplication.) However, for user-defined functions, we need a bit of extra work - we can't just pass our farm to sapling_for (after all, it doesn't have a .lower() method, for just one of many problems). It looks like:
saplings = np.vectorize(sapling_for)(farm)
Okay, not too difficult. Onward to the slicing. This is a bit tricky. We can easily enough get, for example, the north-west slice of the saplings: it is saplings[:-1, :-1] (i.e., everything except the last row and column). Notice we are not doing two separate index operations - this is Deep NumPy Magic (TM), and we need to do things NumPy's way.
My idea here is that we can represent saplings "spreading" to the southeast by taking this northwest slice and adding it to a southeast slice of the farm: farm[1:, 1:] += saplings[:-1, :-1]. We could simply do that eight times for each compass direction of spread. But what about a generalization?
It's a little trickier, since e.g. 1: doesn't mean anything by itself. It does, however, have a built-in Python representation: the native slice type, which we can also use for Numpy indexing (and for indexing built-in sequence types, too!). So I wrote a helper function to create those:
def get_slice(dx):
return slice(dx, None, None) if dx >= 0 else slice(None, dx, None)
These are similar to range objects: the parameters are the start point, end point and "step". The idea here is that a negative value will give a slice taking that many items off the end, while a positive value will take them off the front.
That lets us write a general function to add a slice of one array to a shifted position (in the opposite corner) of a "base" array:
def add_shifted(base, to_add, dx, dy):
base[get_slice(dx), get_slice(dy)] += to_add[get_slice(-dx), get_slice(-dy)]
Hopefully the logic is clear enough. Finally, we can iterate over all the (dx, dy) pairs that make sense for spreading the saplings: everywhere within one space, except for (0, 0).
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx != 0 or dy != 0:
add_shifted(farm, saplings, dx, dy)
And we're done.
A NumPy array with a string dtype will silently truncate any strings you try to store that are too big for the dtype. Use a list of lists.

Counting the number of vowels in a string and returning the count Python?

I am a beginner and my objective is this - Write a function called count_vowels that accepts a string argument that represents a word and returns the number of vowels that are in the word.
Heres my code so far to explain:
string = 'oboe'
def count_vowels(string):
count = 0
if 'a' or 'A' in string:
count += 1
if 'e' or 'E' in string:
count += 1
if 'i' or 'I' in string:
count += 1
if 'o' or 'O' in string:
count += 1
if 'u' or 'U' in string:
count += 1
return count
print(count_vowels(string))
Where i am a bit lost is the output value. If you run this code with the word 'oboe' you get 5. makes no sense So i was wondering, do elif statements change the output? Besides that, what would I need to alter in my code to have it work properly. I feel like something is being iterated upon too many times.
thank you!
The if-conditions in form if 'a' or 'A' in string: etc. are always evaluating to True. It should be if ('a' in string) or ('A' in string):.
Also, it's necessary to evaluate these conditions in a loop, to get correct answer.
Here is example with sum() builtin:
def count_vowels(string):
return sum(ch in 'aeiou' for ch in string.lower())
print(count_vowels('oboe'))
Prints:
3

i'am trying to make a function that deletes vowels in a string

def disemvowel(word):
new_word = []
list_of_letter = list(word)
for letter in list_of_letter:
if letter == 'a' or 'A' or 'E' or 'e' or 'O' or 'o' or 'U' or 'u':
continue
else:
new_word.append(letter)
return ''.join(new_word)
Your condition is always True
You should change it to:
if letter in "aAeEiIoOuU":
When you write
if letter == 'a' or 'A'
You said "if letter is 'a' or if 'A' is not a empty string", and a is not a empty string.

How to combine a different strings under one single cell array in matlab?

I have data in different cells (mostly strings) and I would like to bring some of the data in one cell and keep the rest of the data as it is.
For instance:
A = {'1' '2' '3' '4' '5'; '6' '7' '8' '9' '10'; '11' '12' '13' '14' '15'};
The desired output should be:
B = {'1' '2' '3 4 5'; '6' '7' '8 9 10'; '11' '12' '13 14 15'};
The numbers must be separated by a space.
Using string and join in 16b makes this a bit easier than using strjoin since join works with the dimensionality of matrices.
>> A = string({'1' '2' '3' '4' '5'; '6' '7' '8' '9' '10'; '11' '12' '13' '14' '15'});
>> [A(:,1:2) join(A(:,3:end),2)]
ans =
3×3 string array
"1" "2" "3 4 5"
"6" "7" "8 9 10"
"11" "12" "13 14 15"
c{1} = 'a'
c{2} = 'b'
c{3} = 'c'
>> c{2} = 'b'
c =
'a' 'b' 'c'
>> {char(c)'}
ans =
'abc'
>> {strjoin(c, ' ')}
ans =
'a b c'
Use the strjoin method.
strjoin(A(1,1:3))
returns '1 2 3'
// Automatically has spaces.
This MATLAB method defaults to a space delimeter. However....
If you should need an additional delimeter use this
strjoin(A(1,1:3),'*')
returns '1*2*3'
B = A(:,1:2);
for count = 1:size(A)
B(count,3)=cellstr(strjoin(A(count,3:5)));
end
This is how I would do what you wanted above.
Just in case anyone here has MATLAB prior to R2013a (which does not have strjoin()) or R2013b (which does not have join()):
% The original
A = { '1' '2' '3' '4' '5'
'6' '7' '8' '9' '10'
'11' '12' '13' '14' '15'};
% The new
B = A;
B(:,3) = strcat(arrayfun(#(ii) sprintf('%s ', B{ii,3:end-1}), 1:size(B,1), 'UniformOutput', false)', ...
B(:,end));
B(:,4:end) = []
which is so fugly that it only serves as a vindication for strjoin() :)

error C2143: syntax error : missing ')' before 'constant

I keep getting this error on my project and i cant figure it out! please help!
error C2143: syntax error : missing ')' before 'constant'
the line is:
while (selection == ('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i','A','B' 'C', 'D', 'E', 'F', 'G', 'H', 'I');
also i know there is an easier way to write that line out but im not sure how i can do it. im a beginner at this so can any of you pros edit this line for me!
How many open parentheses do you have?
How many closed parentheses do you have?
Are these the same number? If not, where is one missing?
Also, the syntax a == (b,c,d) is not shorthand for a == b || a == c || a == d like you seem to think. It's actually equivalent to a == d due to the way the comma operator works.
To be completely explicit, what you actually want is this:
while (selection == 'a' || selection == 'b' ||
selection == 'c' || selection == 'd' ||
selection == 'e' || selection == 'f' ||
selection == 'g' || selection == 'h' ||
selection == 'i' || selection == 'A' ||
selection == 'B' || selection == 'C' ||
selection == 'D' || selection == 'E' ||
selection == 'F' || selection == 'G' ||
selection == 'H' || selection == 'I')
{
/* Do stuff */
}
Or, to be a lot more consice about it, you can take advantage of the fact that the letters are arranged alphabetically in the ASCII table, and write
while (tolower(selection) >= 'a' && tolower(selection) <= 'i')
{
/* Do stuff */
}
This requires inclusion of <ctype.h> for the tolower function.
Given your comments on Tyler's post, it seems like what you really want is:
while ((selection >= 'a' && selection <= 'i') || (selection >= 'A' && selection <= 'I'))
{
// loop
}
Characters can be compared as if they were numbers (because they are numbers in the CPU), which means that you can check for a range of characters using the < > <= >= operators.

Resources