首页 > 试题广场 >

坐标移动

[编程题]坐标移动
  • 热度指数:563949 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

输入:

合法坐标为A(或者D或者W或者S) + 数字(两位以内)

坐标之间以;分隔。

非法坐标点需要进行丢弃。如AA10;  A1A;  $%$;  YAD; 等。

下面是一个简单的例子 如:

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)

数据范围:每组输入的字符串长度满足 ,坐标保证满足 ,且数字部分仅含正数

输入描述:

一行字符串



输出描述:

最终坐标,以逗号分隔

示例1

输入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出

10,-10
示例2

输入

ABC;AKL;DA1;

输出

0,0
cons = input().split(";")
pos = [0, 0]

for con in cons:
    if con == "":
        continue
   
    try:
        d = int(con[1:])
    except:
        continue
    if con[0] == "A":
        pos[0] -= d
    elif con[0] == "D":
        pos[0] += d
    elif con[0] == "W":
        pos[1] += d
    elif con[0] == "S":
        pos[1] -= d

print(pos[0], pos[1], sep=",")

编辑于 2024-04-20 09:44:44 回复(0)
l = list(input().split(';'))
fin = [0, 0]
for s in l:
    if len(s) >= 2 and s[0] in 'ADSW' and s[1:].isdigit():
        if s[0] == 'A':
            fin[0] -= int(s[1:])
        elif s[0] == 'D':
            fin[0] += int(s[1:])
        elif s[0] == 'W':
            fin[1] += int(s[1:])
        elif s[0] == 'S':
            fin[1] -= int(s[1:])
print(str(fin)[1:-1].replace(', ', ','))

发表于 2024-04-16 14:05:20 回复(0)
import re
dist = {'A':[-1,0],'D':[1,0],'W':[0,1],'S':[0,-1]}
post = [0,0]
strs = input().split(';')
for i in strs:
    match = re.match('^[A-Z](\d{1,2})$',i)
    if not match:
        continue
    else:
        move = ''.join(re.findall('[A-Z]',i))
        step = int(''.join(re.findall('\d+',i)))
        post[0]+=dist[move][0]*step
        post[1]+=dist[move][1]*step
print(post[0],post[1],sep=',')

发表于 2024-04-06 18:19:05 回复(0)
str = input().split(";")
b = ["W","A","S","D"]
x = 0
y = 0# 确定初始坐标
for a in str:
    if len(a) >= 2 and a[0] in b and a[1:].isdigit():
        # 判断字符串长度大于二并且首字母是WASD并且其他为数字
        c = int(a[1:])
        if a[0] == 'A':
            x -= c
        elif a[0] == 'S':
            y -= c
        elif a[0] == 'W':
            y += c
        elif a[0] == 'D':
            x += c
print(f"{x},{y}")
编辑于 2024-04-04 00:17:34 回复(0)
list_input = input().split(";")

list_todo = []
for todo in list_input:
    if len(todo) in [2, 3] and todo[0] in ["A", "D", "W", "S"] and todo[1:].isdigit():
        list_todo.append([todo[0], int(todo[1:])])

current_loc = [0, 0]
for a, b in list_todo:
    if a == "A":
        current_loc[0] -= b
    elif a == "D":
        current_loc[0] += b
    elif a == "W":
        current_loc[1] += b
    elif a == "S":
        current_loc[1] -= b

print(",".join(map(str, current_loc)))

发表于 2024-03-30 00:54:02 回复(0)
def valid_and_position(strs) -> list:
    if strs[0] not in ['A', 'S', 'W', 'D']&nbs***bsp;len(strs) > 3&nbs***bsp;strs[0] in ['a', 's', 'w', 'd']:
        return [0, 0]
    #以上是对 首位不是ASDW’以及坐标字符数量大于3的坐标进行排除
    new_str = ''
    for i in range(len(strs)-1):
        new_str += strs[i+1]
    if not new_str.isdigit():
        return [0, 0]
    #以上是对 首位是‘asdw’,但是其余位不是纯正数的无效坐标排除
    #以上均为无效坐标的判断

    if strs[0] == 'A':
        return [-int(new_str), 0]
    elif strs[0] == 'S':
        return [0, -int(new_str)]
    elif strs[0] == 'D':
        return [int(new_str), 0]
    elif strs[0] == 'W':
        return [0, int(new_str)]
    else:
        return [0, 0]

