Bitwise Programming in Python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to write a program to solve an ACM problem, and it has to be very fast. A mathematically fast approach to the problem is to use bitwise computations. However, I'm using python and I'm having trouble performing these computations at bit level. The problems are:
Counting the number of 1's and 0's in the bit. For example, how do we calculate the the binary digit 100010 has two 1's and 4 0's. The only approach I can imagine is to convert it to a string and and count them. But this conversion cancels out all the speed gained by working at bit level in the first place.
How to represent a string input describing the binary digit such as '100101' as an actual binary digit in Python? Currently I have a function that converts the bit into an integer and I perform the bitwise operations on the ints.
Is there a bit data type? That is can I receive the input as a bit rather than a string or an int?
I did consider writing a class such as bitSet in C++, but I have a feeling this will not be very fast either. P.S. the binary digits I'm working with can be as large as 1000 bits and I might have to work with a 1000 such binary digits, so efficiency is imperative.

Here's a well-known algorithm for counting the one-bits:
def bitCount(x):
count = 0
while x != 0:
count += 1
x &= (x-1)
return count
The point is that x-1 has the same binary representation as x, except that the least least significant one-bit is cleared to 0 and all the trailing 0's are set to one. So, setting x = x & (x-1) simply clears the least significant one-bit.

Related

python shift operator uses [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
Im just learning about pythons bitwise operator << and >>. as far as I see, it takes the binary version of an integer and shifts it n places left or right. that would mean that saying x<<y is equivalent to x*(2**y)
so my question is why is there an operator for this? as far as I know python doesnt like to give you more than 1 way of doing things to avoid confusion. is there a reason this operator is particularly useful or typical scenerios where its used? I know this is a pretty open ended question but when searching for this I only come across what this operator does, not why we would use it. thankyou in advance
The key is in your remark "it takes the binary version of an integer and shifts it n places left or right".
Ask yourself this: how does your computer represent integers at all? What are integers? Any integer is a sequence of bits, (typically a multiple of 8 bits, i.e. a byte) and your computer is built around memory positions, registers, addresses, etc. that hold these integer values.
So, it makes sense for a CPU to have an operation to shift such a value left or right by one bit, for an extremely fast multiplication or division by 2, more so since powers of two are very commonly needed because everything in your computer is binary.
Other operations can be composed from simple addition, subtraction, shift by n, etc. - Python exposes this operation to give you access to this very basic and quick operation, although Python integers aren't always (or even all that often) the same efficient integers you operate on directly in many other languages.
But bit-shifting has many applications, and as a standard operation of your computer, it only makes sense that Python would give you access to a tool that programmers are very used to, and have applications for in many common algorithms.

Averaging the digits of pi in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
As a preface, I must admit that this is my first real attempt to code a simple program from scratch, and I've just begun my foray into learning python.
As a simple project, I wanted to write a program to find the average value of the digits of π. In other words, we all know that π=3.141529....., but I set out to determine the value of (3+1+4+1+5+....)/(# of digits summed).
This was the result:
#retrieve the value of pi
n=math.pi
#request the number of digits of pi to average over
mag=input("how many terms?")
mag=int(mag)-1
#generate a string populated with the whole number values of the digits of py
k=int(round(n*10**(mag),0))
digits=[int(d) for d in str(k)]
print(k)
#sum the specified values of the digits of pi
print(sum(digits))
#recall the length of the string
print(len(digits))
#calculate average
print((sum(digits)/len(digits)))
The code runs well enough, but I am curious about what tweaks I could make to improve the program or simplify it.
Most specifically, I would like to know if there there is a simpler or more direct way to cast the individual digits of pi into a list or string of integers for manipulation. For instance, is there a specific operator one could use to call individual digits of a given number, like digit(0) returns 3 with respect to pi.
Any advice is greatly appreciated!

Difference between binary search and binary sort [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What is the difference between binary search and binary sort? (Or is there no such thing as binary sort.)
Can I perform binary search on an unsorted list? (I am a little in clear on this can someone please explain it to me.)
If I perform binary sort on an unsorted list and then binary search for an element in that (now) sorted list what will be the time complexity of the whole process?
Can I perform binary search on an unsorted list?(I am a little in clear on this can someone please explain it to me)
No you cannot,
The core idea of Binary search is to reduce the search space by value comparison.
for instance look at [1,2,3,4,5,6,7] and the element to be search for is 5.
in binary search we look at the middle element in this case 4, since the target element is greater than 4 and we know the array is sorted we can look only at the right half [5,6,7]
Binary search can also be implemented where the function is MONOTONOUS , example
[T , T , T , T , F , F , F]
You can apply binary search to find the first False in the array with this template
start=0, end=size
while(start<end)
if(condition)
end=mid
else
start=mid+1
return start
returning start will give you the first element which is false.

Indexed-based numbering in pseudocode [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm studying a-level computer science and my text shows array pseudocode declarations, some starting at 1 and others 0. Can anyone tell me why this is the case. Please note that I am studying Python.
DECLARE List1 : ARRAY[1:3] OF STRING // 3 elements in this list
DECLARE List2 : ARRAY[0:5] OF INTEGER // 6 elements in this list
DECLARE List3 : ARRAY[1:100] OF INTEGER // 100 elements in this list
DECLARE List4 : ARRAY[0:25] OF STRING // 26 elements in this list
There are languages that use either or both, and some algorithms are easier to express with one or the other. For instance, a textbook heap uses 1-based indexing. C and Python use 0 based indexing, Pascal and Ada let you choose, Lua and Matlab use 1 based. In practical terms, you mostly need to be aware which is used in the language you write.
https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array) lists the conventions used in a few languages. One bit of trivia that's not in there is the C way to find the number of elements in an array: sizeof(array)/sizeof(array[0]). It's rarely used because C's calling conventions strip size information by demoting arrays to pointers, anyway.
In languages like for example Pascal you actually decide what is the lower and upper bound for indexing. This is the notation the text is using.
In Python and most other programming languages instead the first element is always at index 0 and when declaring an array you only say what is the number N of elements.
In a few badly designed programming languages the first element is instead at index 1.

Python when substituting "**" instead of "+" into Fibonacci [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My code, stuck at 6561, unable to continue. I have tried printing B, I've tried substituting while True for a counter of greater value than the amount being printed. I have also tried different numbers for the original values, this could sometimes make it worse; eg. "a, b = 9, 10" will only print 9 and 10. Question, how do I unstick it?
the code
UPDATE: It appears that if you run this code in idle, then create a new python file, python stops responding.
It's not a bug with the code, it's a direct consequence of the size of the generated numbers.
8 ** 6561 is a 5926 digit number. The next step in the sequence is 6561 raised to the power of that 5926 number. That's where it gets stuck - the computation is simply too large for Python to handle in a reasonable amount of time.
Python supports arbitrary sized integers beyond the native size supported by the hardware, and the implementation requires memory to store the digits of the integer. The result is that your program will consume more and more memory until either the answer is produced, your system/process runs out of memory, or you run out of patience.
You will find that it works with multiplication and addition simply because the numbers involved are smaller, and so it will take a lot longer to reach the huge sizes produced by exponentiation.

Categories