1

I want to convert series of numbers in to arrays in Python without using any libraries. ( 0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8) (1,3 3,4 5,9 7,5 10,2 11,4 20,10 ) (0,0 6,6 12,3 19,6 (green)) for example these three series. Is it possible to do it without libraries like numpy? I tried to use numpy but and reached the solution like this for the first series.

array([[ 0,  2],
       [ 3,  0],
       [ 4,  5],
       [ 7,  8],
       [ 8,  6],
       [ 9,  5],
       [13,  6],
       [15,  9],
       [17, 10],
       [21,  8]])

but the professor did not accept that.

3
  • How are this series provided to you?...what is the initial data structure?...string...generator...or what? Commented Apr 2, 2016 at 19:43
  • I Am given the following input in coordinates x,y: 0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8 1,3 3,4 5,9 7,5 10,2 11,4 20,10 0,0 6,6 12,3 19,6 Commented Apr 2, 2016 at 20:13
  • So this is a string? Commented Apr 2, 2016 at 20:43

2 Answers 2

1

If

a = "1,2 2,3 3,4 ..."

then

result = [map(int, v.split(",")) for v in a.split()]

Will give you

print result
[[1, 2], [2, 3], [3, 4], ... ]
Sign up to request clarification or add additional context in comments.

Comments

0

If series of numbers are string line then you could try next code:

a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"

lines = a.split(' ')
arr = [[int(i) for i in x.split(',')] for x in lines]
print arr

output

[[0, 2], [3, 0], [4, 5], [7, 8], [8, 6], [9, 5], [13, 6], [15, 9], [17, 10], [21, 8]]

EDIT (avoid O(n^2)):

One way passing:

a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"    
position = 0
previous_position = 0
final_array = []
temp_array = []
for character in a:
    if character == ',':
        temp_array = []
        temp_array.append(int(a[previous_position:position]))
        previous_position = position
    elif character == ' ':
        temp_array.append(int(a[previous_position+1:position]))
        previous_position = position+1
        final_array.append(temp_array)
    elif position == len(a) - 1:
        temp_array.append(int(a[previous_position+1:]))
        final_array.append(temp_array)

    position += 1

print final_array

1 Comment

Thanks a lot. It works. But for the sake of complexity it runs O(n^2) because of the nested loop. Is there any way to it in O(n)??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.