Leon Lang
Leon Lang

Reputation: 113

What went wrong in my Python Code?

I'm new to programming and Python specifically. Here I tried to write a code that receives a matrix (written as a list of lists) from the user and makes this string to a "real" list:

def string_to_matrix(arg):
    result = []
    lines = arg.count("[") - 1
    for i in range(lines):
        result.append([])
    count = 0
    i = 2
    while i <= len(arg):
        if arg[i] == "[":
            count += 1
            i += 1
        elif arg[i].isdigit():
            new_number = 0
            while arg[i].isdigit():
                new_number = 10*new_number + int(arg[i])
                i += 1
            result[count].append(new_number)
    return result


m_1 = string_to_matrix(raw_input("Type your first matrix in format [[x, y, ...],[z, ...],[...], ...]: "))
print m_1

But after I input a matrix (for example [[1]] or [[1, 2], [3, 4]]), the code loops forever and never prints anything. What did I do wrong?

Upvotes: 1

Views: 230

Answers (3)

gonczor
gonczor

Reputation: 4136

def string_to_matrix(arg):
    result = []
    lines = arg.count("[") - 1
    for i in range(lines):
        result.append([])
    count = 0
    i = 2
    while i < len(arg):
        if arg[i] == "[":
            count += 1
            i += 1
        elif arg[i].isdigit():
            new_number = 0
            while arg[i].isdigit():
                new_number = 10*new_number + int(arg[i])
                i += 1
            result[count].append(new_number)
        else:
            i += 1
    return result


m_1 = string_to_matrix(input("Type your first matrix in format [[x, y, ...],[z, ...],[...], ...]: "))
print(m_1)

You code has several issues. First of all raw_input and print used as a statement not as a function (without braces) will not work with python 3 you are using. Second, if you try to get to element of index i in a list consisting of exactly i elements, you will get out of its bound. Remember that most modern programming languages start iterating lists and arrays from 0, which means that maximum element you may get into has index i-1. Moreover, you are not increasing your i counter in every run, which causes your program enter infinite loop.

The code above is contains minimal changes I had to make to run it properly. However, it could be improved to meet Python standards and use everything it offers more efficiently.

  1. Use list comprehension where possible. This allows to keep your code simple and short. Consider using this:

    result = [[] for i in range(lines)]

Instead of this:

result = []
lines = arg.count("[") - 1
for i in range(lines):
    result.append([])
  1. Consider using split method on you string. Look at this:

    arg = '[[1, 2, 3],[4, 5, 6],[7, 8, 9]]'

    print(arg[2:-2].split('],['))

    ['1, 2, 3', '4, 5, 6', '7, 8, 9']

See? In one line you get a list of strings which you can easily parse to separate rows of your matrix. And with this look what happens now:

>>> l = '1, 2, 3'.split(',')
>>> l
['1', ' 2', ' 3']
>>> l1 = [int(value) for value in l]
>>> l1
[1, 2, 3]

Of course you can add some more meaningful names, checking for correctness of user data and so on, but I think you can make use of the examples I've written here.

Upvotes: 2

Prakhar Verma
Prakhar Verma

Reputation: 467

Go through the below code and see if it prints correct output.

def string_to_matrix(arg):
    result = []
    lines = arg.count("[") - 1
    for i in range(lines):
        result.append([])
    count = 0
    i = 2
    while i < len(arg):
        if arg[i] == "[":
            count += 1
            i=i+1
        elif arg[i].isdigit():
            new_number = 0
            while arg[i].isdigit():
                new_number = 10*new_number + int(arg[i])
                i=i+1
            result[count].append(new_number)
        else:
            i=i+1
    return result 

Upvotes: 2

Nipun Garg
Nipun Garg

Reputation: 658

Here is the another simple way if you like :

def string_to_matrix(arg):
    result = []
    i=1
    while i<len(arg)-1:
        if(arg[i]=='['):
            i+=1
            temp = ""
            while(arg[i]!=']'):
                temp+=arg[i]
                i+=1
            temp = temp.split(',')
            temp2 = []
            for j in temp:
                temp2.append(int(j.strip(' ')))
            result.append(temp2)
        else:
            i+=1
    return result


m_1 = string_to_matrix(raw_input("Type your first matrix in format [[x, y, ...],[z, ...],[...], ...]: "))
print m_1

Upvotes: 1

Related Questions