position = [0, 0]
line = input().split(';')
for i in range(len(line)):
    if line[i] == '':
        continue
    temp = valid_and_position(line[i])
    if temp[0] != 0:
        position[0] += temp[0]
    elif temp[1] != 0:
        position[1] += temp[1]
    else:
        continue
    
print(f'{position[0]},{position[1]}')

编辑于 2024-03-08 19:52:19 回复(0)
option = input().split(';') # 将输入值按照‘;’隔开,然后传入列表
x = 0
y = 0
for i in option: # 遍历列表
    try:
        if i[0] == 'A': # 如果字符串第一个字符是A,则x减去后面的数字值
                x -= int(i[1:])
        elif i[0] == 'S': # 如果字符串第一个字符是S,则y减去后面的数字值
                y -= int(i[1:])
        elif i[0] == 'W': # 如果字符串第一个字符是W,则y加去后面的数字值
                y += int(i[1:])
        elif i[0] == 'D': # 如果字符串第一个字符是D,则x加去后面的数字值
                x += int(i[1:])
        else: #如果第一个字符不是ASDW,则跳过
            continue
    except Exception as a: # 如果以上代码报错则跳过
        continue
print(f'{x},{y}')

纯新人写法

编辑于 2024-02-23 19:48:28 回复(0)
def move(lst):
    lst_out = [0, 0]
    for m in lst:
        dic = {"A": [-1, 0], "D": [1, 0], "W": [0, 1], "S": [0, -1]}
        if 2 <= len(m) <= 3 and m[0] in dic and m[1:3].isdigit():
        # 确定m的位数,第一位是否为ASDW,后面1-2位是否为数字
            lst_1 = [i * int(m[1:3]) for i in dic.get(m[0])]
            lst_out = [x + y for x, y in zip(lst_out, lst_1)]
    return lst_out

l = move((input().split(";")))
print(','.join(map(str,l)))
发表于 2023-12-20 14:49:57 回复(0)
import re

dList = input().split(";")
dArr = {"A": [-1, 0], "D": [1, 0], "W": [0, 1], "S": [0, -1]}
post = [0, 0]
for i in dList:
    match = re.match("^[A-Z](\d{1,2})$", i)
    if not match:
        continue
    else:
        move = "".join(re.findall("^[A-Z]", i))
        step = int("".join(re.findall("\d+", i)))
        if move in dArr:
            post[0] += dArr[move][0] * step
            post[1] += dArr[move][1] * step
print(post[0],post[1],sep=',')


发表于 2023-11-29 10:40:38 回复(0)
strs = input()
in_s = strs.split(";")
pos = [0, 0]
ary = ['A', 'D', 'W', 'S']
for s in in_s:
    s = str(s)
    if not 2 <= len(s) <= 3:
        continue
    e = s[0]
   
    if e in ary:
        if not s[1:].isdigit():
            continue
        s_num = int(s[1:])
        if e == "A":
            pos[0] -= s_num
        elif e == "D":
            pos[0] += s_num
        elif e == "W":
            pos[1] += s_num
        elif e == "S":
            pos[1] -= s_num

print(str(pos[0])+','+ str(pos[1]))
发表于 2023-11-22 13:56:34 回复(0)
import sys

in_list = input().split(';')
out = [0 , 0] # x, y
# 操作坐标 0 是x移动,1 是 y 移动. -1是减
my_dcit = {'A': [0, -1], 'D': [0,1], 'W': [1, 1], 'S': [1, -1]}
for i in in_list:
    if i == ''&nbs***bsp;i[0] not in [ 'A', 'S', 'W', 'D']:
        continue
    try:
        num = int(i[1:])
    except:
        continue
    # print(i)
    inx = my_dcit[i[0]]  # 取出坐标操作值 
    out[inx[0]] = out[inx[0]] + inx[1] * num # 坐标移动
    # print(out)
print(out[0], out[1], sep=',')

发表于 2023-10-28 20:15:02 回复(0)
str_list = input().split(";")
d = {}  # 字典
for item in str_list:
    if len(item) > 1 and item[0] in list("ADSW") and item[1:].isdecimal():
        d[item[0]] = d.get(item[0], 0) + int(item[1:])
