罗克布剪刀(Python)枚举列表,根据逻辑提取值,并将这些值与原始lis进行比较

2024-04-28 15:18:19 发布

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

所以问题是有N个人排成一行,玩石头布剪刀。除了我,每个人只能使用一种手,表示为

['P', 'R', 'S', 'P']表示N只手。你知道吗

我可以使用任何类型,并且处于任意位置

我需要知道一旦名单到达我的对手是什么位置,所以N-A-1。这意味着我必须反复浏览列表,找出每一场比赛的赢家,并将结果与列表中的下一个位置进行比较,直到找到为止。你知道吗

我尝试的是创建一个winners的空数组,然后在给定的列表中枚举。你知道吗

一旦有了赢家的值,就会将其与列表枚举中下一个索引的值进行比较。你知道吗

我目前还没有解决当我进入最后一个迭代时会发生什么的方法,但是目前我的问题是我得到一个空列表作为优胜者的输出。你知道吗

任何关于这种逻辑列表的最佳实践的帮助都是很棒的,我还没有找到任何合适的。你知道吗

代码:

def previous_and_next(n, a, formations):
    positions = list(formations)
    print(positions)

    winners = []
    print(winners)    

    for i, pos in enumerate(positions):
        nex = pos[i + 1]
        if not winners:
            if pos == 'R' and nex == 'P':
                winners.append(nex)   
            elif pos == 'R' and nex == 'S':
                winners.append(pos)
            elif pos == 'R' and nex == 'R':
                continue
            elif pos == 'P' and nex == 'S':
                winners.append(nex)
            elif pos == 'P' and nex == 'R':
                winners.append(pos)
            elif pos == 'P' and nex == 'P':
                continue
            elif pos == 'S' and nex == 'R':
                winners.append(nex)
            elif pos == 'S' and nex == 'P':
                winners.append(pos)
            elif pos == 'S' and nex == 'S':
                continue
        if nex < len(positions-1):
            if  winners[-1:]    == 'P' and nex == 'R' or nex == 'P':
                continue
            elif winners[-1:]  == 'R' and nex == 'R' or nex == 'S':
                continue
            elif winners[-1:]  == 'S' and nex == 'P' or nex == 'S':
                continue
            elif winners[-1:]  == 'P' and nex == 'S':
                winners.append(pos)
            elif winners[-1:]  == 'R' and nex == 'P':
                winners.append(pos)
            elif winners[-1:]  == 'S' and nex == 'R':
                winners.append(pos)




def main():
    previous_and_next(5,0,'PRSP')

main()

Tags: orandpos列表ifdefnextelif
2条回答

你没有回应我要求澄清的评论。我现在发布了一个答案,我将修改后,你再次解释提示。我试着把你最初的帖子解释成一系列的步骤(正如我所理解的)。请让我知道这是否是您的计划流程:

    ['R', 'S', 'P', 'R', '?']
      0    1    2    3    A

1.) Player 0 and Player 1 play rock paper scissors.
    Player 0 wins, because (R)ock beats (S)cissors.

2.) The previous winner (Player 0) and Player 2 play rock paper scissors.
    Player 2 wins, because (P)aper beats (R)ock.

3.) The previous winner (Player 2) and Player 3 play rock paper scissors.
    Player 2 wins, because (P)aper beats (R)ock.

4.) The previous winner (Player 2) and Player A (you) play rock paper scissors.
    You must play (S)cissors to beat (P)aper

编辑-附加问题:假设我们有:

['S', 'R', 'P', 'S', 'S', 'R', 'P']
  0    1    2    3    4    5    6
  1. 石头胜过剪刀
  2. 纸胜过石头
  3. 剪刀胜过纸
  4. 剪刀和剪刀领带

既然我们已经到了第一局,到底发生了什么?你说两把剪刀被淘汰了,但是比赛怎么继续?我们是跳转到索引5的岩石上,让他们在索引6和纸比赛,还是跳转到最后一个有效的赢家(在这个例子中是索引2的纸),让他们在索引5和岩石比赛?谢谢你的进一步信息。你知道吗

编辑-这是我想出的一个解决方案。要计算出您需要进行多少手牌更改,您需要将您之前击败获胜手牌所需的手牌更改数(0或1)与您之后击败所有手牌所需的手牌更改数相加。我相信有一种更可爱的方式:

