Best Python Input method for Integers - python

In python 2.7, if we take an integer as input, which one is more faster and efficient or there is no difference at all:
input() or int(raw_input())

From the Python docs
input([prompt])
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
int(raw_input()) will be faster, more secure and produce less confusing results.
Consider:
>>> b = 5
>>> a = input()
[1, 2, 3]
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> a = int(raw_input())
[1, 2, 3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '[1, 2, 3]'
The ValueError raised when reading input is far more desirable than the TypeError raised when using the variable.

Related

Is x in int(x) numeric/non-numeric string?

In the code below, int(x) throws an exception. I understand that x should be a string but -numeric or non-numeric string?
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz")
The string you supply as the function argument has to be representable as an integer. What would you consider the numerical representation of "xyz" to be?
If you pass the function string representations of numbers, positive or negative, then you won't trigger the exception.
When numbers are encoded as strings there are no problems,
>>> int("10")
10
>>> int("-10")
-10
When symbols that aren't readily represented by a number is supplied to the function the exception will triggered,
>>> int("-10a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-10a'
int(x) does not accept floating-point numbers either:
>>> int("10.0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.0'

Python: invalid literal for int() with base 10

I'm getting an invalid literal for int() with base 10 where it seems as if the input stream is concatenating values generated in a loop.
def collectData():
lst = makeCases()
cases = int(input())
for i in range(cases):
size = int(input())
case = []
for j in range(size):
value = int(input())
case +=[value]
insert(lst,case)
return lst
That is the function generating the issue. The value and size variables are the problem as they seem to concatenate subsequent values before the conversion.
The makeCases() function generates a tuple on the form ("Case",[]).
EDIT: The code works fine locally but won't work in the hackerrank IDE
As Tom Karzes has said, input() is returning something other than a number. Looking at the error message that is produced by Python, I assume you are using Python 3 but I will cover Python 2 too.
Python 2
input() checks if the given input from stdin is something it can evaluate to. It is equivalent to eval(raw_input()). (Pydoc)
>>> a = input()
123
>>> a
123
>>> abc = 3
>>> a = input()
abc
>>> a
3
It produces a different error when you input() something it cannot eval:
>>> a = input()
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
Since it performs eval on the given input, it will assume that abc may be a variable name. It searches for it but throws an error because it couldn't find it.
Python 3
input() is the new raw_input() in Python 2. input() returns a string even if the given input is a number. (Pydoc)
>>> a = input()
123
>>> a
'123'
This is the most likely reason you would convert it to an int() after you get an input().
I can replicate your error message as so (in Python 3):
>>> a = int(input())
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> a = int(input())
123 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123 123'
In conclusion, the most likely reason why it is returning such an error is because you are giving it something it cannot convert to an int.

TypeError: 'int' object is not callable for a recursive function

a = 3
def f(x):
x = (x**3-4*x)/(3(x**2)-4)
return x
while True:
print(a)
a = f(a)
I'm getting a type error here, and I'm not sure why. I'm trying to run this recursive function, is there any way to fix this?
You need a * operator after your parentheses. Multiplication is only implied in mathematical notation in this context, in Python it looks like you're trying to call a function.
3(x**2)
So it would be
3*(x**2)
For example
>>> 3(5*2)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
3(5*2)
TypeError: 'int' object is not callable
>>> 3*(5*2)
30

Is there any object can make str() function throw error or exception in python?

I have a function that requires the input to be a string.
I know I can assert or do check on the input type, but I would like to handle that as much as possible.
I have following code to handle that. But I'm wondering if there's any case that this line can throw exception that I need to handle.
def foo(any_input):
clean_input = str(any_input) # will this throw any exception or error?
process(clean_input)
Yes, some unicodes:
>>> str(u'í')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 0: ordinal not in range(128)
You might get a RuntimeError while trying to str a deeply-nested list:
>>> x = []
>>> for i in range(100000):
... x = [x]
...
>>> y = str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded while getting the repr of a list
or a MemoryError trying to str a huge list:
>>> x = 'a'*1000000
>>> y = [x] * 1000000 # x and y only require a few MB of memory
>>> str(y) # but str(y) requires about a TB of memory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
I mean, you could trivially make one:
class BadStr:
def __str__(self):
raise Exception("Nope.")

Python curiosity: [] > lambda n: n

One of my coworkers was using the builtin max function (on Python 2.7), and he found a weird behavior.
By mistake, instead of using the keyword argument key (as in key=lambda n: n) to pre-sort the list passed as a parameter, he did:
>>> max([1,2,3,3], lambda n : n)
[1, 2, 3, 3]
He was doing what in the documentation is explained as:
If two or more positional arguments are provided, the largest of the positional arguments is returned., so now I'm curious about why this happens:
>>> (lambda n:n) < []
True
>>> def hello():
... pass
...
>>> hello < []
True
>>> len(hello)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'function' has no len()
I know it's not a big deal, but I'd appreciate if any of the stackoverflowers could explain how those comparisons are internally made (or point me into a direction where I can find that information). :-)
Thank you in advance!
Python 2 orders objects of different types rather arbitrarily. It did this to make lists always sortable, whatever the contents. Which direction that comparison comes out as is really not of importance, just that one always wins. As it happens, the C implementation falls back to comparing type names; lambda's type name is function, which sorts before list.
In Python 3, your code would raise an exception instead:
>>> (lambda n: n) < []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: function() < list()
because, as you found out, supporting arbitrary comparisons mostly leads to hard-to-crack bugs.
Everything in Python (2) can be compared, but some are fairly nonsensical, as you've seen.
>>> (lambda n:n) < []
True
Python 3 resolves this, and produces exceptions instead.

Categories

Resources