0

我有两个模块:“factors.py”和“primes.py”。在“factors.pyc”中,我有一个函数应该找到一个数字的所有素因子。在其中,我从“primes.py”导入了 2 个函数。我在“primes.py”中有一本字典,它被声明为全局(在定义之前)。当我尝试在“factors.py”的代码中使用它时,我收到了这个错误:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    pFactors(250)
  File "D:\my_stuff\Google Drive\Modules\factors.py", line 53, in pFactors
    for i in primes_dict:
NameError: global name 'primes_dict' is not defined

这是我的代码:

在“因素.py”中:

def pFactors(n):
   import primes as p
   from math import sqrt
   from time import time
   pFact, primes, start, limit, check, num = [], [], time(), int(round(sqrt(n))), 2, n
   if p.isPrime(n):
      pFact = [1, n]
   else:
      p.prevPrimes(limit)
      for i in primes_dict:
         if primes_dict[i]:
            primes.append(i)
   #other code

在“primes.py”中:

def prevPrimes(n):
    if type(n) != int and type(n) != long:
        raise TypeError("Argument <n> accepts only <type 'int'> or <type 'long'>")
    if n < 2:
        raise ValueError("Argument <n> accepts only integers greater than 1")
    from time import time
    global primes_dict
    start, primes_dict, num = time(), {}, 0
    for i in range(2, n + 1):
        primes_dict[i] = True
    for i in primes_dict:
        if primes_dict[i]:
            num = 2
            while (num * i < n):
                primes_dict[num*i] = False
                num += 1
    end = time()
    print round((end - start), 4), ' seconds'
    return primes_dict #I added this in based off of an answer on another question, but it still was unable to solve my issue

prevPrimes(n)以预期的方式工作。但是,因为我无法访问primes_dictpFactors(n)所以不起作用。

如何primes_dict在另一个模块中使用字典(在一个模块中创建)?提前致谢。

4

1 回答 1

2

中定义的任何内容primes都将以您的名称命名import。由于您将其导入为pprimes_dict因此可以作为p.primes_dict. 如果你愿意,你可以做

from primes import primes_dict

将其作为顶级名称。

于 2012-11-24T01:36:52.400 回答