How do i print a table in python? - python

I am trying to print the output of the following code in two columns using the python launcher:
def main():
print "This program illustrates a chaotic function"
n = input("How many numbers should I print? ")
x = input("Enter a numbers between 0 and 1: ")
y = input("Enter another number between 0 and 1: ")
for i in range(n):
x = 2.0 * x * (1 - x)
print #??
for i in range(n):
y = 2.0 * y * (1 - y)
print #??
main()

for x, y in listOfTwotuples:
print x, y
Given that you've provided no details I've gone ahead and assumed that you've got a list of two-tuples. Update your question with more info and I'll update my answer to match!
edit: with actual details now
If in each loop you store the numbers in a list, you can then use zip to get the format needed to use my code snippet above.
So after reading the input in (be careful with input by the way, using raw_input is better, google why):
xs = []
ys = []
for i in range(n):
xs.append(2.0 * x * (1 - x))
for i in range(n):
ys.append(2.0 * y * (1 - y))
Then you can use zip to apply my code snippet above:
for x, y in zip(xs, ys):
print x, y
zip takes one list [0, 1, 2, ...] and another [10, 20, 30, ...] to produce a list of tuples with these lists [(0, 10), (1, 20), (2, 30), ...].

>>>print "a table in python? using two columns"
a table in python? using two columns
;-)

Check out the format string syntax which will help you to pad strings with spaces to get columns.

If all you want is an x and a y value on each line, then once the preliminaries are done, you can say:
for i in range(n):
x = 2 * x * (1 - x)
y = 2 * y * (1 - y)
print x,y

Related

Trying to get multiple values from a multiplication using a list with python

I am trying to include a list (with the use of a range) within a multiplication to get multiple values back:
say I have z = range(0, 26, 5)
how do I include this range into the formula:
t = (z * 4) + z
to then get back five different values? (i.e for every value of z)
You can use a for-loop over the range within square-brackets, which will get you a list. This is called a list comprehension.
t = [(x * 4) + x for x in z]
Isn't that the same as? :
t = [(x * 5) for x in z]

python How to convert the input value into a mathematical function

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2
You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!
You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

More information on output array with equation and indicies

I have a math function whose output is defined by two variables, x and y.
The function is e^(x^3 + y^2).
I want to calculate every possible integer combination between 1 and some defined integer for x and y, and place them in an array so that each output is aligned with the cooresponding x value and y value index. So something like:
given:
x = 3
y = 5
output would be an array like this:
f(1,1) f(1,2) f(1,3)
f(2,1) f(2,2) f(2,3)
f(3,1) f(3,2) f(3,3)
f(4,1) f(4,2) f(4,3)
f(5,1) f(5,2) f(5,3)
I feel like this is an easy problem to tackle but I have limited knowledge. The code that follows is the best description.
import math
import numpy as np
equation = math.exp(x**3 + y**2)
#start at 1, not zero
i = 1
j = 1
#i want an array output
output = []
#function
def shape_f (i,j):
shape = []
output.append(shape)
while i < x + 1:
while j < y +1:
return math.exp(i**3 + j**2)
#increase counter
i = i +1
j = j +1
print output
I've gotten a blank array recently but I have also gotten one value (int instead of an array)
I am not sure if you have an indentation error, but it looks like you never do anything with the output of the function shape_f. You should define your equation as a function, rather than expression assignment. Then you can make a function that populates a list of lists as you describes.
import math
def equation(x, y):
return math.exp(x**3 + y**2)
def make_matrix(x_max, y_max, x_min=1, y_min=1):
out = []
for i in range(x_min, x_max+1):
row = []
for j in range(y_min, y_max+1):
row.append(equation(i, j))
out.append(row)
return out
matrix = make_matrix(3, 3)
matrix
# returns:
[[7.38905609893065, 148.4131591025766, 22026.465794806718],
[8103.083927575384, 162754.79141900392, 24154952.7535753],
[1446257064291.475, 29048849665247.426, 4311231547115195.0]]
We can do this very simply with numpy.
First, we use np.arange to generate a range of values from 0 (to simplify indexing) to a maximum value for both x and y. We can perform exponentiation, in a vectorised manner, to get the values of x^3 and y^2.
Next, we can apply np.add on the outer product of x^3 and y^3 to get every possible combination thereof. The final step is taking the natural exponential of the result:
x_max = 3
y_max = 5
x = np.arange(x_max + 1) ** 3
y = np.arange(y_max + 1) ** 2
result = np.e ** np.add.outer(x, y)
print(result[2, 3]) # e^(2 ** 3 + 3 ** 2)
Output:
24154952.753575277
A trivial solution would be to use the broadcasting feature of numpy with the exp function:
x = 3
y = 5
i = np.arange(y).reshape(-1, 1) + 1
j = np.arange(x).reshape(1, -1) + 1
result = np.exp(j**3 + y**2)
The reshape operations make i into a column with y elements and j into a row with x elements. Exponentiation does not change those shapes. Broadcasting happens when you add the two arrays together. The unit dimensions in one array get expanded to the corresponding dimension in the other. The result is a y-by-x matrix.

