Can Anyone Please Explain this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

3rd Jan 2020, 5:09 PM
Ishmam
Ishmam - avatar
6 Answers
+ 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
3rd Jan 2020, 5:59 PM
Selin Genkur
+ 4
Haha, I'd like to hear that too! 😁
3rd Jan 2020, 5:14 PM
HonFu
HonFu - avatar
+ 4
I think the author of the code is an alien! 😱😩
3rd Jan 2020, 5:15 PM
Ishmam
Ishmam - avatar
+ 1
Selin Genkur But how do the print function works in the while loop?
4th Jan 2020, 2:39 AM
Ishmam
Ishmam - avatar
+ 1
'while' evaluates its condition at the begining of each loop and executes whatever there is in the condition.
4th Jan 2020, 2:45 AM
Selin Genkur
+ 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.
4th Jan 2020, 3:07 AM
Selin Genkur