华为od考试记录 - 代码编辑器 - Python

文章讲述了如何编写一个代码编辑器程序,接受指令序列对输入文本进行操作,如移动指针、查找、插入和删除。

互联网收集的od练习题, 记录解题过程. 因为无运行环境.暂时无法验证正确性,仅供参考 ( 这个需要编译环境调试,考试时提交多次才通过)

题目描述:
某公司为了更高效的编写代码,邀请你开发一款代码编辑器程序。
程序的输入为 已有的代码文本和指令序列,程序需输出编辑后的最终文本。指针初始位置位于文本的开头。
支持的指令(X为大于等于0的整数, word 为无空格的字符串):
FORWARD X 指针向前(右)移动X,如果指针移动位置超过了文本末尾,则将指针移动到文本末尾
BACKWARD X 指针向后(左)移动X,如果指针移动位置超过了文本开头,则将指针移动到文本开头
SEARCH-FORWARD word 从指针当前位置向前查找 word 并将指针移动到word的起始位置,如果未找到则保持不变
SEARCH-BACKWARD word 在文本中向后查我 word 并将指针移动到word的起始位置,如果未找到则保持不变
INSERT word 在指针当前位置前插入word,并将指针移动到word的结尾
REPLACE word 在指针当前位置替换并插入字符(删除原有字符,并增加新的字符)
DELETE X 在指针位置删除X个字符
输入:
输入的第一行为命令列表的长度K
输入的第二行为文件中的原始文本
接下来的K行,每行为一个指令
输出:
编辑后的最终结果

输入:
1
ello
INSERT h
输出: hello

输入:
2
hllo
FORWARD 1
INSERT e
输出: hello

自定义输入:
7
hllo
FORWARD 1
BACKWARD 1
SEARCH-FORWARD l
SEARCH-BACKWARD l
INSERT word
REPLACE word
DELETE 2

输出: hwordrd

def solution():
    k = int(input())
    content = input()
    index = 0
    cmds = []
    for i in range(k):
        cmds.append(input().split())

    for cmd in cmds:
        opt, s = cmd
        if opt.startswith("FORWARD"):
            index = min(index + int(s), len(content))  # 越界问题
        elif opt.startswith("BACKWARD"):
            index = max(0, index - int(s))
        elif opt.startswith("SEARCH-FORWARD"):  # 越界问题
            if s in content[index:]:
                index += content[index:].index(s)
        elif opt.startswith("SEARCH-BACKWARD"):
            if s in content[:index + 1]:
                for j in range(index, -1, -1):
                    if s in content[j:index + 1]:
                        index = j
                        break
        elif opt.startswith("INSERT"):
            content = content[:index] + s + content[index:]
            index += len(s)
        elif opt.startswith("REPLACE"):
            content = content[:index] + s + content[index + len(s):]

        elif opt.startswith("DELETE"):
            content = content[:index] + content[index + int(s):]

    print(content)


if __name__ == '__main__':
    while True:
        solution()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值