Python global name

I want to find out if the two digits N1 and N2 are permutations of the same digits. For example, 123 and 321 are permutations of the same digits, where as 234 and 123 are not. I used Python to solve a problem that I am not an expert about. I am using the IDLE Python GUI on Windows 7 . Technical Specifications Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 .

Below is the Python code,

 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 import k command. But when I tried to execute code like kk(123, 321) , I get the following error.

 Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> kk(123,321) File "k.py", line 7, in k global arr2 NameError: global name 'arr1' is not defined 

I tried to declare arrays as follows:

 arr1 = [] arr2 = [] 

I also tried

 global arr1 = [] global arr2 = [] 

and

 global arr1 global arr2 

But I still get the same error. What is wrong with my code?

I checked the following answers in SO , but I could not solve my problem.

Help Definition of global names

Using the "global" keyword in Python

I figured that in Python you don't need to declare any variables, instead you can just use them. Am I mistaken in this assumption?

Any suggestions? Thanks.

+7
source share
2 answers

There is nothing to do with global values ​​here. Everything should be contained in a function.

The problem is that you do not define arr1 or arr2 before trying to add them. You must define them in this function along with s1 , s2 , k and fl .

Change I must add that your code is extremely non-petite. All of these, while loops with increasing counters should be replaced by loops: for k in range(10) , etc. But the first loop is not even needed - you should have arr1 = [0] * 10 and the same for arr2 .

+3
source

You need to define arrays in functions. And then join him. arr1 = [] defines an empty array.

 arr1[k] = 2 

trying to change the value in index k . Therefore, either you must initialize it to a certain size, or add it to an empty array (using the append function).

Also, if you want to access arrays from outside the function, you might want to return arrays from the function

+1
source

All Articles