Guest User

Verify solutions for powers of 2

a guest
Mar 6th, 2020
101
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # For X you are giving the input for 2**X
  2. # For solution, you provide your solution
  3. # and the algorithim is suppose to decide if its correct
  4.  
  5. X =  int(input('enter your exponent for X: '))
  6. solution = int(input('enter your solution for 2**X: '))
  7.  
  8. # Converting solution into binary
  9.  
  10. binary = "{0:b}".format(int(solution))
  11.  
  12. # Powers of 2 should only have ONE 1-bit and the rest 0-bits.
  13. # Using a slice to make sure that all bits are 0 after the first Index.
  14.  
  15. zero_bits = binary[1:]
  16.  
  17. if zero_bits.count(str('1')) != 0:
  18.   print(zero_bits.count(str('1')) == 0)
  19.   # returns false if solution is not a power of 2
  20.   quit()
  21.  
  22. # Below the statement checks the length of 0-bits comparing to the value X
  23. # if both equal then it returns True.
  24.  
  25. if len(zero_bits) == X:
  26.   print(len(zero_bits) == X)
  27.   # Returns True if solution is correct
  28. else:
  29.   print(len(zero_bits) == X)
  30.   # Returns False if solution is wrong
RAW Paste Data