from enum import Enum


class Hand(Enum):
    Rock = 0
    Paper = 1
    Scissors = 2


class Game:

    def __init__(self, hands):
        self.hands = hands

    @staticmethod
    def get_winner_from_hands(hands):

        # This function, given a list of hands, will return the winning hand in that list.
        # In other words, it returns the type of hand that the winning player had in that list of hands.
        # This is especially useful if we pass in a sublist/slice of the whole list (the slice)...
        # ...would contain all hands before the player whose number of hand changes we are...
        # ... interested in computing.

        # This 'stack' list is meant to simulate the stack data-structure.
        # It's a stack of hands where, at any given moment, the most recent...
        # ...winning hand is on top of the stack.
        stack = []

        while hands:
            # While there are hands left to be matched up
            if not stack:
                stack.append(hands.pop(0))

            # 'top_hand' represents the hand that's on top of the stack...
            # ...(the most recent winning hand).
            top_hand = stack[-1]
            try:
                next_hand = hands.pop(0)
            except IndexError:
                # There were no more hands left to process.
                # This happens when we just had a tie (and cleared the stack as a result)...
                # ...but there was only one more hand left to process (and you need at least two for a match).
                # This can also happen if the 'hands' list that was passed in only had one hand in it.
                break
            winner = Game.get_match_winner(top_hand, next_hand)
            if winner is None:
                # It's a tie.
                stack.clear()
            elif winner is next_hand:
                stack.append(next_hand)

        try:
            # Return the last winning hand on the stack.
            return stack.pop()
        except IndexError:
            # If the stack was empty, there was no winning hand because of a tie.
            return None

    def get_number_of_hand_changes(self, hand_index):
        # Returns the number of times the player at index 'hand_index'...
        # ...must change their hand type in order to beat all other hands...
        # ...before them and after them.

        hands_before = self.hands[:hand_index]
        hands_after = self.hands[hand_index+1:]

        hand = self.hands[hand_index]

        # Who is the winner before us?
        previous_winner = Game.get_winner_from_hands(hands_before)

        if previous_winner is None or hand is Game.get_winning_hand(previous_winner):
            # All hands before 'hand_index' do not contribute to the total number of...
            # ...hand changes the player needs to make, either because of...
            # ...a tie, or we would beat the previous winner without changing hands anyway.
            hand_changes = 0
        else:
            # We either tied with, or didn't beat the previous winner.
            hand_changes = 1
            # Pick the hand we need to beat the previous winner.
            hand = Game.get_winning_hand(previous_winner)

        # This stack of hands represents the hand changes we need to make...
        # ...to beat the hands that come after us. At any given moment, the...
        # ...hand on top of this stack is the last hand change we've had to make.
        stack = []
        hands = hands_after

        while hands:
            top_hand = hand if not stack else stack[-1]
            next_hand = hands.pop(0)
            if top_hand is not Game.get_match_winner(top_hand, next_hand):
                stack.append(Game.get_winning_hand(next_hand))

        # The total number of hand changes we've had to make is...
        # ...the sum of the number of hand changes we've had to make to...
        # ...beat the winning hand before us, and  the number of hand changes...
        # we've had to make to beat the hands after us.
        return hand_changes + len(stack)

    @staticmethod
    def get_winning_hand(hand):
        # Given a hand, return the hand that beats it.
        return Hand((hand.value + 1) % len(Hand))

    @staticmethod
    def get_match_winner(hand_a, hand_b):
        # This function simulates a single Rock-Paper-Scissors match between two hands.
        # It returns the winning hand, or None if it's a tie.
        if hand_a is hand_b:
            return None
        return [hand_a, hand_b][Game.get_winning_hand(hand_a) is hand_b]


def main():

    hand_index = 4

    hands = [
        Hand.Rock,
        Hand.Scissors,
        Hand.Paper,
        Hand.Rock,
        Hand.Paper,  # hand_index
        Hand.Paper,
        Hand.Paper,
        Hand.Scissors,
        Hand.Rock
    ]

    game = Game(hands)

    hand_changes = game.get_number_of_hand_changes(hand_index)

    print(hand_changes)

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

我不是100%确定这个问题在问什么,但您的问题似乎是试图将字符串与int进行比较。请尝试nex = positions[i + 1]而不是nex = i + 1。你知道吗

相关问题 更多 >