【每日一题20220914】让死鱼游泳

:man_construction_worker: 编写一个简单的解析器来解析和运行 Deadfish。

Deadfish 有 4 个命令,每个 1 个字符长:

  • i 增加值(最初0
  • d 递减值
  • s 平方值
  • o 将值输出到返回数组

应忽略无效字符。

parse("iiisdoso")  ==>  [8, 64]

题目难度:一般
题目来源: Make the Deadfish Swim | Codewars

assert parse("ooo") == [0,0,0]
assert parse("ioioio") == [1,2,3]
assert parse("idoiido") == [0,1]
assert parse("isoisoiso") == [1,4,25]
assert parse("hogwarts") == [0]
import re


def parse(tell: str) -> list:
    start_number = 0
    li = []
    d_dic = {"i": lambda x: x + 1, "d": lambda x: x - 1, "s": lambda x: x * x}
    tell = re.sub("[^idso]", "", tell)
    for d in tell:
        if d == "o":
            li.append(start_number)
        else:
            start_number = d_dic[d](start_number)
    return li
def parse(s: str) -> list:
    result = []
    initial = 0
    for i in s:
        if i == "i":
            initial += 1
        elif i == 'd':
            initial -= 1
        elif i == 's':
            initial = pow(initial, 2)
        elif i == 'o':
            result.append(initial)
    return result
1 个赞
def parse(order:str)->list:
    num=0
    list_num=[]
    for i in order:
        if i=='i':num+=1
        elif i=='d':num-=1
        elif i=='s':num**=2
        elif i=='o':list_num.append(num)
    return list_num
def deadfish(string: str) -> list:
    sentinel = 0
    target_list = list()
    # 结合lambda优化循环
    dic = {"i": lambda x: x + 1, "d": lambda x: x - 1, "s": lambda x: x ** 2}
    string = re.sub("[^idso]", "", string)
    for i in string:
        if i == 'o':
            target_list.append(i)
        else:
            sentinel = dic[i](sentinel)
    return target_list
func Parse(data string) []int {
	tmp := 0
	res := make([]int, 0)
	for _, i := range data {
		if i == 'i' {
			tmp++
		} else if i == 'd' {
			tmp--
		} else if i == 's' {
			tmp = tmp * tmp
		} else if i == 'o' {
			res = append(res, tmp)
		}
	}
	return res
}
def parse(tell: str) -> list:
    x=0
    res_list=[]
    for j in range(len(tell)):
        if tell[j]=='i':
            x+=1
        elif tell[j]=='d':
            x-=1
        elif tell[j]=='s':
            x=x**2
        elif tell[j]=='o':
            res_list.append(x)
        else:
            continue
    return res_list

assert parse("ooo") == [0,0,0]
assert parse("ioioio") == [1,2,3]
assert parse("idoiido") == [0,1]
assert parse("isoisoiso") == [1,4,25]
assert parse("hogwarts") == [0]