2016-12-07 34 views
0

我有這段代碼,我試圖在循環內部有一個循環來確定某個位置是否被窺視了兩次。更改值

current_dir = 1 
position = [0,0] 
index = 0 
move_list = ["L2", "L3", "L3", "L4", "R1", "R2", "L3", "R3", "R3", "L1", "L3", "R2", "R3", "L3", "R4", "R3", "R3", "L1", "L4", "R4", "L2", "R5", "R1", "L5", "R1", "R3", "L5", "R2", "L2", "R2", "R1", "L1", "L3", "L3", "R4", "R5", "R4", "L1", "L189", "L2", "R2", "L5", "R5", "R45", "L3", "R4", "R77", "L1", "R1", "R194", "R2", "L5", "L3", "L2", "L1", "R5", "L3", "L3", "L5", "L5", "L5", "R2", "L1", "L2", "L3", "R2", "R5", "R4", "L2", "R3", "R5", "L2", "L2", "R3", "L3", "L2", "L1", "L3", "R5", "R4", "R3", "R2", "L1", "R2", "L5", "R4", "L5", "L4", "R4", "L2", "R5", "L3", "L2", "R4", "L1", "L2", "R2", "R3", "L2", "L5", "R1", "R1", "R3", "R4", "R1", "R2", "R4", "R5", "L3", "L5", "L3", "L3", "R5", "R4", "R1", "L3", "R1", "L3", "R3", "R3", "R3", "L1", "R3", "R4", "L5", "L3", "L1", "L5", "L4", "R4", "R1", "L4", "R3", "R3", "R5", "R4", "R3", "R3", "L1", "L2", "R1", "L4", "L4", "L3", "L4", "L3", "L5", "R2", "R4", "L2"] 
for i in move_list: 
    turn = i[0] 
    movement = int(i[1:]) 
    if turn == "R": 
     current_dir += 1 
     if current_dir > 4: 
      current_dir = 1 
    if turn == "L": 
     current_dir -= 1 
     if current_dir < 1: 
      current_dir = 4 
    if current_dir == 1: #Move North 
     position[1] += movement 
    if current_dir == 3: #Move South 
     position[1] -= movement 
    if current_dir == 2: #Move East 
     position[0] += movement 
    if current_dir == 4: #Move West 
     position[0] -= movement 
    position_2 = position 
    current_dir2 = current_dir 
    turn2 = turn 
    for f in move_list[index+1:]: 
     turn2 = f[0] 
     movement2 = int(f[1:]) 
     if turn2 == "R": 
      current_dir2 += 1 
      if current_dir2 > 4: 
       current_dir2 = 1 
     if turn2 == "L": 
      current_dir2 -= 1 
      if current_dir2 < 1: 
       current_dir2 = 4 
     if current_dir2 == 1: # Move North 
      position_2[1] += movement2 
     if current_dir2 == 3: # Move South 
      position_2[1] -= movement2 
     if current_dir2 == 2: # Move East 
      position_2[0] += movement2 
     if current_dir2 == 4: # Move West 
      position_2[0] -= movement2 
     print position_2 
    print position 
    i = + 1 
    index += 1 

它應該工作正常,但我有哪裏的位置值,當我試圖改變position_2,我真的不明白爲什麼發生變化的問題。

它改變了這部分

if current_dir2 == 1: # Move North 
    position_2[1] += movement2 
if current_dir2 == 3: # Move South 
    position_2[1] -= movement2 
if current_dir2 == 2: # Move East 
    position_2[0] += movement2 
if current_dir2 == 4: # Move West 
    position_2[0] -= movement2 

回答

0

你的問題是你說的position_2 = position。這使位置指向與position_2相同的對象。有用的文章here。你應該說:

position_2 = position[:] 

使他們指向不同的對象。

0

沒關係我想通了,我做的情況2 =位置,這意味着它們都在同一ARRY指點。在我沒有意識到之前,我學會了這一點。

+0

同時驗證代碼中的「i = + 1」部分。我相信它的邏輯不正確。 'i'最初是move_list的成員,但是您正試圖在此添加1。 –

+0

@VijayakumarUdupa:它不會增加一個,它會用1代替它。不會傷害任何東西,因爲'i'會立即被循環更新,這對於大多數目的來說是不可操作的。 – ShadowRanger

+0

糟糕,無法正確讀取代碼。 –