0

This is my code:

def brujinGraph(k, strList):

    vertex = [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0]]

    brujinGraph = {strList[i]: strList[j][:-1] for i in range(len(vertex)) for j in range(k) and vertex[i][j] == 1}

    return brujinGraph

strList = ['AAGA', 'AAGA', 'AGAT', 'ATTC', 'CTAA', 'CTCT', 'GATT', 'TAAG', 'TCTA', 'TCTC', 'TTCT']
brujinGraph(4, strList)

and it is throwing me an UnboundLocalError: local variable 'j' referenced before assignment

any idea what does it means and why am I getting this error?

masber
  • 2,875
  • 7
  • 29
  • 49
  • 2
    Possible duplicate of [Create a dictionary with list comprehension in Python](http://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python) – Jason Mar 13 '16 at 01:06
  • Please show us the rest of your code so we can reproduce it. To me it looks like your trying to reference a key `j` in `strList`(assuming `strList` is a dict) when j doesnt exist in `strList`. – Jason Mar 13 '16 at 01:08
  • The second range will be evaluated before the `for j`, and the range depends on `j`. That just won't work. – Joachim Isaksson Mar 13 '16 at 01:10
  • @Signal I put my code so you can reproduce – masber Mar 13 '16 at 01:24
  • @JoachimIsaksson I get same error even if I change the second range with a contant – masber Mar 13 '16 at 01:25
  • Could you explain what your desired output is? There are multiple oddities in the comprehension so I can't quite figure out what needs to be changed to get the result you're looking for. – Joachim Isaksson Mar 13 '16 at 07:35

2 Answers2

1

Without knowing exactly what vertex and strList are :

Do you actually mean :

{strList[i]: strList[j][:-1] for i in range(len(vertex)) for j in range(len(vertex[i])) if vertex[i][j] == 1}

i.e. change that and into an if

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
1

Couple of issues:

  1. You need an if not an and at the end

  2. I think it is better expressed this way:

    brujinGraph = {strList[i]: strList[j][:-1] for i, x in enumerate(vertex) for j, e in enumerate(x) if e == 1}

Community
  • 1
  • 1
dawg
  • 98,345
  • 23
  • 131
  • 206