'and' operator in python3 - python-3.x

I'm pretty new to coding but I though I understood how the 'and' operator worked. In the example I provided I would have thought that the 'False' statement would get run not the 'True' statement. Can someone enlighten me on why this is not performing as I expected?
string = 'asdf'
if 'z' and 's' in string:
True
else:
False

The and keyword is part of an expression and it should be located between two subexpressions. Here you write 'z' and 's' in string which is interpreted as:
('z') and ('s' in string)
where the first subexpression, 'z' is more or less evaluated as True, while the second subexpression is a little more sophisticated (in your example, it is also intereted as True since 's' actually is in string.
Combining both subexpressions yields True (here).
You certainly wanted to write:
if 'z' in string and 's' in string:

Just to build up on the answer above, to get the correct output that you expect from the if statement you need to specify if "z" in string and "s" in string in order for python to compute the correct meaning of what you intend it to do.
string = 'asdf'
if 'z' in string and 's' in string:
print("True")
else:
print("False")

Related

How to check if a string is alphanumeric?

I can use occursin function, but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it. Is there a neat way of doing this in Julia?
I'm not sure your assumption about occursin is correct:
julia> occursin(r"[a-zA-z]", "ABC123")
true
julia> occursin(r"[a-zA-z]", "123")
false
but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it.
If you mean its needle argument, it can be a Regex, for eg.:
julia> occursin(r"^[[:alnum:]]*$", "adf24asg24y")
true
julia> occursin(r"^[[:alnum:]]*$", "adf24asg2_4y")
false
This checks that the given haystack string is alphanumeric using Unicode-aware character class
[[:alnum:]] which you can think of as equivalent to [a-zA-Z\d], extended to non-English characters too. (As always with Unicode, a "perfect" solution involves more work and complication, but this takes you most of the way.)
If you do mean you want the haystack argument to be a Regex, it's not clear why you'd want that here, and also why "I have to pass the entire alphanumeric string to it" is a bad thing.
As has been noted, you can indeed use regexes with occursin, and it works well. But you can also roll your own version, quite simply:
isalphanumeric(c::AbstractChar) = isletter(c) || ('0' <= c <= '9')
isalphanumeric(str::AbstractString) = all(isalphanumeric, str)

How to compare a char to [ in Julia?

In Julia, I have some lines in a file that start with a [ char. To get these lines, I try to compare the first char of each line to this char, but I seem to be missing some syntax. So far, I've tried this, which returns false (for the first one) or doesn't accept the char (for the second) :
if (line[1] == "[")
if (line[1] == "\[")
What would be the proper syntax to use here ?
The canonical way would be to use startswith, which works with both single characters and longer strings:
julia> line = "[hello, world]";
julia> startswith(line, '[') # single character
true
julia> startswith(line, "[") # length-1 string
true
julia> startswith(line, "[hello") # longer string
true
If you really want to get the first character of a string it is better to use first since indexing to strings is, in general, tricky.
julia> first(line) == '['
true
See https://docs.julialang.org/en/v1/manual/strings/#Unicode-and-UTF-8-1 for more details about string indexing.
You comparing a string "[" not a char '['
Hope it solve your problem

isalnum() in python not giving expected results

string = "xyz123"
print(string.isalnum()) # this returns 'True'
string = "xy 12"
print(string.isalnum()) # this returns 'False'
string = "xy"
print(string.isalnum()) # this return 'True'
But 'xy' is not alphanumeric.
Python version 3.6.4
As #BugHunter has pointed out, isalnum() may not be helpful in your case.
You can try:
bool(re.match('^(?=.*[a-zA-Z])(?=.*[0-9])', string))
Alphanumeric means consisting of either letters and numbers or both, so that is why you received that output. Whitespace is not alphanumeric hence why it is false.

How to compare strings in groovy script

I cannot understand why my simple String equality test is returning false.
Code is:
boolean isDevelopment() {
//config.project_stage is set to "Development"
String cfgvar = "${config.project_stage}"
String comp = "Development"
assert cfgvar.equals(comp)
}
Result is:
assert cfgvar.equals(comp)
| | |
| false Development
Development
I also get false if I do:
assert cfgvar == comp
toString() is not necessary. Most probably you have some trailing
spaces in config.project_stage, so they are retained also in cfgvar.
comp has no extra spaces, what can be seen from your code.
Initially the expression "${config.project_stage}" is of GString
type, but since you assign it to a variable typed as String,
it is coerced just to String, so toString() will not change anything.
It is up to you whether you use equals(...) or ==.
Actually Groovy silently translates the second form to the first.
So, to sum up, you can write assert cfgvar.trim() == comp.
You can also trim cfgvar at the very beginning, writing:
cfgvar = "${config.project_stage}".trim()
and then not to worry about any trailing spaces.
Have you checked for trailing spaces? At least your output as one for the first Development. Try a .trim() when you compare those strings (and maybe a .toLowerCase() too)
And remember: .equals() in Groovy is a pointer comparison. What want to do is ==. Yes, just the opposite from what it is defined in Java, but the Groovy definition makes more sense :-)
Update: see comment by #tim_yates - I mixed .equals() up with .is()
On of the objects you comparing is not a String but GString, try:
cfgvar.toString().equals(comp)
However your code works with groovy v. 2.4.5. Which version are you using?

How to check if two strings can be made equal by using recursion?

I am trying to practice recursion, but at the moment I don't quite understand it well...
I want to write a recursive Boolean function which takes 2 strings as arguments, and returns true if the second string can be made equal to the first by replacing some letters with a certain special character.
I'll demonstrate what I mean:
Let s1 = "hello", s2 = "h%lo", where '%' is the special character.
The function will return true since '%' can replace "el", causing the two strings to be equal.
Another example:
Let s1 = "hello", s2 = "h%l".
The function will return false since an 'o' is lacking in the second string, and there is no special character that can replace the 'o' (h%l% would return true).
Now the problem isn't so much with writing the code, but with understanding how to solve the problem in general, I don't even know where to begin.
If someone could guide me in the right direction I would be very grateful, even by just using English words, I'll try to translate it to code (Java)...
Thank you.
So this is relatively easy to do in Python. The method I chose was to put the first string ("hello") into an array then iterate over the second string ("h%lo") comparing the elements to those in the array. If the element was in the array i.e. 'h', 'l', 'o' then I would pop it from the array. The resulting array is then ['e','l']. The special character can be found as it is the element which does not exist in the initial array.
One can then substitute the special character for the joined array "el" in the string and compare with the first string.
In the first case this will give "hello" == "hello" -> True
In the second case this will give "hello" == "helol" -> False
I hope this helps and makes sense.

Resources