【问题标题】:Why is my array comparison algorithm giving me the wrong output?为什么我的数组比较算法给了我错误的输出?
【发布时间】:2018-09-24 22:38:36
【问题描述】:

所以我正在尝试完成 Hackerrank.com 挑战“Compare The Triplets”,我得到了一个意想不到的输出:

Input (stdin)
    5 6 7
    3 6 10
Your Output (stdout)
    0 1
Expected Output
    1 1

所以我已经有代码可以满足挑战想要我做的事情,将一个数组与三个元素进行比较,但我认为将一个数组与 n 个元素进行比较会更有用。我写了一些代码来尝试让它工作,但输出不是应该的。目标是比较两个单独数组中元素的值。这是我的代码:

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the compareTriplets function below.
def compareTriplets(a, b):
loopLen = 0
if len(a) > len(b):
    loopLen = len(a)
elif len(a) == len(b):
    loopLen = len(a)
elif len(a) < len(b):
    loopLen = len(b)
for i in range(0, loopLen):
    bob = 0
    alice = 0
    if a[i] > b[i]:
        bob += 1
    elif a[i] == b[i]:
        bob += 0
        alice += 0
    elif a[i] < b[i]:
        alice += 1
    i += 1

return bob, alice

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

a = list(map(int, input().rstrip().split()))

b = list(map(int, input().rstrip().split()))

result = compareTriplets(a, b)

fptr.write(' '.join(map(str, result)))
fptr.write('\n')

fptr.close()

编辑:在 cmets 中回答的问题

【问题讨论】:

  • 你在循环中设置i = 0(这是错误的)并在它的末尾增加i += 1(这是没用的)。
  • 你指的listsarrays吗?
  • 什么是错误或输出(编辑问题以将其显示为格式正确的文本)?
  • 你应该删除你的工作代码,而是给我们输入和预期的输出
  • @Jodast 阅读以上评论,如果您想找到更好的方法,请给我们输入和预期输出,我们所拥有的只是您的解决方案,没有预期的结果或输入

标签: python arrays python-3.x algorithm comparison


【解决方案1】:

您可以压缩列表并从那里进行评估,这现在适用于任何大小的列表

alice = [5, 6, 7]
bob = [3, 6, 10]

score = [0,0]

l = list(zip(alice, bob))

for i in l:
    if i[0] > i[1]:
        score[0] += 1
    elif i[1] > i[0]:
        score[1] += 1
    else:  
        pass

print(score)
[1, 1]

【讨论】:

    【解决方案2】:

    我猜下面的函数适用于 2 个列表中的任意数量的元素

    def compTrip(a,b):
        alice = 0
        bob = 0
        result = []
        for i, j in zip(a,b):
            if i < j:
                alice = alice + 1
            if j < i:
                bob = bob + 1
        result.append(bob)
        result.append(alice)        
        return(result)
    

    【讨论】:

      【解决方案3】:

      @Jodast - 您的代码中的错误是您在 for 循环的每次迭代中将变量 alicebob 重新初始化为 0。将其从 for 循环中删除,您的代码将像魅力一样工作。

      有错误的行(从 for 循环中删除这些行):

      bob = 0
      alice = 0
      

      编码愉快! :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 1970-01-01
        相关资源
        最近更新 更多