How can I convert m and n to long int or double in Python 3.4? Currently for large integers (ex:65535), the output is 'None'?
m = eval(input("Enter value for m: "))
n = eval(input("Enter value for n: "))
>>> float("1234.56")
1234.56
>>> int("1234")
1234
>>> long("12345678910")
12345678910
The float() and int() operators will be sufficient, as Python floats are usually the equivalent of C doubles, and if the integer is too large, int() will cast it to a long int. However, the long() operator will work if you want to explicitly cast to a long.
Python Numeric Types Docs for more info.
The eval() function is not a type casting operator, but rather evaluates strings or code objects as Python code, which can lead to problems if you're not careful:
>>> eval("1+2")
2
input() returns a string, which when evaluated returns None. If you're trying to assign an integer value to your variables, use the int() function:
m = int(input("Enter value for m: "))
n = int(input("Enter value for n: "))
Also, using eval is almost always a bad idea, as it runs the input as Python code, with the permissions of the script. If you must translate input, consider using ast.literal_eval instead.
Related
I am always fascinated to see how scala always infers the type correctly . How scala does it?
scala> val num = 5
num: Int = 5
scala> val num = "5"
num: String = 5
I know it might be a very stupid question to ask here but i don't know the answer.
Please enlighten me.
Thanks!
There are several methods for inferencing the type of a variable. Mainly using those called inference rules based in logic theory.
There are plenty of papers explaining the theory behind. Here I put a good example (with Scala ;) )
www2.in.tum.de/hp/file?fid=879
While parsing the code compile can infer that 5 is of type Int and "5" is of String type.
In simple terms any value enclosed in double quotes " will be considered String, value enclosed in single quote ' is considered Char and digits are considered Int (unless specified otherwise).
This is further used to used to infer types for expression results.
Consider this example
val a = 5 // translates to val a:Int = 5
val b = "5" // translates to val b:String = "5"
val x = a+1 // expression 1
val y = b+1 // expression 2
In this example the code type of a is inferred as Int and type of b is inferred as String.
Based on this expression 1 calls function Int.+(x: Int): Int which returns Int, hence type of x is guessed to be Int.
Similarly expression 2 calls function StringOps.+(arg0: Any): String which returns String, hence type of y is guessed to be String.
I am creating a simple function in Scala
def addOne(m: Int): Int = m + 1
Using it with integers works normally, using double it throws a type mismatch error.
addOne(2) = 3
addOne(2.1) = error: type mismatch
When I use it with a character in double quotes, it throws a type mismatch as expected.
addOne("z") = error: type mismatch
However, when using a single quotes character it returns a value for that letter.
addOne('z') = 123
What is happening here and why is it like this?
The reason you can use a Char as an argument to a function taking an Int is because Scala performs an implicit conversion from Char to Int. This specific conversion is defined in the companion object of the Char class. See here:
http://www.scala-lang.org/api/2.12.1/scala/Char$.html (It seems like SO breaks this link at the $ character. Copy-paste it instead)
The function perfoming the conversion is called char2int. It converts the Char into its corresponding Unicode value as an Int.
When the Scala compiler sees that the types Char and Int don't match, it will first check if there are any available implicit conversions. It only gives a compile error if it didn't find any. If it finds an implicit conversion, it will insert that function call into your code. Your code is therefore transformed to this:
addOne(Char.char2int('z'))
If you want to make your own implicit conversion to, for example, let your function accept String, you can define this:
// Enable implicit conversions.
import scala.language.implicitConversions
// The "implicit" modifier is the important part here, not the name of the function.
implicit def string2int(s: String) = s.toInt
Now this compiles:
// This returns 6
addOne("5")
/*
* This throws a NumberFormatException due to my implementation of string2int.
* Create your own implementation of string2int if you want it to work properly.
*/
addOne("a")
Finally: Beware that implicit conversions are very powerful and therefore can be dangerous! See TheArchetypalPaul's comment for an explanation.
It is because addOne(m: Int) [The part after colon (:) ] tells Scala you will pass Int to it, not Double, not anything else.
if you want it to work for Double, try this, but then you will always get Double as Result.
def addone (m : Double ) = m+1
addone: (m: Double)Double
scala> addone(1)
res0: Double = 2.0
scala> addone(1.1)
res1: Double = 2.1
Scala map the char type using the ASCII Table. So, 'z' is mapped to 122, which is an integer. In the method, addOne('z'), the input parameter been cast to an integer (i.e. 122).
However, the input parameter in addOne(2.1) is 2.1, which is a double and in addOne("z") is a string. They cannot be cast to an integer automatically.
def addOne(m: Int): Int = m + 1 only accept an integer for m
It also work with a single quoted character (z) because it's translated into its ASCII value. The value for 'z' is 122 and you add 1.
scala> val foo: Int = 'z'
foo: Int = 122
scala> val bar = foo + 1
bar: Int = 123
If you want to make this working with double you can specify def addOne(m: Double): Double = m + 1
I have some numbers list that I go through it, and doing a simple calculation to for two numbers:
I have numberA and numberB, and the calculation im doing is:
val res = (numberA/numberB) * 100
now, I dont know what type is the number, but I know it could be float (with 2 nums after the dot) or integer...
so I want to know what is the syntax in scala to calculate it?
currently I have:
val num1 = (vatReclaimed.toInt/vatPaid.toInt) * 100
but its obviously dont work, and I cannot really use toInt i guess since I dont know the type...
whats important to me that the res will hold the right answer, so if its 2.3 * 4 the res will hold 9.2
thanksss!
When you do not know the type only, that is a number, you probably have to work with Numeric. With numeric you can convert any numeric value to Double, Float, Int or Long. For precision I would recommend Double:
def calc[A : Numeric, B : Numeric](a: A, b: B): Double = (a.toDouble / b.toDouble) * 100
I would like to not to mind about type of numbers.
All numbers could be treated as Double,
but I would like to know the better scalaish way to use numbers just as numbers.
This is just one example, suppose I have the following:
val n = 5
val l = List(1,2,3,4,5) grouped (n / 2d).ceil.toInt
Is there a way to do just (exactly):
val l = List(1,2,3,4,5) grouped (n / 2).ceil
with no compilation error due to the mismatched type of 'grouped' parameter?
EDIT
The n / 2 in grouped (n / 2).ceil part could be, in another example, the non integer result of a function f:
grouped f.ceil
It still needs type conversion, or in all situations there is a trick or design pattern to avoid it?
val l = List(1,2,3,4,5) grouped((n + 1) / 2)
You could check out the numeric library Spire, I believe it has what you are looking for, namely, the ability to treat numbers as numbers whether they are int/double/float/etc.
There is a way to do it. You can define an implicit conversion like this:
implicit def double2Int(d: Double): Int = d.toInt
Once that's in scope, it will convert any Double automatically to Int. However, doing so is not recommended, as you lose type safety.
Given the following scala code:
var short: Short = 0
short += 1 // error: type mismatch
short += short // error: type mismatch
short += 1.toByte // error: type mismatch
I don't questioning the underlying typing - it's clear that "Short + value == Int".
My questions are:
1. Is there any way at all that the operator can be used?
2. If not, then why is the operator available for use on Short & Byte?
[And by extension *=, |= &=, etc.]
The problem seems to be that "+(Short)" on Short class is defined as:
def +(x: Short): Int
So it always returns an Int.
Given this you end up not being able to use the += "operator" because the + operation evaluates to an Int which (obviously) can not be assigned to the "short" var in the desugared version:
short = short + short
As for your second question, it is "available" because when the scala compiler finds expressions like:
x K= y
And if x is a var and K is any symbolic operator and there is K method in x then the compiler translates or "desugar" it to:
x = x K y
And then tries to continue compilation with that.