+ 4
Can Anyone Please Explain this code?
I just get mad whenever I look at this code!!! Can Anyone Please explain this code?? https://code.sololearn.com/c2dIXIjcwKFe/?ref=app
6 ответов
+ 7
n,p=0,int(input())
while print(n,p)or~-p:n,p=-~n,[p>>1,p*3+1][p&1]
I will try to explain only the weird parts.
print(n,p) is only there to print, the 'while' condition depends only on '~-p' which will be 0 when p is 1.
Then: n = -~n is equivalent to n += 1
p>>1 is actually p//2.
and [a,b][p&1] will be a if p is even, and b if p is odd.
(almost) equivalent code:
n = 0
p = int(input())
while p != 1: #~-p
print(n, p)
n += 1 #n = -~n
if p % 2:
p = p*3 + 1
else:
p = p//2 #p>>1
+ 4
Haha, I'd like to hear that too! 😁
+ 4
I think the author of the code is an alien! 😱😩
+ 1
Selin Genkur But how do the print function works in the while loop?
+ 1
'while' evaluates its condition at the begining of each loop and executes whatever there is in the condition.
+ 1
Now I realized that my "equivalent" code isn't that equivalent, as his code executes print() even when p==1, while mine just exits the loop.