Python代码的输出
我是Python新手。这是我的 Wiered python 代码,它适用于所有输入,除了
c=0 和 r!=0 时。
我有许多测试用例(tc)、r 和 c 作为输入,根据条件给出所需的输出。
问题---对于输入 r=4 & c=0 ,输出应该是 2 ,但输出却是 1 。我对每个 r!=0 & 都得到错误的答案c=0。
代码:
tc=int(input())
while tc:
r,c=raw_input().split()
if int(r)%2==0 and r!=2 and r!=0 and c!=0:
r=int(r)/2
elif r!=2 and r!=0 and c!=0:
r=int(r)/2+1
elif r==0 or r ==2:
r=1
if r!=0:
if int(c)!=0:
print(int(r)*int(c))
else :
if int(r)%2==0 :
print(int(r)/2)
else:
r=int(r)/2+1
print(r)
else :
print(c);
tc=tc-1
示例输入和输出
4 //tc
10 10 //r=10 c= 10
50 //fine
3 3 //r=3 c=3
6 //fine
4 0 //r=4 c=0
1 //Should be 2 accoring to code
5 0 //r=5 c=0
2 //Output should be 3 accoring to the code
I am new at python. Here is my wiered python code Which works fine for all inputs except
when c=0 and r!=0 .
I have number of test case(tc) , r and c as inputs which give required output depending condition.
Question---For input r=4 & c=0 ,Output Should be 2,but output is coming 1 . I am geting wrong answer for every r!=0 & c=0.
Code:
tc=int(input())
while tc:
r,c=raw_input().split()
if int(r)%2==0 and r!=2 and r!=0 and c!=0:
r=int(r)/2
elif r!=2 and r!=0 and c!=0:
r=int(r)/2+1
elif r==0 or r ==2:
r=1
if r!=0:
if int(c)!=0:
print(int(r)*int(c))
else :
if int(r)%2==0 :
print(int(r)/2)
else:
r=int(r)/2+1
print(r)
else :
print(c);
tc=tc-1
sample input and output
4 //tc
10 10 //r=10 c= 10
50 //fine
3 3 //r=3 c=3
6 //fine
4 0 //r=4 c=0
1 //Should be 2 accoring to code
5 0 //r=5 c=0
2 //Output should be 3 accoring to the code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经自己解决了这个谜团(某种程度上):
r
是一个字符串。因此,r
将始终为!=2
,因为"2" != 2
始终为 true。所有其他比较也是如此。我猜你首先得到了一个
TypeError
与if r%2==0
,所以你改变了程序的那部分(也在你的所有其他地方)实际上正在用这些值进行计算),但忽略了将这种见解应用到程序的其他部分。因此,首先将所有输入转换为 int,然后开始应用程序逻辑。
You have solved the mystery yourself (kind of):
r
is a string. Sor
will always be!=2
because"2" != 2
is always true. Same goes for all the other comparisons.I'm guessing you first got a
TypeError
withif r%2==0
, so you changed that bit of the program (also in all the other places where you're actually doing calculations with the values) but neglected to apply this insight to the other parts of the program.So first convert all your inputs to
int
s, then start applying your program logic.