Discussion of the bitwise operator operator

I am wondering what a python instruction is:

csum = (N * (N + 1)) >> 1

where N = 5and csum = 15. I do not understand the operator >>and what is happening in this statement. What is the thought behind this action? csumshould be the cumulative sum of vector 1: 5.

Rate your thoughts on this.

+6
source share
2 answers

Based on the Python wiki :

x >> yReturns xwith bits shifted to the right in yplaces. This is the same as // 'ing xon 2**y.

python (N * (N + 1)), >> 1:

In [4]: (N * (N + 1))
Out[4]: 30

In [5]: 30 >> 1
Out[5]: 15

, bin():

In [6]: bin(30)
Out[6]: '0b11110'

1, :

01111

int() 2 :

In [11]: int('01111', 2)
Out[11]: 15

operator.rshift():

In [12]: from operator import rshift
In [13]: rshift(30, 1)
Out[13]: 15

: https://en.wikipedia.org/wiki/Arithmetic_shift

python @eryksun, , 30 ( ) 2 1 ( ) , 2 .

bin(30) 11110, :

1 * 2 4 + 1 * 2 3 + 1 * 2 2 + 1 * 2 1 + 0 * 2 0

, 2, :

1 * 2 3 + 1 * 2 2 + 1 * 2 1 + 1 * 2 0 + 0 = 8 + 4 + 2 + 1 = 15

+5

>> , 1. 2 ^ N, 2 ^ 1 (, 2). :

csum = (N * (N + 1)) >> 1

N = 5, 5 * 6 / 2, 15.

, 1:5

+3

Source: https://habr.com/ru/post/1016812/


All Articles