# CS190C: Spring 2009
# Problem Set 3, Problem 2
# Helper IO and visualization functions
#
# Submit this file - without changing its name - along with file problem2.py.
# import functions box, sphere, vector from VPython
from visual import box, sphere, vector
def read_points(filename):
"""
Read points from file filename.
>>> read_points("testdata0.txt")
[[0.0, 0.0], [1.0, -1.0], [2.0, 3.0]]
"""
file = open(filename, 'r')
points = [] #initialize our list of points
for line in file:
point = [] #a point is just a pair of numbers
str_coords = line.split() #split the line
#"2 4" -> ["2", "4"]
for str_coord in str_coords:
coord = float(str_coord) #convert coordinate to number
point.append(coord) #add coordinate to point
points.append(point) #add point to the list of points
file.close()
return points
def save_points(points, fname):
"""
Given a list of points, save them to the file named fname. These
points can be read back in with read_points(fname).
>>> save_points([[0,0],[1,-1],[2,3]], "testdata0.txt")
"""
file = open(fname, 'w')
for point in points:
for coord in point:
print >>file, coord,
print >>file
file.close()
def show_points(points, color=(0,1,0)):
"""
Given a list of 2D or 3D points, draw them as spheres in the active
VPython window. If no color is given, the spheres will be green.
#>>> show_points([[0,0],[1,-1],[2,3]])
"""
for point in points:
sphere(pos=point, radius=.5, color=color)
def random_points(n, d):
"""
Generate a list of n random points in d-dimensional space. For example,
if d=2, then the points will be in 2D space (they will have two
coordinates). The space that the points are placed in scales with n and d.
>>> len(random_points(5, 3))
5
"""
from random import uniform
r = int(n**(1./d)+1) # we use this so there is roughly
# the same density of points
# regardless of n or d
points = [] # initialize our list of points
for i in range(n): # n times...
point = [] # initialize our point
# (which is just a list of coords)
for j in range(d): # for each dimension...
point.append(uniform(-r, r))# add a random number to the point
points.append(point) # add our completed point to the list
return points
# Self-test code if this module is run directly...
#
if __name__ == "__main__":
import doctest
doctest.master = None
doctest.testmod()