HackerRank Python print STDOUT似乎没有

2024-05-23 17:43:12 发布

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

我对Python非常陌生,所以正在尝试HackerRank上的'Counting Valleys'问题。 我用PyCharm编写了我的解决方案,它运行良好/给出了解决方案预期输出的正确答案。在

  • 我试图在这个网站上搜索,但似乎没有找到具体的东西,所以我一定漏掉了一些显而易见的东西。在

问题是,当我把代码移植到HackerRank时,它只是说“错误答案”。在

我想通过使用“打印”或其他任何方式来获得反馈,从而了解问题所在。在

下面我添加了'打印'线不同的地方,以显示我也尝试过的领域。在

这是我遇到这个问题的第二个解决方案,任何建议/建议都将不胜感激,因为它超级烦人和令人沮丧的继续工作,任何帮助感激。在

# !/bin/python

import math
import os
import random
import re
import sys
import logging


# Complete the countingValleys function below.
def countingValleys(n, s):
    print('Please print')
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')

        n = int(raw_input())
        s = raw_input()

        sea_level = 0
        valleys = 0
        last_step = ''
        in_same_valley = False
        print('Ok maybe here?')
        for step in s:
            if step == 'D':
                if last_step == 'D' and sea_level <= 0:
                    if not in_same_valley:
                        valleys += 1
                        in_same_valley = True
                sea_level -= 1
            else:
                sea_level += 1
                in_same_valley = False
            last_step = step

        print('Ok perhaps here?')
        fptr.write(str('valleys') + '\n')
        fptr.close()
    print('Ok try here?')

Tags: inimportifherestepok解决方案level
2条回答

你的缩进错了。尝试类似于:

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countingValleys function below.
def countingValleys(n, s):
    print('hi')

# The below line should not be inside the function countingValleys
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    ....

它应该会起作用的。您将在底部的Debug output框中看到输出

计数谷挑战

这就是我如何解决我的计数谷挑战

def countingValleys(n, s):
    ls = list(s)
    seeLevel = 0
    valley = 0
    for i in ls:
        if i == 'U':
            seeLevel += 1
        else:
            if seeLevel == 0:
               valley +=1
            seeLevel-= 1
    return valley
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(raw_input())
    s = raw_input()

相关问题 更多 >