so for my Numerical methods module we are requested solving a real world problem using Numerical methods and write a script for it through octave I am the last part of my project but it just doesn't want to do as I intend it to do? can someone perhaps help me here?
The section of code is as follows:
Code in question
F=1;
M=3;
input('has this met your criterion? (F/M): ')
if (F)
printf('\n'); %Spacer
printf('__________________________________________________ \n');%Divider
printf('\n'); %Spacer
printf('summation of results are as follows:');
printf('\n'); %Spacer
printf('___________________________________________\n');%Divider
printf('\n'); %Spacer
printf(__________________________________________\n');%Divider
printf('\n'); %Spacer
printf('flows (m3/s)');
QinPipe1=Q1x2=Di(1,1);
QinPipe2=Q2x2=Di(2,1);
QinPipe3=Q3x2=Di(3,1);
printf('\n'); %Spacer
printf('\n'); %Spacer
QinPipe1=Q1x2
QinPipe2=Q2x2
QinPipe3=Q3x2
printf("______________________________________\n");
printf("criterion check(percentage):\n");
printf('\n'); %Spacer
printf('\n'); %Spacer
RelError1=Q1e1=abs(((abs(Q1x)-abs(Q1x2))/abs((Q1x2))))*100;
RelError2=Q2e2=abs(((abs(Q2x)-abs(Q2x2))/abs((Q2x2))))*100;
RelError3=Q3e3=abs(((abs(Q3x)-abs(Q3x2))/abs((Q3x2))))*100;
RelError1=Q1e1
RelError2=Q2e2
RelError3=Q3e3
else if (M)
cramerwdntest
end
endif
What I need it to do is that after it has run the previous commands up until this point once the user answers with either F or M it should either print out the summation (F) of the final results from the script run earlier and if not it should run the following m file (M) again until the user eventually answers with an (F) instead no matter what letter you enter (M or F) it runs the first part of the if statement regardless
I attempted to use the "yes_or_no" function but that seemed to not work either
Could someone please help me on this.
What do F and M represent, and why do you set them to 1 and 3?
There's a lot to improve here, but to answer your question:
F=1;
M=3;
in = input('has this met your criterion? (F/M): ','s')
if in == 'F'
...
's' is used to specify that you input a string (character). You must store the input in a variable. I've called it in but you should choose a variable name that matches its purpose in your script.
You must compare the input to the character F, or input a number instead of a string.
New answer:
in = input('Is this OK? (Y / N)', 's');
while in ~= 'Y' && in ~= 'N'
in = input('Please answer with "Y" or "N". Is this OK?', 's');
end
if in == 'Y'
...
Related
Why is the else statement is not allowed to have a then or other conditions?
Is it because it is the final condition within the else-if conditions it represents?
I am struggling to understand this concept since I'm a beginner who just learned about variables.
I'm asking this because I received an error with my else statement in the code:
message = 0
condition = 30
if condition <=10
message = “try harder”
elseif
condition <=20 then
message = "Almost learning"
else
condition = <=30 **—This is the line where I get the error message**
message = "Now you’re getting it"
end
print(message)
Would appreciate someone breaking down in laymen terms, why else is not allowed to have < or > or then or other conditions.
else condition = <= 30
(which is the way your code was originally formatted) would be a very unusual feature in a language.
The whole point of else on its own is to execute if none of the other conditions were true. So a condition on the else is absolutely useless.
The Programming in Lua book if statement shows the normal usage:
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
However, your actual code (when formatted correctly) ends up looking like:
else
condition = <=30
which is correct in terms of the else but unfortunately makes the next line a statement. And this statement is very much incorrect syntax.
Now it may be that you meant to assign 30 to condition but, based on your other lines (that sort of match this as a condition), I suspect not. So it's probably best just to remove that line totally.
I'm trying to determine if it's between the hours of 12 am and 1 am. Here is my if statement:
If InStr(Time,"12") AND InStr(Time,"AM") Then
' Do something
Else
' Do something else
End If
The problem is that this statement evaluates to false, even if both of the conditions are true. I know this because I have tried a nested if like this
If InStr(Time,"12") Then
If InStr(Time,"AM") Then
' Do something
...
And that works. This also works
If InStr(Time,"12")<>0 AND InStr(Time,"AM")<>0 Then
' Do something
...
But if it works as a nested if, why can't I test both of the nested if conditions in a single if statement?
I replaced the InStr function calls with the values that they return
If 1 AND 10 Then
' Do something
Else
' Do something else
End If
And the same thing happened: the if statement evaluated as false and the "Do something else" commands were executed instead. But when I nested the second condition as another if statement inside the first if statement, the "Do something" commands were executed.
Why is that and is there any way to do this without the <>0 and without nesting?
If Time() >= TimeValue("12:00:00") AND Time() <= TimeValue("23:59:59") then
'Do Something
ElseIf Time() >= TimeValue("00:00:00") AND Time() <= TimeValue("01:00:00") then
'Do the same
Else
'Do something different
End If
This should work :)
The problem you observed is caused by the fact that VBScript uses the same operators for boolean and bit operations, depending on the data type of the operands. The InStr function returns a numeric value unless one of the strings is Null, so the operation becomes a bitwise comparison instead of a boolean comparison, as JosefZ pointed out. The behavior is documented:
The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result [...]
Demonstration:
>>> WScript.Echo "" & (True And True)
True
>>> WScript.Echo "" & (6 And 1) '0b0110 && 0b0001 ⇒ 0b0000
0
>>> WScript.Echo "" & (6 And 2) '0b0110 && 0b0010 ⇒ 0b0010
2
To enforce a boolean comparison you need to use InStr(...) > 0 or CBool(InStr(...)) (both of which evaluate to a boolean result) instead of just InStr(...) (which evaluates to a numeric result).
Date and Time are stored as number of days, where midnight is 0.0, and 1 am is 1/24 :
If Time <= 1/24 Then ' or If Time <= #1am# Then
When you using Time() function and if result like that 10:12:12 AM in this way Instr will result Ture because Instr by default use vbbinarycompare looking For any 12in binary format in 10:12:12 AM and there is sec and min 12 so it will Return True .
just try this :
myHour=replace(Time,Right(Time,9),"") 'get only the hour from time
myAMPM=replace(Time,Time,Right(Time,2)) 'get only AM or PM from time
If InStr(1,myHour,12,1) > 0 AND InStr(1,myAMPM,"AM",1) > 0 Then
wscript.echo "True"
Else
wscript.echo "False"
End If
Excuse me for the use of the term "component", there probably is a better term to use in such context.
But moving on to my question, I want to use the else statement to execute a statement block based on the truth of the test statement. Here is the test statement I tried using:
else:
if ((reply != a) && (reply != c) && (reply =! e)):
I'm getting a syntax error, and the carrot is pointing at the first set of ampersands. I'm assuming now that I might be improperly using '&&'.
With this statement, my goal is to execute the statement block only if the test statement is true, meaning further, that 'reply' must not be equal to a, c, or e.
I know that I can use nested if's under the else statement, but I'm hoping StackExchange knows a better way. Thank you.
parenthesis check :
if (((reply != a) && (reply != c)) && (reply =! e))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
def countchar(str):
list1 = [0]*26
for i in range(0,len(str)):
if (str[i] >= 'a' and str[i] <='z'):
***list1[ord(str[i])-0] += 1***
print list1
if __name__ == "__main__":
str = " GOOD morning and have a nice day"
str = str.lower()
print countchar(str)
there is an error in my code so I can achieve my goal.
Your main issue was that you needed to be subtracting ord("a") (which is 97) from each character to find its index in list1, not 0.
But I cleaned up the rest of your code too, since there were a lot of other inefficiencies and bad practices and stuff.
def countchar(sentence):
list1 = [0 for i in range(26)]
for c in sentence:
if 'a' <= c <= 'z':
list1[ord(c) - ord("a")] += 1
return list1
if __name__ == "__main__":
string = " GOOD morning and have a nice day"
string = string.lower()
print countchar(string)
In particular, it's bad practice to use keywords like str as variable names.
Also, depending on what you're planning to do with this, it's likely that a dictionary would work better for your purposes than a list.
Here's a quick rewrite (with the additional functionality that it'll count all characters, not just lowercase letters) using a dictionary:
def countchar(sentence):
char_dict = {}
for c in sentence:
if c in char_dict:
char_dict[c] += 1
else:
char_dict[c] = 1
return char_dict
if __name__ == "__main__":
string = " GOOD morning and have a nice day!!"
print "With uppercase (and punctuation, etc):"
print countchar(string)
print "All lowercase (and punctuation, etc):"
string = string.lower()
print countchar(string)
As requested in a comment, here is some clarification of the following line:
list1[ord(c) - ord("a")] += 1
First let's look at the inside, ord(c) - ord("a"). c is a string with only a single character in it, so ord(c) gives you the ASCII value for that string. Since you're mapping lowercase letters to the numbers 0, 1, ..., 25, we need to make sure that the letter "a" gets mapped to 0. Since, in ASCII, the letters are sequential (a=97, b=98, ..., z=122), then we can just subtract the smallest one from each one in order to map them:
a --> 97-97 = 0
b --> 98-97 = 1
c --> 99-97 = 2
...
z --> 122-97 = 25
So that's what ord(c) - ord("a") is doing. It's subtracting that 97 (which is the value of ord("a")) from each value, and giving a number between 0 and 25.
Then list1[ that number between 0 and 25 ] += 1 just increments the proper index in list1.
I'm at a loss why the following code doesn't work. The intention is to input a vector of strings, some of which can be converted to a number, some can't. The following 'sapply' function should use a regex to match numbers and then return the number or (if not) return the original.
sapply(c("test","6","-99.99","test2"), function(v){
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$",v)){as.numeric(v)} else {v}
})
Which returns the following result:
"test" "6" "-99.99" "test2"
Edit: What I expect the code to return:
"test" 6 -99.99 "test2
I can run the if statement on each element successfully.
> if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$","test")){as.numeric("test")} else {"test"}
[1] "test"
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$","6")){as.numeric("6")} else {"6"}
[1] 6
And etc...
I don't understand why this is happening. I guess I have two questions. One: Why is this happening? And two: Usually I'm pretty good at troubleshooting, but I have no idea where to even look for this. If you know the problem, how did you find/know the solution? Should I open up the internal lapply function code?
that happens because sapply returns a vector, and a vector can't be mixed. If you use lapply then you get a list result which can be mixed, the same code but with lapply instead of sapply works how you want it to.
#Jeremy points into right direction, you can use lapply, which returns a list. Or, you can tell sapply not to simplify result.
If simplification occurs, the output type is determined from the
highest type of the return values in the hierarchy NULL < raw <
logical < integer < double < complex < character < list < expression,
after coercion of pairlists to lists.
out <- sapply(c("test","6","-99.99","test2"), function(v){
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$",v)){
as.numeric(v)
} else {
v
}
}, simplify = FALSE)
> out
$test
[1] "test"
$`6`
[1] 6
$`-99.99`
[1] -99.99
$test2
[1] "test2"