We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Bit operations in Python tend to not be very efficient. From my understanding, this is due to the fact that, internally, CPython (the most common implementation) represents its integers as C-structs, and all types in CPython (including presumed value types such as ints) actually live on the CPython private heap as objects.
To get max efficiency out of bit operations, you need to use a lang that fully employs value-types, stored on the stack. (There still may be some times where representing data as bits makes sense in Python, but this is a data structures issue.) When it comes to efficiency, bitwise operators such as << are rarely the best choice in langs like Python. (Not to mention that these may not precisely do what you expect, as Python will simply grow your int to accommodate overflow -- so no dropping of bits following a left-shift.)
However, I believe that some external libraries, like numpy, make improvements to some of CPython's standard numeric implementations, and I believe these may improve the baseline efficiency of << and the like. Generally, though, standard C-tricks like utilizing x >> n to divide by 2^n won't be worth it.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Two Strings
You are viewing a single comment's thread. Return to all comments →
Bit operations in Python tend to not be very efficient. From my understanding, this is due to the fact that, internally, CPython (the most common implementation) represents its integers as C-structs, and all types in CPython (including presumed value types such as ints) actually live on the CPython private heap as objects.
To get max efficiency out of bit operations, you need to use a lang that fully employs value-types, stored on the stack. (There still may be some times where representing data as bits makes sense in Python, but this is a data structures issue.) When it comes to efficiency, bitwise operators such as << are rarely the best choice in langs like Python. (Not to mention that these may not precisely do what you expect, as Python will simply grow your int to accommodate overflow -- so no dropping of bits following a left-shift.)
However, I believe that some external libraries, like numpy, make improvements to some of CPython's standard numeric implementations, and I believe these may improve the baseline efficiency of << and the like. Generally, though, standard C-tricks like utilizing x >> n to divide by 2^n won't be worth it.