behaviour of reduce function in python

I am confused by the behavior of the reduce function.
In the first example, I get the expected result: (1-1/2) * (1-1/3) = 1/3
>>> reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y), [2,3])
0.33333333333333337
In the second example, I do not get the expected result: (1-1/2) * (1-1/3) * (1-1/5) = 0.2666666
>>> reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y), [2,3,5])
-1.5999999999999996
Can someone please explain me what I am missing?
What you need is a map and reduce:
>>> from functools import reduce
>>> yourlist = [2, 3]
>>> reduce(lambda x, y: x*y, map(lambda x: (1-1/x), yourlist))
0.33333333333333337
>>> yourlist = [2, 3, 5]
>>> reduce(lambda x, y: x*y, map(lambda x: (1-1/x), yourlist))
0.2666666666666667
Because map converts each item to the (1-1/item) and then the reduce multiplies all of them.
Additional remarks:
Instead of the lambda x, y: x * y you could also use the faster operator.mul, for example:
>>> import operator
>>> yourlist = [2, 3, 5]
>>> reduce(operator.mul, map(lambda x: (1-1/x), yourlist))
0.2666666666666667
Thanks #acushner for pointing this out (in the comments).
What went wrong in your function
In this case it's actually quite easy to see what doesn't work, just use a named function and add some prints:
def myfunc(x, y):
print('x = {}'.format(x))
print('y = {}'.format(y))
res = (1 - 1.0/x) * (1 - 1.0/y)
print('res = {}'.format(res))
return res
reduce(myfunc, [2, 3])
# x = 2
# y = 3
# res = 0.33333333333333337
reduce(myfunc, [2, 3, 5])
# x = 2
# y = 3
# res = 0.33333333333333337
# x = 0.33333333333333337
# y = 5
# res = -1.5999999999999996
So it uses the last result as "next" x value. That's why it worked for the length-2-list case but for more elements it simply doesn't apply the formula you want.
Alternative
Instead of using map and reduce you could also use a simple for-loop. It's much easier to get them right and most of the times they are more readable (and in some cases it's faster than reduce).
prod = 1
for item in yourlist:
prod *= 1 - 1 / item
print(prod)
Yes, instead of 1 line it's now 4 lines long but it's easy to understand what is happening (but there might be some edge cases in which that doesn't behave like reduce, for example for empty inputs).
But I generally prefer simple loops over complicated reduce-operations but as always YMMV. :)
EDIT: I approve map/reduce answer above.
To understand why, read this:
https://docs.python.org/2/library/functions.html#reduce
Reduce recursively calls your function on each element of your list with 2 arguments: an accumulator (value of last call) and current element.
So you get:
(1 - 1.0/( (1 - 1.0/2) * (1 - 1.0/3) )) * (1 - 1.0/5)
With:
reduce(lambda acc, x: (1 - 1.0/acc) * (1 - 1.0/x), [2,3,5])
>>-1.5999999999999996
To add to why you get -1.5999999999999996 as your result and for completeness we can compute it using https://docs.python.org/2/library/functions.html#reduce as our guide:
The first iteration will be (which takes our first 2 iterator values of 2 and 3 as x and y):
(1 - 1.0 / 2) * (1 - 1.0 / 3)
which becomes:
0.5 * 0.6666666666666667
which yields:
0.33333333333333337.
We then use 0.33333333333333337 to move on to our next iteration which takes this result as x and our next iteration number of 5 as y:
Therefore, our second iteration will be:
(1 - 1.0 / 0.33333333333333337) * (1 - 1.0/5)
which becomes:
-1.9999999999999996 * 0.8
which yields:
-1.5999999999999996
In your second example you have 3 inputs. You need:
reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y)* (1 - 1.0/z),...

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))
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
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"]

Categories