Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a table in Python 3(beginner)

So I just started learning Python 3 in school, and we had to make a function that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.

We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of a computed with the first function; the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.

I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.

def mysqrt(a):
    for x in range(1,int(1./2*a)):
        while True:
            y = (x + a/x) / 2
            if y == x:
                break
            x = y
    print(x)
print(mysqrt(16))
like image 204
Fruitdruif Avatar asked May 10 '17 09:05

Fruitdruif


People also ask

Can we create table in Python?

PrettyTable class inside the prettytable library is used to create relational tables in Python. It can be installed using the below command.


1 Answers

If you're allowed to use libraries

from tabulate import tabulate
from math import sqrt


def mysqrt(a):
    for x in range(1, int(1 / 2 * a)):
        while True:
            y = (x + a / x) / 2
            ifjl y == x:
                break
            x = y
    return x


results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))

Outputs

  num    mysqrt     sqrt
-----  --------  -------
   10   3.16228  3.16228
   11   3.31662  3.31662
   12   3.4641   3.4641
   13   3.60555  3.60555
   14   3.74166  3.74166
   15   3.87298  3.87298
   16   4        4
   17   4.12311  4.12311
   18   4.24264  4.24264
   19   4.3589   4.3589

Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data

like image 138
Jack Evans Avatar answered Sep 20 '22 16:09

Jack Evans