開發一個座標計算工具, A表示向左移動,D表示向右移動,W表示向上移動,S表示向下移動。從(0,0)點開始移動,從輸入字符串裏面讀取一些座標,並將最終輸入結果輸出到輸出文件裏面。
輸入:
合法座標爲A(或者D或者W或者S) + 數字(兩位以內)
座標之間以;分隔。
非法座標點需要進行丟棄。如AA10; A1A;
下面是一個簡單的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
處理過程:
起點(0,0)
A10 = (-10,0)
S20 = (-10,-20)
W10 = (-10,-10)
D30 = (20,-10)
x = 無效
A1A = 無效
B10A11 = 無效
一個空 不影響
A10 = (10,-10)
結果 (10, -10)
python代碼實現:
#coding=utf-8
#判斷命令格式是否正確
def judge_command(string):
#定義三個變量,分別檢測字母、數字、特殊字符的個數
alpha_count = 0
number_count = 0
other_count = 0
alpha_bak = ['A','S','D','W']
#如果長度小於1,代表命令爲空,返回false
if len(string) < 1:
return False
#記錄字母、數字、特殊非'-'號特殊字符的個數
if string[0].isdigit():
return False
for i in string:
if i.isalpha():
alpha_count += 1
elif i.isdigit():
number_count += 1
elif i != '-':
other_count += 1
#如果格式正確,輸出True,否則,輸出Flase
if alpha_count == 1 and string[0] in alpha_bak and number_count<=2 and number_count >= 1 and other_count == 0:
return True
else:
return False
#座標移動
def axis_move(command,axis):
if command[1] == '-':
number = 0 - int(command[2:])
else:
number = int(command[1:])
if command[0] == 'A':
axis[0] -= number
elif command[0] == 'S':
axis[1] -= number
elif command[0] == 'D':
axis[0] += number
elif command[0] == 'W':
axis[1] += number
return axis
#主函數
def main():
axis = [0,0]
inputs = raw_input()
commands = inputs.split(';')
for c in commands:
if judge_command(c):
axis = axis_move(c,axis)
print str(axis[0]) + ',' + str(axis[1])
return
if __name__ == '__main__':
main()