>> and << operators?

Mensanator mensanator at aol.com
Fri Aug 22 19:10:58 EDT 2008


On Aug 22, 5:43 pm, "Medardo Rodriguez (Merchise Group)"
<med.... at gmail.com> wrote:
> On Fri, Aug 22, 2008 at 6:30 PM, defn noob <circularf... at yahoo.se> wrote:
> > What does >> and << do?
>
> Normally they are bitwise operators:>> Shifts bits right
>
> << Shifts bits left
>
> print 1 << 3
> 8
>
> because 8 = 00001000 in binary
>
> Regards

An example of usage:

import gmpy
def Collatz(n):
  #
  # if n is odd, multiply by 3 and add 1
  # if n is even, divide by 2 until n becomes odd
  # repeat until n == 1
  #
  while n>1:
    print n,
    f = gmpy.scan1(n)  # find position of first 1-bit
    if f>0:            # it's even, so...
      n = n >> f       # ...remove factors of 2 in one fell swoop
    else:              # it's odd
      n = 3*n + 1
  print n

print 'Collatz(11):',
Collatz(11)

print

print 'Collatz(27):',
Collatz(27)

##  Collatz(11): 11 34 17 52 13 40 5 16 1
##
##  Collatz(27): 27 82 41 124 31 94 47 142 71
##               214 107 322 161 484 121 364
##               91 274 137 412 103 310 155
##               466 233 700 175 526 263 790
##               395 1186 593 1780 445 1336
##               167 502 251 754 377 1132 283
##               850 425 1276 319 958 479 1438
##               719 2158 1079 3238 1619 4858
##               2429 7288 911 2734 1367 4102
##               2051 6154 3077 9232 577 1732
##               433 1300 325 976 61 184 23 70
##               35 106 53 160 5 16 1



More information about the Python-list mailing list