2016-08-19 4 views
-1

何かをデコードするコードを書きました。少数を試してみるとうまくいく。しかし、私はいくつかの大きな数字を試してみると、それは間違っています。"データが大きくなるときにローカル変数 'x'が代入の前に参照される"

私はデコードしたいどのような事はこれです: enter image description here

def decode(n): 
    if n == 0: 
     return (0, 0) 
    circle = int(sqrt(n)/2 + 0.5) 
    largest = (2 * circle + 1) ** 2 - 1 
    distance = largest - n 
    quotient = distance // (2 * circle) 
    remainder = distance % (2 * circle) 

    if quotient == 0: 
     x = circle- remainder 
     y = - circle 
    if quotient == 1: 
     x = -circle 
     y = -circle + remainder 
    if quotient == 2: 
     x = -circle + remainder 
     y = circle 
    if quotient == 3: 
     x = circle 
     y = circle - remainder 
    return (x, y) 

print(decode(2070)) #(23, 23)  
print(decode(204019576686482721392)) #(7141771, 7141771081) 
print(decode(142656302882002193830320)) 
#Traceback (most recent call last): 
# File line 51, in <module> 
# print(decode(142656302882002193830320)) 
# File line 47, in decode 
# return (x, y) 
#UnboundLocalError: local variable 'x' referenced before assignment 

私も試してみましたN 1-14から、すべての結果は右です。

私は別のint()をsqrt(n)で提供しなければならない理由を発見しました。

circle = int(int(sqrt(n)/2) + 0.5) 

ありがとうございます。

+1

だから '商 'の価値は何ですか? – melpomene

+0

商が3より大きい場合、 'x'の値を設定することはありません。したがって、 'x'を試して返すときにエラーが発生します。 –

+0

ありがとうございます。私は商を4にしようとしたので、これがエラーの原因です。しかし、なぜ商が4になるのか、私は混乱しています。私にもっとヒントを与えてください。 – Mangosteen

答えて

1

返信しようとしたときにif文が一致しない状況があります。xが定義されていません。 xyのデフォルト値を与える必要があります。

また、elif(else if)句を使用する必要があります。それ以外の場合は、ブロックifをチェックする必要があります。 elifを使用すると、文が一致すると残りはスキップされます。 2つのステートメントが誤って同時にマッチングすることは、より効率的で、あまり起こりにくいものです。

def decode(n): 
    # either pre-define your default values... 
    x = 0 
    y = 0 

    if quotient == 0: 
     x = circle - remainder 
     y = - circle 
    elif quotient == 1: 
     x = -circle 
     y = -circle + remainder 
    elif quotient == 2: 
     x = -circle + remainder 
     y = circle 
    elif quotient == 3: 
     x = circle 
     y = circle - remainder 
    # ...or define your defaults in an else clause 
    else: 
     x = 0 
     y = 0 

    return (x, y) 
+0

ありがとうございますが、入力が大きくなると商の値が私の予想外になる理由をデバッグする方法はありますか? – Mangosteen

+0

これはフォーラムではないので、新しい質問をする必要があります。 – Soviut

関連する問題