x, y = (d["D"] - d["A"]), (d["W"] - d["S"])
print("%d,%d" % (x, y))

发表于 2023-10-09 11:53:48 回复(1)
#用字典去解决
n=input().split(';')
for i in n:
    if i=='':
        n.remove(i)
dic={'A':0,'D':0,'S':0,'W':0}
for i in n:
    if i[0] in dic and i[1:].isdigit():
        dic[i[0]]=dic.get(i[0])+int(i[1:])
print(int(dic['D'])-int(dic['A']),int(dic['W'])-int(dic['S']),sep=',')
发表于 2023-09-26 15:36:40 回复(0)
import re
valid_action = r"^[ADWS]\d{1,2}$"
input_str = input()
x, y = 0, 0
for char in input_str.split(";"):
    if re.match(valid_action, char):
        d, value = char[0], int(char[1:])
        if d in ("A", "S"):
            value = -value
        if d in ("A", "D"):
            x += value
        else:
            y += value
print(f'{x},{y}')


发表于 2023-09-21 13:12:06 回复(0)
swifts = input().split(';')
position = [0,0]
for swift in swifts:
    if swift[1:].isdigit():
        if swift[0] == 'A':
            position[0] = position[0] - int(swift[1:])
        elif swift[0] == 'D':
            position[0] = position[0] + int(swift[1:])
        elif swift[0] == 'W':
            position[1] = position[1] + int(swift[1:])
        elif swift[0] == 'S':
            position[1] = position[1] - int(swift[1:])
print(','.join(map(str,position)))

发表于 2023-09-17 16:57:47 回复(0)
while True:
    try:
        # 定义一个移动类,其中的计算函数用于给出移动后的坐标
        class Move(object):
            # 初始化坐标
            zuobiao = [0, 0]

            def jisuan(self, str):
                if str[0] == "W":
                    self.zuobiao[1] += int(str[1:])
                if str[0] == "A":
                    self.zuobiao[0] -= int(str[1:])
                if str[0] == "S":
                    self.zuobiao[1] -= int(str[1:])
                if str[0] == "D":
                    self.zuobiao[0] += int(str[1:])
                return self.zuobiao

        # 将输入的字符串按照分号分割,然后筛选出符合要求的字符串,再进行计算
        str = input().split(";")
        str = [i for i in str if (len(i) > 1 and (i[0] in ["A", "S", "W", "D"]) and i[1:].isdigit())]
        # 做完所有移动后,输出坐标
        for i in str:
            a = Move().jisuan(i)
        print(a[0], ",", a[1], sep="")

    except EOFError:
        break

发表于 2023-09-15 23:16:07 回复(0)
以每个字符串的第一个字母做为字典的key,字符串后面的用int强制转换,并做一个累加的动作,失败就放过;最后输出的时候只拿key为ABCD的值
string = input()

arr = string.split(';')
mid_dict = {}
for i in range(len(arr)):
    try:
        # 判断字典中是否存在该首字母 如果没有 则把中间值置为0
        mid_num = mid_dict.get(arr[i][0],0)
        # 强制转换 int 失败则说明后面是非法的 跳过即可
        mid_dict[arr[i][0]] = mid_num + int(arr[i][1:])
    except:
        continue

print(str(mid_dict['D'] - mid_dict['A'])+','+str(mid_dict['W'] - mid_dict['S']))


发表于 2023-08-14 14:59:54 回复(0)
发表于 2023-08-04 00:11:29 回复(1)
while 1:
    try:
        move = input().split(';')
        pos = [0, 0]
        for m in move:
            if  2 <= len(m) <= 3:
                try:
                    n = int(m[1:])
                    d = m[0]
                except:
                    continue
                if d == 'A':
                    pos[0] -= n
                elif d == 'D':
                    pos[0] += n
                elif d == 'W':
                    pos[1] += n
                elif d == 'S':
                    pos[1] -= n
        print(f"{pos[0]},{pos[1]}")

    except:
        break

发表于 2023-07-28 19:07:33 回复(0)

问题信息

难度:
69条回答 92822浏览

热门推荐

通过挑战的用户

查看代码