奇数和偶数 HackerRank 挑战

Odd and Even HackerRank challenge

我正在尝试解决 HackerRank 上的一个问题,我发送了代码,它在几乎所有场景中都有效,除了场景 7 和 3,它们插入了 18,它应该 return“奇怪”并且当他们插入 20 时,根据网站,它也应该 return “奇怪”。

挑战规则为:

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')

我看不出我做错了什么,你能帮我解决一下,让它在所有场景下都能工作吗?

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

第一期:重新分配 'n'。

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

第二期: uneccesarry 'if'

'n%2 == 0' 的结果已经是 True/False,这取决于 n 是否是一个 even/odd 数字。所以你可以简单地分配结果,而不是使用 'if' 块。

第三期:多个运算符

逻辑运算符有运算顺序和分辨率。 'n == even > 5 < 20' 语句没有逻辑意义。相反,您应该进行独立的布尔比较,并将它们与“and”或“or”连接起来。例如。 'if isEven and n < 5 and n> 20'.