奇偶黑客挑战

2024-09-14 22:57:56 发布

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

我正试图解决HackerRank上的一个问题,我发送了代码,除了scnario 7和3之外,它在所有的scnario中都能正常工作,在scnario 7和3中,它们插入18,应该返回“怪异”,当它们插入20,也应该返回“怪异”

挑战的规则是:

Given an integer, n, positive number from 1 to 100 , perform the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird Input Format

A single line containing a positive integer, .

Constraints

Output Format

Print Weird if the number is weird. Otherwise, print Not Weird.

我的代码是:

n = 0
n = int(input('Type a number between 1 and 100: '))
odd = False
even = True

# ODD / EVEN
if (n%2) == 0:
    n = even #True
else:
    n = odd #False

# Is this odd or is this even?
if n == odd:
    print ('Weird')
    if n == even > 5 < 20:
        print('Weird')
elif n == even > 1 < 6:
    print ('Not Weird')
else:
    print('Not Weird')

我看不出我做错了什么,你能帮我解决这个问题,这样它就可以在所有的scnarios中运行吗


Tags: andtheto代码numberifisnot
1条回答
网友
1楼 · 发布于 2024-09-14 22:57:56

这里有很多东西要解开。由于这是一项作业,我不打算在这里打印完整的解决方案,但我会指出您所犯的错误,以便您能够得出正确的解决方案

第一个问题:重新分配“n”

将输入值指定给n,然后用奇数或偶数替换。这意味着您丢失了原始输入号码。相反,您应该将结果分配给一个新变量(例如“isEven”)

第二个问题:不成功的“如果”

“n%2==0”的结果已为真/假,具体取决于n是否为偶数/奇数。因此,您可以简单地分配结果,而不是使用“if”块

第三个问题:多运营商

逻辑运算符具有操作顺序和分辨率。语句'n==偶数>;5<;20'没有逻辑意义。相反,您应该进行独立的布尔比较,并用“and”或“or”连接它们。例如,“如果为偶数且n<;5和n>;20'.

相关问题 更多 >