Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help.
#1
Below, is an assignment I was given, first of all I'm no where near this level in math yet but the math operation line for this should be something like: distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2) I think, anyway we just covered opening files, reading files, outputting to files and that part is new to me.

My question is do I want to use file.readlines() for something like this and if so, how do I go about running loop over my lists? Below is the assignment:


In Cartesian coordinate system, the distance between two points

## Page will not display special characters from this file but the formula is: the distance between P1 and P2 = square root
of: ((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2) ##

In this lab, you are writing a small program which reads in several sets of point coordinates from an input file, calculates their distances, and writes those calculated distances to an output file.

Reading from and Writing to Files

There are exactly six integers (could be negative) appear in each line of the input file. The first three numbers represent the first point P1( x 1 , y 1 , z 1 ) , and the next three numbers represent the second point P2 ( x 2 , y 2 , z 2 ) . You cannot assume how many lines are in the input file. Your program should read all the data from the input file.

After reading the six numbers in a line, your program calculates the distance between the two points, which should be floating-point number. Then, your program outputs the calculated distance to the output file. Each distance is in a separate line in the output file.

Writing the Distance Function

You need to write a function called calcDistance, which takes in 6 arguments (all integers) that represent the x x , y y and z z coordinates of the two points. The method calculates the distance between the two points, and returns the value (floating-point).
Reply
#2
What have you tried? We're not big on writing code for people here, but we would be happy to help you fix your code when you run into problems. When you do run into problems, please post your code in Python tags, and clearly explain the problem you are having, including the full text of any errors.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Not looking for someone to write the code. More or less looking for advice about the logic behind something like this, obviously define a math function, open file, readlines()? -> creates a list of strings of each line? <- This is where i'm shaky about it, he went over that very fast in lecture. Run a for loop using the math function on the list and write to an output file
Reply
#4
In general, programming in any language is reading tons of documentation.
It is supposed that you'll use math module to compute sqrt, when computing distance. So, you need to read official documentation
about math.sqrt function. You even could implement distance function without explicitly using of sqrt function, e.g.
(I just wrote and didn't test it):

def calc_distance(x, y, tol=0.001, maxiter=100):  
    """Get distance between two points without using math.sqrt function
    This function uses iterating process to compute square root of a value.
    It shouldn't be used in real world applications, it is quite slow.
    
    Example
    -------
    >>> x = [0, 0, 0]
    >>> y = [1, 1, 1]
    >>> calc_distance(x, y)
    # expected value is 1.73 etc.
    """

    eps = 1
    a = sum((a - b) * (a - b) for a, b in zip(x, y))
    approx_sqrt = a / 2
    ind  = 0
    while eps > tol and ind < maxiter:
        eps = approx_sqrt
        approx_sqrt = 0.5 * (approx_sqrt + a / approx_sqrt)
        eps = abs(eps - approx_sqrt)
        ind += 1
    return approx_sqrt
This is the first step... Further, you'll need to find docs about reading and writing data to files. Also, you'll need to find info about how to work with strings. Every line read from a file should be parsed into numbers. Decompose original problem into small and clear for understanding ones, write functions solving these problems and compose entire solution from them. Hope that helps...
Reply
#5
[list=1]
[*]import math

#def calcDistance(x1, x2, y1, y2, z1, z2):
 #   distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)
    
  #  return distance

output_file = open('output.txt', 'w') 
nums = []
nums.append(open('input.txt', 'r'))

lines_of_file = []
for lines in nums:
    lines_of_file.append(lines.readlines())
       
print(lines_of_file)
[/list]
print returns: [['1 2 3 4 5 6\n', '7 8 9 0 1 2\n', '9 8 7 1 2 3\n', '11 12 13 14 15 16\n', '99 99 99 99 99 99\n', '\n']]
This is the correct numbers from the sample file he provided, however it should probably be [['1, 2, 3, 4, 5, 6], [etc, etc]] in order to work with it further

How can I split the contents of each string? When I use the split function it returns an error:

AttributeError: 'list' object has no attribute 'str'
Reply
#6
1) It would be better to handle files using context manager protocol, using with, e.g.

with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
    # do some stuff here
You wouldn't need to take care about closing files, if they were opened using with statement.

2) How did you try to convert list of strings to float numbers? you probably need to apply split first, e.g. map(lambda x: x.split(), data[0]) and then map(float, ) to each list obtained after strings splitting.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020