dvdktn
dvdktn

Reputation: 63

Parsing numbers into point objects in Python

I need to get an input line from the user. It must be a series of numbers separated by spaces. I need to parse the input into a series of Point objects. The points are like points on a Cartesian plain (x, y). And finally I have to print those point out like (1, 2), (3, 4), (5, 6), etc.

If the input is

"0 1 2 3 4 5" 

the output should be

(0, 1), (2, 3), (4, 5)

The code have so far looks like

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __str__(self):
        return ('(%f, %f)' % (self.x,self.y))
if __name__ == "__main__":
    points = []
    usrIn = input()
    tokens = usrIn.split(' ')
    for token in tokens:
        #not sure what to do here ****************
    print(points)

Does this code look like it's on the right track?

I'm kinda lost on this assignment. Not sure how objects really work yet, any explanation would be appreciated. Thanks.

Upvotes: 0

Views: 337

Answers (2)

Paul Rooney
Paul Rooney

Reputation: 21609

You can split the string on spaces and then zip the alternate elements of the split list.

s = "0 1 2 3 4 5" 

x = s.split();
print(list(zip(x[::2], x[1::2])))

The 3rd parameter to a slice is the stride. So it takes every 2nd element from the list (0, 2, 4, etc) and the second slice is also a slice with stride 2 but starting from index 1 (1,3,5, etc).

The list call is only there to force immediate evaluation for the print statement. It's not required if you will later iterate over the return value of zip.

The above outputs tuples. If you want to turn them into Point objects.

points = [Point(*map(float,t)) for t in zip(x[::2], x[1::2])]
for p in points:
    print('%s' % p, end='')
print()

It looks a bit magical, but essentially its just calling the Point constructor in a loop with each pair of values. The map(float, t) part converts the two coordinates to float values (I inferred this from your __str__ method) and the * explodes the tuple into the 2 values for the constructor.

The output is

(0.000000, 1.000000)(2.000000, 3.000000)(4.000000, 5.000000)

You didn't ask for all the trailing 0's but your __str__ is printing floats, so I left it like that.

Also in your example you try to print the list itself directly using print(points). If you want each list item to custom print itself in this situation, you should define the __repr__ function.

Upvotes: 2

Prune
Prune

Reputation: 77837

points = [(tokens[i], tokens[i+1]) for i in range (0, len(tokens), 2)]

This should return you a list of the tuples you want. Drop the for loop; it's included in this statement (called a "list comprehension").

You might note that the point coordinates are still strings. You may want to convert the two items in the tuple to int.

Upvotes: 1

Related Questions