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

时间:2016-11-02 02:10:49

标签: python list python-3.x character shift

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

示例:

#Input:

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

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

#Output:

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

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

这是我的代码到目前为止,但我真的无法弄清楚如何实现这一目标。也许我会用pop

def move_sideways(symbol, direction, lst):

    for symbol in range(len(lst))
        lst[1:] + lst[:1]
            return lst

1 个答案:

答案 0 :(得分:0)

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/vivus/0.3.1/vivus.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
</head>
<body>
  <svg id = "hexagon" viewbox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <pattern id="img" patternUnits="userSpaceOnUse" width="100" height="100">
      <image xlink:href="http://graphicloads.com/wp-content/uploads/2014/11/iron-man-illustration.png" x="-25" width="150" height="100" />
    </pattern>
  </defs>
  <polygon id="hex" points="50 1 95 25 95 75 50 99 5 75 5 25" />
</svg>

</body>

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