Python While循环中,and(&)运算符不起作用 [英] Python While Loop, the and (&) operator is not working

查看:1165
本文介绍了Python While循环中,and(&)运算符不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最大的共同因素.

I am trying to find the greatest common factor.

我写了一个错误的(运算密集型)算法,将较低的值减一,使用%检查是否将分子和分母均分,如果这样做,则退出程序.但是,我的while循环没有使用and运算符,因此一旦分子被整除,即使它的答案不正确,它也会停止.

I wrote a bad (operation intensive) algorithm that decrements the lower value by one, checks using % to see if it evenly divides both the numerator and denominator, if it does then it exits the program. However, my while loop is not using the and operator, and thus once the numerator is divisible it stops, even though its not the correct answer.

我使用的数字是54和42,正确的GCD(最大公分母)是6.

The numbers I am using are 54 and 42, the correct GCD (greatest common denominator) is 6.

#heres a simple algorithm to find the greatest common denominator: 

iterations = 0; #used to calculate number of times while loop is executed

u = 54; v= 42; d = v-1; #u is the numerator, v is the denominator, d is the number decremented by one 

while ((v % d !=0) & (u % d != 0)): #while both numerator AND denominator cannot be evenly divided by the decremented number
 d -= 1 #decrement the number by one
 print d #print the number decremented
 iterations +=1 #add 1 to the count of iterations in while loop

print "the gcd is " +str(d) #should be 6 when the number can evenly divide both
print "the number of iterations was " +str(iterations) #display times it took algorithm to complete

我得到的答案是27,这告诉我,一旦达到27,并且可以平均分配54/27,它就会停止.关于如何在python的while循环中使用and运算符的任何想法?

The answer I am getting is 27, which tells me once it reaches 27 and can divide 54/27 evenly, it stops. Any thoughts on how to use an and operator in a while loop in python?

谢谢!

推荐答案

您应该使用关键字and而不是按位和运算符&:

You should be using the keyword and instead of the bitwise and operator &:

while (v % d != 0) and (u % d != 0): 

这也是相同的:

while (v % d) and (u % d): 

请注意,在第一种情况下,&and会给出相同的结果,而在第二种情况下不会.

Note that & and and will give the same result in the first case, but not in the second.

但是,您的问题是您想使用or而不是and.另外,您的算法效率很低.有计算GCD的更好方法.

Your problem though is that you want to use or instead of and. Also your algorithm is highly inefficient. There are better ways to calculate the GCD.

这篇关于Python While循环中,and(&)运算符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