0

How can I implement the following algorithm in python:

enter image description here (source)

def getGraycodeRank(n, t):
    r = 0#range
    b = 0
    for i in reversed(range(0, n)):
        if n - i IS IN t: #how to check it?
            b = 1-b
        if b == 1:
            r += 2^i
    return r
TooTone
  • 7,129
  • 5
  • 34
  • 60
Michal_Szulc
  • 4,097
  • 6
  • 32
  • 59

2 Answers2

0

You can use the in operator:

if (n - i) in t:

or simply

if n - i in t:

Also, the operator ^ doesn't do what you think. To get the power of a number, use **:

r += 2**i

Note:

  • The in operator will work with tuples, lists, dicts, strings.

Edit:

Since t is a string, to check if an integer (n - i) is contained by t, you will have to convert the integer n - i to a string:

if str(n - i) in `t`:
    # ...
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

assuming t is a dict or list

if (n - i) in t:

this should work...

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264