How does this variable declaration works in python? - python

i = 0x0800
What I understand here is that 0x0800 is a hexadecimal number where '0x' denotes the hex type and the following number '0800' is a 2 byte hexadecimal number. On assigning it to a variable 'i', when its type is checked I got this error
>>> type(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Here I make out that 'i' is suppose to be an int object. I got more confused when I tried this
>>> print i
2048
What is '2048' exactly .. Can anyone throw some light here ?

i is an integer, but you redefined type:
>>> i = 0x0800
>>> i
2048
>>> type(i)
<type 'int'>
>>> type = 42
>>> type(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(i)
<type 'int'>
Note the type = 42 line; I created a new global name type and that is found before the built-in. You could also use import __builtin__; __builtin__.type(i) in Python 2, or import builtins; builtins.type(i) in Python 3 to access the original built-in type() function:
>>> import __builtin__
>>> type = 42
>>> __builtin__.type(type)
<type 'int'>
>>> type(type)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(type)
<type 'type'>
The 0x notation is just one of several ways of specifying an integer literal. You are still producing a regular integer, only the syntax for how you define the value differs here. All of the following notations produce the exact same integer value:
0x0800 # hexadecimal
0o04000 # octal, Python 2 also accepts 0400
0b100000000000 # binary
2048 # decimal
See the Integer Literals reference documentation.

I'll quickly put the answer that I figured out ....
i = 0x0800 will assign an int equivalent of the hexadecimal number (0800) to i.
So if we go down to pieces this looks like
>>> i
2048
>>>
>>> (pow(16,3) * 0) + ( pow(16,2) * 8 ) + (pow (16,1) * 0 ) + (pow(16,0) * 0)
2048

Related

x has type function but calling x gives a type error Python3

I have the following python statement
x = lambda :8()
checking the type of x returns the following
<class 'function'>
but then doing this
x()
TypeError: 'int' object is not callable
I can solve this by putting parenthesis around the lambda like so
x = (lambda :8)()
But I am wondering what is going on.
The problem does not lie with calling x, you are trying to call 8 with 8(). Calling an integer raises an error because instances of int are not callable.
I can solve this by putting parenthesis around the lambda like so
What you are doing with x = (lambda :8)() is construct an anonymous function that always returns the number 8, then call it, and assign the name x to the return value.
>>> x = (lambda :8)()
>>> x
8
However, x() will still raise an error because again it's trying to call an integer.
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

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: return arrays must be of ArrayType for a function that uses only floats

This one really stumps me. I have a function that calculates the weight of a word, I've confirmed that both a and b local variables are of type float:
def word_weight(term):
a = term_freq(term)
print a, type(a)
b = idf(term)
print b, type(b)
return a*log(b,2)
running word_weight("the") logs:
0.0208837518791 <type 'float'>
6.04987801572 <type 'float'>
Traceback (most recent call last):
File "summary.py", line 59, in <module>
print word_weight("the")
File "summary.py", line 43, in word_weight
return a*log(b,2)
TypeError: return arrays must be of ArrayType
why?
You are using numpy.log function here, its second argument is not base but out array:
>>> import numpy as np
>>> np.log(1.1, 2)
Traceback (most recent call last):
File "<ipython-input-5-4d17df635b06>", line 1, in <module>
np.log(1.1, 2)
TypeError: return arrays must be of ArrayType
You can now either use numpy.math.log or Python's math.log:
>>> np.math.log(1.1, 2)
0.13750352374993502
>>> import math
>>> math.log(1.1, 2) #This will return a float object not Numpy's scalar value
0.13750352374993502
Or if you're dealing only with base 2 then as #WarrenWeckesser suggested you can use numpy.log2:

Why sum start value is not zero value of iterable?

Why is sum not able to take correct zero value automatically?
>>> sum((['1'], ['2']))
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
sum((['1'], ['2']))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> sum((['1'], ['2']), [])
['1', '2']
It is simple to implement like this:
>>> def sum(s, start=None):
it = iter(s)
n = next(it)
if start is None:
start = type(n)()
return n + __builtins__.sum(it, start)
>>> sum((['1'], ['2']))
['1', '2']
>>>
But sum does not anyway join strings, so maybe it is just to encourage to use proper methods for different 'summings'.
On the other hand if it is meant to be used only for numbers, why not sum_numbers not sum as name to make it clear.
EDIT: to handle empty sequence we must add little code:
>> sum([])
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
sum([])
File "<pyshell#28>", line 3, in sum
n = next(it)
StopIteration
>>> def sum(s, start=None):
it = iter(s)
try:
n= next(it)
except:
return 0
if start is None:
start = type(n)()
return n + __builtins__.sum(it, start)
>>> sum([])
0
>>>
Inferring the zero value is impossible in the general case. What if the iterable produces instances of a user-defined class that has no zero-argument constructor? And as you've shown, it's easy to provide it yourself.

'str' object is not callable using enumerate

I'm trying to do the following:
for index, image_properties in enumerate(list_of_properties):
index = str(index)
But I keep getting
TypeError at /
'str' object is not callable
What is going wrong here?
As the commenters have mentioned, you must have str defined somewhere and it overrides the str built-in function.
In Python you can easily "re-bind" symbols like this. See this session for example:
>>> str(2)
'2'
>>> def str(x): return x + 1
...
>>> str(2)
3
>>> str = 1
>>> str(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Moreover the text of your TypeError suggests that str was defined to be a string object somewhere earlier.

Categories

Resources