Search code examples
pythonloopsfor-looplocation

python changing location using for loop


I want to change location by putting command but got trouble in for loop

All I want is put R R R U D D and get (3,4) location

here is my code

x,y = first start point N= size of map

N=5
x,y = 1,1

I define left(-1,0), right(1,0), upper(0,-1), down(0,1)

def L(x,y):
    if x>1 and x<N and y>1 and y<N:
        x=x
        y=y-1
        return(x,y)
    else:
        return(x,y)
def R(x,y):
    if x<N and y<N:
        x=x
        y=y+1
        return(x,y)
    else:
        return(x,y)
def U(x,y):
    if x>1 and x<N and y>1 and y<N:
        x=x-1
        y=y
        return(x,y)
    else:
        return(x,y)
def D(x,y):
    if x<N and y<N:
        x=x+1
        y=y
        return(x,y)
    else:
        return(x,y)

input command

move_type=L(x,y),R(x,y),U(x,y),D(x,y)


num = [*map(int, input().split())]

put num [1 1]

change location - this is the point where I got trouble

for i in num:
    x,y = move_type[i]
    print(x,y)

**result come like this

1 2
1 2

I expect (1,2) (1,3)

what's wrong with my code help me plz**


Solution

  • Run Method like that

    num = [*map(int, input().split())]
    x, y = num
    
    # move_type=L(x,y),R(x,y),U(x,y),D(x,y) 
    # above tuple has the return value of function because you call them with the x and y as 1.
    
    
    move_type = L, R, U, D  # But here I only provide the function name to 
                            # tuple and later I execute them with the new x and y values
    
    for i in num:
        x, y = move_type[i](x, y) # calling the function with the new value of x and y
        print(x, y)
    
    
    

    One suggestion change your all functions

    def L(x, y):
        if x > 1 and x < N and y > 1 and y < N: # if this if execute then the x and y modify and return at the end
            x = x
            y = y-1
    
        # but if if not execute the x and y values return to the same x and y values
        return (x, y) # this will return the x, y
    
     
    def R(x, y):
        if x < N and y < N:
            x = x
            y = y+1
        return (x, y)
    
    
    def U(x, y):
        if x > 1 and x < N and y > 1 and y < N:
            x = x-1
            y = y
        return (x, y)
    
    
    def D(x, y):
        if x < N and y < N:
            x = x+1
            y = y
        return (x, y)