2016-12-15 7 views
-1

Теперь я хочу пояснить, что я не хочу включать переменную b в качестве аргумента функции g. Есть ли другой способ, которым я мог бы переписать этот код, учитывая, что g называется рекурсивно? Даже упоминание b = 0 и вызов его как глобального не похоже на ошибку задания задания.Специфическая проблема, связанная с ссылкой на переменную

global b 
b = 0 
def g(x): 
    if b < x: 
     for i in range(10): 
      if u == i: 
       b += 1 
       g(x) #g is called recursively 
for u in range(20): 
    b = 5 
    g(7) 

ответ

1
# that is from MSeifert(voted is correct), @Chalid 
b = 0 
first = [] 
second = [] 
def g(x): 
    global b # So python knows you use the global variable! 
    first.append(b) 
    if b < x: 
     for i in range(10): 
      if u == i: 
       b += 1 
       g(x) 

for u in range(20): 
    b = 5 
    g(7) 


# my solution is without any global variable 
# and the result matching the expectation 

def g(x,b): 
    second.append(b) 
    if b < x: 
     for i in range(10): 
      if u == i: 
       b += 1 
       g(x,b) #g is called recursively 
b = 5 
for u in range(20): 
    g(7,b) 

print len(first), len(second) 
print first 
print second 

40 40 
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] 
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] 
+0

Но тогда каждый раз, когда я запускаю функцию 'g', мне придется дать ей некоторое значение вместо b правильно? который может фактически испортить код –

+0

, если b имеет значение для g да, я имею в виду, что вы увеличиваете b на единицу, чем вы вызываете g с последним результатом b –

1

global используется, когда вы явно хотите использовать и обновлять global переменную. Таким образом, вы должны использовать global b внутри вашей функции вместо снаружи:

b = 0 

def g(x): 
    global b # So python knows you use the global variable! 
    if b < x: 
     for i in range(10): 
      if u == i: 
       b += 1 
       g(x) 

for u in range(20): 
    b = 5 
    g(7) 

Поскольку вы используете b += 1 внутри g функции вам нужно объявить b в global. В противном случае вы получите UnboundLocalError:

UnboundLocalError: local variable 'b' referenced before assignment

Смотрите также Python FAQ:

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

0

Это может сделать волосы людей стоять на конце, но вы можете добавить b в качестве атрибута g.

def g(x): 
    If g.b > x: 
     ... 

g.b = 5 
....