将列表1的列表中的字符向左或向右移动。移位后,如果可能,返回true;如果可能,则返回false

2024-05-12 20:59:34 发布

您现在位置:Python中文网/ 问答频道 /正文

如果可能,则指示随机字符向左或向右移动1个位置,并返回True;如果不可能,则返回False。在

示例:

#Input:

[['.', 'B', 'B', '.', '.', '.']]

move_sideways("B", "RIGHT", lot0)

#Output:

True
[['.', '.', 'B', 'B', '.', '.']]

所以两个B都有可能移动到正确的一个位置。如果其中一个B在第一个位置并且被指示向左移动,它将返回False,因为这是不可能的。如果B在最后一个位置并且指示向右移动,则相同。在

到目前为止,这是我的代码,但我真的不知道如何实现这一点。也许我会用流行音乐

^{pr2}$

Tags: 代码rightfalsetrue示例inputoutputmove
1条回答
网友
1楼 · 发布于 2024-05-12 20:59:34

这可能不是最有效的方法,但它是有效的。我很乐意回答任何有关它的问题,但我很快就要睡觉了。在

def move_sideways(symbol, direction, lst):

    if symbol not in lst:
        print('symbol is not in list')
        return False

    ind = [i for i, x in enumerate(lst) if x == symbol] #retunrs a list of the index of every symbol in list [1,2] in given example

    if direction == 'RIGHT':
        if ind[-1]+1 == len(lst):                       #check to see if the right most move will go out of the list 
            return False
        for x in ind[::-1]:
            lst.insert(x+1,lst.pop(x))                  #this will pop out every symbol and insert them back in one to the right  


    if direction == 'LEFT':
        if ind[0] == 0:                                 #checks if the left most symbol is at 0
            return False 
        for x in ind:
            lst.insert(x-1,lst.pop(x))                  #this will pop out every symbol and insert them back in one to the left

    return(True,lst)                                    #return the new list and a True in a tuplit

一。在

^{pr2}$

相关问题 更多 >