Why line is executed even when condition is false? [duplicate] - python-3.x

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I have a function that receives a string argument and condition inside this function that checks if this argument is int or float. Although the outcome of this condition is false, the following line is still executed.
I use PyCharm IDE and Python 3.8
Here is the code.
number1 = 17
number2 = 17.1
testStr = "Test string"
def define_type(argument01):
if type(argument01) == str:
print(argument01 + " - string")
if type(argument01) == int or float:
print(str(argument01) + " - int or float")
define_type(testStr)
The output:
Test string - string
Test string - int or float
Process finished with exit code 0

if type(argument01) == int or float:
can be rewritten
if (type(argument01) == int) or float:
so even argument01 is not an int the test is always true, in a way your test is
if float:
You want :
if type(argument01) == int or type(argument01) == float:

Related

I'm using python to remove the repeated character in a string, is there any way to do this except 'not in' and set()?

I wrote a function to do this, but unfortunately, it doesn't work. Did I miss anything? I try to avoid using 'not in' and set() and anything that C++ doesn't have. But the output is either the same as the input or just no puput at all
def find(number):
global key
for m in range(len(match)):
if number == match[m]:
key = match[m]
break
else:
key = None
def find1(number1):
if number1 == None:
return True
else:
return False
a = str(input())
match = '0'
for i in range(len(a)):
b = find(a[i])
if find1(b):
match += a[i]
print(match)
I have no idea why you'd want to do this in Python in a manner that avoids "anything that C++ doesn't have", however it seemed an interesting exercise so comparable solutions in both Python and C++ below.
The solution(s) below use regular expressions (built-in re library for Python and standard library regex header for C++). Each example matches any single character as the first capture group using (.) and then uses \1+ to identify one or more repetitions of the first character matched, if this pattern matches (i.e. there is a repeated character), this operation is performed left-to-right over the entire string and the string following this operation is returned - i.e. a copy of the original string with repeated characters pruned.
Python Solution
def remove_repeated(s):
return re.sub(r'(.)\1+', r'\1', s)
s = input("Enter a string: ")
print(remove_repeated(s))
C++ Solution
#include <iostream>
#include <string>
#include <regex>
using namespace std;
string remove_repeated(string s)
{
regex r ("(.)\\1+");
return s = regex_replace(s, r, "$1");
}
int main ()
{
string s;
cout << "Enter a string: ";
cin >> s;
s = remove_repeated(s);
cout << s;
return 0;
}
Input:
tteessttiinngg
Output:
testing
Input and output the same over both Python and C++ solutions when testing.

Im trying to sort a string in js. but im missing saomething [duplicate]

This question already has answers here:
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
(2 answers)
Closed 2 years ago.
function sortStrings(stringList) {
var retval = "";
var strings = stringList.split(',');
var sortedStrings = strings.sort((a,b) => {
return a < b;
});
sortedStrings.forEach((str) => {
retval = str + ',';
} );
return retval;
}
what mistake am I making
Your compare function has an error. The logical operator < only returns either true or false while the compare is expected to return an integer. Integers <0 mean that a < b, integers =0 mean a == b and integers >0 mean that a > b.
To accomplish that with strings, you should use localeCompare:
return a.localeCompare(b)

Groovy Cast primitive type

I want to set fields dynamically in groovy so I have a java code that get datas from a database and I set groovy fields using Bindings.setVariable() in java.
I would like to know if it is possible to cast each primitive types in groovy.
String to int, String to float and so on.
So I could always send a string and cast in an other primitive times, it depends of the type of my groovy fields.
#Opal's as solution is good, but I also wanted to mention that the Groovy JDK adds some convenient primitive check and conversion methods to CharSequence, which String implements:
isDouble and asDobule
isFloat and asFloat
isLong and asLong
isInteger and asInteger
Interestingly, it isFloat seems to be greedy, returning true for floating points beyond its range.
['2', '2.2', '2' * 10, "${Double.MAX_VALUE}"].each { s ->
switch (s) {
case { it.isInteger() }:
int i = s.toInteger()
println "String '$s' -> int $i"
break
case { it.isLong() }:
long l = s.toLong()
println "String '$s' -> long $l"
break
case { it.isFloat() }:
float f = s.toFloat()
println "String '$s' -> float $f"
break
case { it.isDouble() }:
double d = s.toDouble()
println "String '$s' -> double $d"
break
default:
println "$s is not a supported primitive"
}
}
prints out
String '2' -> int 2
String '2.2' -> float 2.2
String '2222222222' -> long 2222222222
String '1.7976931348623157E308' -> float Infinity
It depends on what you exactly need, but the following piece of code works well:
assert '2' as Integer == 2
assert '2.2' as Double == 2.2

How to convert a String to an Integer in Groovy [duplicate]

This question already has answers here:
Converting a string to int in Groovy
(13 answers)
Closed 7 years ago.
How can I convert a String (which is a number) to integer in Groovy.
I am using Groovy 2.4.5. Here is a sample code which throws exception:
Code:
def String a = "CHECK";
def String b = "3.5";
def String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def int x = b.toInteger();
def int y = c.toInteger();
}
println b+c;
Output (with exceptions):
Is a number ? false
Is b number ? true
Is c number ? true
Exception thrown
java.lang.NumberFormatException: For input string: "3.5"
at myAdditionLogic.run(myAdditionLogic.groovy:12)
integer is a 32-bit number that doesn’t include a decimal point. You probably want a decimal data type, like Double.
Try this:
String a = "CHECK";
String b = "3.5";
String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def x = b as Double;
def y = c as Double;
println x + y
}

Groovy error with method mod or %

I just started to program in Groovy, I have got this error and I wanted to see if anyone could help me to work it out.
java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5
at Script1.hailstone(Script1.groovy:8)
at Script1$hailstone.callCurrent(Unknown Source)
at Script1.hailstone(Script1.groovy:11)
at Script1$hailstone.callCurrent(Unknown Source)
at Script1.hailstone(Script1.groovy:14)
at Script1$_run_closure1.doCall(Script1.groovy:1)
at Script1.run(Script1.groovy:1)
I have the following Groovy code
def list = [1,2,3].findAll{it-> hailstone(it)}
def hailstone(num){
if(num==1){
return 1;
}
println num
println num.mod(2)
if(num.mod(2)==0){
num = num/2;
return 1 + hailstone(num)
}else{
num = 3*num + 1
return 1 + hailstone(num)
}
}
​
​
and the output:
2
0
3
1
10
0
5
and then it suddenly throws an error on 5.mod(2).
Thanks in advance.
Looks like 'num' is getting coerced into a BigDecimal when you hit the line
num = num/2
If you change the signature of the hailstone method to:
def hailstone(int num) it will not crash (because the parameter will get coerced to an int on each invocation), but this may not give the results that you want, as you will lose precision, e.g. when 'num' is an odd number, and num/2 yields a decimal value, the value will be truncated.
For more info on the (sometimes surprising) way that Groovy math operations work, take a look at http://groovy.codehaus.org/Groovy+Math
After running this code, it was not producing the right output because of the findAll. Here is the code with some minor tweaks:
def list = [1,2,3].collect { hailstone(it) } // use collect, no need for the "it ->" variable it is implicit.
def hailstone(int num) { // int data type to prevent BigDecimal from being passed to mod()
if (num == 1) {
return 1 // no need for semi-colons in groovy
} else if (num % 2 == 0) { // use modulus operator
num = num / 2
} else {
num = 3 * num + 1
}
return 1 + hailstone(num) // this line happens regardless of the condition in the else if or the else
}
println list // outputs : [1,2,8]

Resources