Click here to Skip to main content
15,886,791 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I need to reduce the length of this code in Python3 as much as possible (even if it will be less readable):

Python
a,b,x,y=[int(i) for i in input().split()]
while 1: 
     r=''
     if y<b:r='S';y+=1
     if y>b:r='N';y-=1 
     if x<a:r+='E';x+=1
     if x>a:r+='W';x-=1
     print(r)

It's a map: you are on (x,y) and you need to go to (a,b) S for South N for North NE for North East.... After each turn I must tell where to go using print.

For example could I put all the if on one line ?
Posted
Updated 7-May-15 21:52pm
v3
Comments
ZurdoDev 7-May-15 15:45pm    
Why?
jgakenhe 7-May-15 16:39pm    
Probably for a class assignment.
Sergey Alexandrovich Kryukov 7-May-15 18:23pm    
This is not a valid Python code, to start with. You need to indent it properly.
—SA

1 solution

The variable r can be dispensed with as it is not necessary. You could also improve the while loop so it actually completes, as follows:
Python
while (a != x or b != y):
    if y>b:y-=1;print('North', y)
    if y<b:y+=1;print('South', y)
    if x<a:x+=1;print('East', x)
    if x>a:x-=1;print('West', x)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900