Global name in Python
I want to find out whether two numbers N1 and N2 are the permutations of the same digits. For example 123
and 321
are permutations of the same digits, where as 234
and 123
are not. I have used Python to solve the problem of which I am not an expert. I am using IDLE Python GUI
on Windows 7
. The specifications are Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
.
The Python code is shown below,
def k(n, m):
s1 = n
s2 = m
k = 0
fl = 0
while k < 10 :
arr1[k] = 0
arr2[k] = 0
k = k + 1
while s1 > 0 :
t = s1 % 10
arr1[t] = 1
t = s2 % 10
arr2[t] = 1
s1 = s1 / 10
s2 = s2 / 10
k = 0
while k < 10 :
if arr1[k] != arr2[k]:
fl = 1
k = k + 1
return fl
I saved the file as k.py
and imported using the following command import k
. But when I tried to execute the code as kk(123, 321)
I am getting the following error.
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
k.k(123,321)
File "k.py", line 7, in k
global arr2
NameError: global name 'arr1' is not defined
I tried to declare the arrays as follows,
arr1 = []
arr2 = []
I also tried,
global arr1 = []
global arr2 = []
and
global arr1
global arr2
But I am still getting the same error. What is wrong with my code?
I have checked the following answers in SO but I couldn't solve my problem.
Help Defining Global Names
Use of "global" keyword in Python
What I believed was that in Python you don't have to declare any variables, instead you can simply use them. Am I wrong about this assumption?
Any suggestions? Thank you.
There is no need to do anything with global values here. Everything should be contained within the function.
The problem is simply that you don't define arr1
or arr2
before you try appending to them. You need to define them in that function, along with s1
, s2
, k
and fl
.
Edit I should add that your code is extremely unPythonic. All these while loops with incrementing counters should be replaced with for loops: for k in range(10)
etc. But the first loop isn't even necessary - you should have arr1 = [0] * 10
and the same for arr2
.
You need to define the arrays in the functions. And then append to it. arr1 = []
defines an empty array.
arr1[k] = 2
tries to change the value at index k
. So either you should initialise it to a certain size or append to the empty array (using the append
function).
Also, if you want to access the arrays from outside the function, you might want to return the arrays from the function
链接地址: http://www.djcxy.com/p/71316.html上一篇: 调试和分析网络工作者
下一篇: Python中的全局名称