TypeError 'int' - python-3.x

I'm trying to make a function the returns all possible permutations for a list of numbers for example:
List= [1,2,3]
[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],[3,2,1]]
however I keep running into the same error
TypeError: 'int' object is not callable
in this line
return permutations(result,variable,List,permutations)
the rest of the code is
def permutationsaux(List):
if List==[]:
return []
else:
return permutations([List],0,List,countpermutations(List))
def permutations(result,variable,List,permutations):
if len(result)==permutations:
return result
elif len(result[variable])==len(List):
result.append([])
variable=variable+1
return permutations(result,variable,List,permutations)
return permutations(result[variable]+reorderlist(List),variable+1,reorderlist(lista),permutations)
def countpermutations(List):
if List==[]:
return 1
return len(List)*countpermutations(List[1:])
def reorderlist(List):
temp=List[len(List)-2]
List[len(List)-2]=LIst[len(List)-1]
List[len(List)-1]=temp
return List

Your function "permutations" has an argument named "permutations". Guess which one is in scope within the function.

Related

'int' object is not callable (about closure)

today I learn some python.
When I try to write some code, I had some questions.
def outer(a, b):
def inner():
return a+b
return inner
a=outer(4, 3)
print(a)
print(a())
<function outer.<locals>.inner at 0x0000028F37C519D0
7
and this code
def outer2(a, b):
def inner2(c, d):
return c + d
return inner2(a, b)
b = outer2(4,3)
print(b)
print(b())
7
TypeError Traceback (most recent call last) <ipython-input-41-b2c9e3844269> in <module> 5 b = outer2(4,3) 6 print(b) ----> 7 print(b()) TypeError: 'int' object is not callable
I really want to know difference between a and b , anyone can help me? Thank you very much
The problem lies in this line : return inner2(a, b)
what you did was:
You are actually invoking a function inner2(c,d) and passing an argument to it.Which will eventually return an integer.
what you should do instead:
Do not invoke a function with arguments, just return the reference : return inner2.
You code should look something like this now:
def outer2(a, b):
def inner2():
return a + b
return inner2
#b now holds the reference to a function inner2()
b = outer2(4,3)
#prints the reference to the function object
print(b)
#invokes the function inner2 and use the arguments a,b from an outer function.
print(b())
This is called currying in python i.e, a function returning another function: Here to get some ideas

Attribute error while using functools.reduce

I get an attribute error while running this code. Why isn't the result.append(item) being returned in the next iteration?
from functools import reduce
def reducer(arr):
return reduce((lambda result,item: result.append(item)),arr,[])
print(reducer([[1,3],[2,4]]))
list.append doesn't return the list. You can use list1 + list2 to extend list1 with all the elements in list2, so the following would work.
def reducer(arr):
return reduce((lambda result, item: result + item), arr, [])

'list' object is not callable: TypeError

I have a function which is returning 2 values. When I try to fetch those values in a list in another function, it is giving the following error:
'list' object is not callable: TypeError
Here is the function returning two values.
def function():
return val1, val2
Here is the other function calling function():
def function1():
values = []
values = function()
value_1 = values[0]
value_2 = values[1]
function() returns two values, which cannot be stored in a single variable 'values', so instead make function() return a list of those two values
def function():
return [val1,val2]
def function1():
values=function()
value_1=values[0]
value_2=values[1]
You don't need values=[] since it will get overridden anyways by values=function()
Your code should not throw that exception, as the return from function is a tuple.
However here is a modified version of your code which returns a list.
def function():
val1 = 10
val2 = 20
#return the values in a list
return [val1, val2]
def function1():
values = function()
value_1 = values[0]
value_2 = values[1]
print(value_1, value_2)
function1()
Output:
10 20
Here you go
def function():
#return any predefined value here
return 1, 2
def function1():
values = []
a,b = function()
values.append(a)
values.append(b)
print(values)
function1()
Output:
[1, 2]

Error when searching for the length of a list

[Edit: Solved, i was calling the same function from another place in the code with wrong input arguments, creating this error]
I am new to python and after some search i've decided to post my problem..
My function takes *args as input: a variable number of lists
In this function i use a for loop to read all lists and try to get len(each_list).
I then get the error TypeError: object of type 'numpy.float64' has no len()
I've tried to find the problem by myself but i don't understand the behavior
If i do:
def myfunction(* args):
for p in args:
print(isinstance(p, list))
print(type(p))
print(p)
I'll get: True + class 'list' + [value1, value2, ... etc]
But if i add one line to get the length (last one)
def myfunction(* args):
for p in args:
print(isinstance(p, list))
print(type(p))
print(p)
a = len(p)
I'll get: False + class 'numpy.float64' + error (i understand it is not iterable)
I call the function as:
All_lists = [list1, list2, list3]
myfunction(All_lists)
# I've also tried myfunction(*All_lists)
Thank you for your help
You need to do len(p) for the length of arguments list
def myfunction(* args):
for p in args:
print(isinstance(p, list))
print(type(p))
print(p)
print(len(p))
myfunction([[1,2,3],[4,5,6],[7,8,9] ])
#True
#<class 'list'>
#[1, 2, 3]
#3

Showing that function for IF statement does not work the same way as IF statement

This is a question for a homework problem that I cant figure out:
Question Beginning
Q3. Let's try to write a function that does the same thing as an if statement:
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and false_result otherwise."""
if condition:
return true_result
else:
return false_result
This function actually doesn't do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that one of these functions returns the number 1, but the other does not:
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
Question End
Heres what I figured out:
with_if_statement() does not evaluate f() if c() is true, but with_if_function() evaluates all 3 before checking if c() is true or not.
So, I thought of assigning a global variable in c(), and changing its value in f()
heres my code (which does not work):
def c():
try:
global x
except NameError:
x=1
if x==1:
return True
else:
return False
def t():
if x==1:
return (1)
else:
return (0)
def f():
global x
x=2
if x==1:
return (1)
else:
return (0)
can anyone help me figure out the answer? Thanks..!
The global statement shouldn't throw a NameError (and so you won't run x=1 in c()). I would try rewriting your code without using exceptions, they won't be necessary to solve this and are making it more complicated than it needs to be. Using a global variable and having side effects in your functions is certainly the right track.
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result
def with_if_statement():
"""
>>> with_if_statement()
1
"""
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
The question requires that, write 3 functions: c, t and f such that with_if_statement returns 1 and with_if_function does not return 1 (and it can do anything else)
At the beginning, the problem seems to be ridiculous since, logically, with_if_statement and with_if_function are same. However, if we see these two functions from an interpreter view, they are different.
The function with_if_function uses a call expression, which guarantees that all of its operand subexpressions will be evaluated before if_function is applied to the resulting arguments. Therefore, even if c returns False, the function t will be called. By contrast, with_if_statement will never call t if c returns False (This paragraph from the UCB website).
def c():
return True
def t():
return 1
def f():
'1'.sort() # anything breaks the program is OK

Resources