【问题标题】:Survive the attack (7 kyu) - comparing arrays在攻击中幸存下来 (7 kyu) - 比较数组
【发布时间】:2022-12-11 23:38:21
【问题描述】:

我遇到了麻烦

给定两个数组,其中值是每个士兵的力量,如果你在攻击中幸存则返回真,如果你死了则返回假。

条件

每个士兵攻击数组相同索引中的对方士兵。幸存者是具有最高价值的数字。

如果价值相同,他们都会灭亡

如果其中一个值是空的(不同的数组长度),则非空值士兵会存活下来。

为了生存,防御方必须比攻击方有更多的幸存者。

如果双方的幸存者人数相同,则初始攻击力最高的一方获胜。如果双方的总攻击力相同则返回真。

初始攻击力是每个数组中所有值的总和。

这是我尝试做的- 它通过了大约一半的测试,并为另一半返回错误的值。我不知道为什么

    def is_defended(attackers, defenders):
    survivors_a = 0
    survivors_b = 0
    
    if attackers < defenders:
        survivors_b+=1
        
    if attackers > defenders:
        survivors_a+=1
    
    if attackers == defenders:
        survivors_a+=0
        survivors_b+=0

    if survivors_a == survivors_b and sum(attackers) > sum(defenders):
        return False
    
    if survivors_a == survivors_b and sum(attackers) < sum(defenders):
        return True
    
    if survivors_a == survivors_b and sum(attackers) == sum(defenders):
        return True
        
    elif survivors_a > survivors_b:
        return False
    
    elif survivors_a < survivors_b:
        return True
    

【问题讨论】:

  • 假设 attackersdefenders 是数组,您没有进行任务涉及的任何成对比较。

标签: python arrays


【解决方案1】:
  • 将攻击者中的第一项与防御者中的第一项进行比较;决定哪一个幸存

  • 将攻击者中的第二项与防御者中的第二项进行比较;决定哪一个幸存下来。
    ...

  • 将攻击者中的第 N 项与防御者中的第 N 项进行比较;决定哪一个幸存

  • 比较幸存者人数

【讨论】:

    【解决方案2】:

    您的代码不起作用的原因是您关于比较运算符如何在数组上工作的假设是错误的。

    您需要做的是比较它们逐个元素:

    # I'm assuming that there's as many attackers as defenders, for the sake of brevity 
    surviving_attackers = 0
    surviving_defenders = 0
    for i in range(len(attackers)):
      if attackers[i] > defenders[i]:
        surviving_attackers += 1
      elif attackers[i] < defenders[i]:
        surviving_defenders += 1
      else:
        pass # if strengths are equal, neither soldier survives
    
    # and then compare the number of survivors and account for initial strength to resolve a tie if both sides have the same number of survivors
    

    或者,对于更 pythonic 的方法,请执行以下操作:

    for attacker_strength, defender_strength in zip(attackers, defenders):
       if attacker_strength > defender_strength:
         surviving_attackers += 1 
       # ... and so on ...
    

    代替:

    for i in range(len(attackers)):
       #  ... comparison code ...
    

    要处理长度不均匀的列表,请使用 itertools.zip_longest 而不是 zip

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      相关资源
      最近更新 更多