Home > Blockchain >  Assigning values to names in list
Assigning values to names in list

Time:04-27

connections = [('anna', 'bob'),('anna', 'bill'),('ian', 'anna'),('tim', 'bob'),
 ('bill', 'tim'),('ian', 'tim'),('bill', 'bob'),('ian', 'bob'),('ian', 'bill'),
 ('dawn', 'ian'),('kate', 'ian')]

def network_to_matrix(x):
    A = np.array(x)
    i = A[:,0]
    j = A[:,1]

    mat = np.zeros((5,5))

    for k in range(len(connections)):
        connections[n] = k[n].append(0 ,5)

    for k in range(1,5):
       mat[i[k],j[k]] = 1
    return mat

I currently have code that looks like this as I am trying to figure out how to assign values 0-5 to the names in the list and if the numbers are within the parentheses, a 1 goes in that location on a matrix. For example, if (1,5) is within the list, a 1 goes in for (1,5) and (5,1) on a matrix. This is an example of a desired output: enter image description here

CodePudding user response:

Firstly, please provide as much information as you can with your question:

  • Runnable code (yours isn't)
  • Expected result
  • Actual result

Name your variables more descriptively, so the reader can infer what it's supposed to contain and use the documentation, you can't index on the items provided from the range function.

Anyway, here's your function

import numpy as np

connections = [
    ("anna", "bob"),
    ("anna", "bill"),
    ("ian", "anna"),
    ("tim", "bob"),
    ("bill", "tim"),
    ("ian", "tim"),
    ("bill", "bob"),
    ("ian", "bob"),
    ("ian", "bill"),
    ("dawn", "ian"),
    ("kate", "ian"),
]


def network_to_matrix(conn_list):

    num_provider = iter(range(len(conn_list) * 2))
    name_map = {
        name: next(num_provider)
        for name in {name for pair in conn_list for name in pair}
    }

    # keep this somewhere
    print(name_map)

    conn_mat = np.zeros(2 * (len(name_map),))
    for start, end in conn_list:
        start_index, end_index = name_map[start], name_map[end]
        conn_mat[start_index, end_index] = 1
        conn_mat[end_index, start_index] = 1

    return conn_mat


matrix = network_to_matrix(connections)
print(matrix)
  • Related