Looping the Fibbonacci Sequence in Python - python

I am writing a program in Python 2.7.6 that calculates the Fibonacci Sequence(1,1,2,3,5,8,etc.). This is the code(so far):
x = int(input("Enter a number: "))
y = int(input("Enter the number that comes before it:"))
z = x + y
a = z + x
b = a + z
c = b + a
d = c + b
e = d + c
f = e + d
g = f + e
print x, z, a, b, c, d, e, f, g
Is there a way I can loop the process so that I don't have to keep typing f=e+d and others?

Sure, just use some form of loop. For example, if you want to make a list of the first 11 Fibonacci numbers after x:
fiblist = [x]
for _ in range(10):
z = x + y
fiblist.append(z)
x, y = z, x
print(fiblist)
(or use a loop instead of the single print to vary the output's cosmetics -- not relevant to your core Q).
For different purposes (e.g "list all numbers in the sequence until the first one above 100") you could easily tweak the loop (e.g in lieu of the for use while x <= 100:).

You can write a loop or just use the built-in reduce function in Python.
fib = lambda n: reduce(lambda x, y: x+[x[-1]+x[-2]],range(n-2), [0, 1])

Related

How do I have a loop create a function?

I have a project for a class and I am having trouble one part. So, I have defined three variables N, p, E. I create a loop for an index value of 10 times, where I want to set x equal to the equation below. However when I execute the module the loop prints the value obtained from the equation 10 times. What I want is for the equation to be evaluated, and then have that output be the NEXT N value, rinse and repeat (I want it like a mathematical function). How do I do this?
def main():
N, p, E = eval(input("Initial, probability, average"))
for i in range(10):
x = (1 + E * p) * N
print(x)
main()
The function you want to create would look like:
def f(initial, probability, average):
return (1 + average * probability) * initial
To run this in a loop where each iteration updates the value of initial you might do:
i, p, a = map(float, input("Initial, probability, average").split())
for _ in range(10):
i = f(i, p, a)
print(i)
Since the value of N is to be updated with the x value, a while loop is used where the value is updated after each iteration.
def calculate():
N, P, E = list(map(float, input("Initial, Probability, Average").split(" ")))
i = 0
while i < 10:
x = (1 + E * P) * N
N = x
print(x)
i+=1
calculate()
Hi I believe this is what you are looking for
if not please let me know
def main():
N, p, E = eval(input("Initial : ")), eval(input("probability : ")), eval(input("average : "))
def _eval_equation(_x): return (_x + E * p) * N
x = N
for _ in range(10):
x = _eval_equation(x)
print(x)
main()

How do I write a Python code for partial fraction decomposition without using "apart"?

So I am very unexperienced with Python, I know basically nothing, and our teacher gave us the task to write a code that makes a partial fraction decomposition with this function:
I don't really know how to start or even how to define that function. I tried this at first: `
def function(x):
a = (x^4)-(3*x^2)+x+5
b = (x^11)-(3*x^10)-(x^9)+(7*x^8)-(9*x^7)+(23*x^6)-(11*x^5)-(3*x^4)-(4*x^3)-(32*x^2)-16
return a/b
But our maths script says that we need to split up the denominator and then make a system of equations out of it and solve it.
So I was thinking about defining each part of the function itself and then make a function somehow like a = 7*x and use it like f(x) = b/a^7 if this works but I don't really know. We are unfortunately not allowed to use "apart" which I think is a sympy-function?
Thank you so much in advance!
Sincerely, Phie
Addition: So after a few hours of trying I figured this. But I am very sure that this is not the way to do it. Also it tells me that variable l is not defined in z and I am sure that all the others aren't as well. I don't know what to do.
def function(x):
global a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v
a = (x^4)-(3*x^2)+x+5
b = 11
c = 10
d = 9
e = 8
f = 7
g = 6
h = 5
i = 4
j = 3
k = 2
l = x**b
m = 3*x**c
n = x**d
o = 7*x**e
p = 9*x**f
q = 23*x**g
r = 11*x**h
s = 3*x**i
t = 4*x**j
u = 32*x**k
v = 16
return a/(l-m-n+o-p+q-r-s-t-u-v)
print("We are starting the partial fraction decomposition with this
function: (x^4)-(3*x^2)+x+5 / (x^11)-(3*x^10)-(x^9)+(7*x^8)-(9*x^7)+
(23*x^6)-(11*x^5)-(3*x^4)-(4*x^3)-(32*x^2)-16")
z = l-m-n+o-p+q-r-s-t-u-v
while c >= 0:
c = c-1
z = z-l
while d >= 0:
d = d-1
z = z-m
while e >= 0:
e = e-1
z = z-n
while f >= 0:
f = f-1
z = z+o
while g >= 0:
g = g-1
z = z-p
while h >= 0:
h = h-1
z = z+q
while i >= 0:
i = i-1
z = z-r
while j >= 0:
j = j-1
z = z-s
while k >= 0:
k = k-1
z = z-t
print(z)
Since I just solved this myself, here's some input:
Let poly = function() for your function, although be careful to replace ^ with **. Include both from sympy import * and from sympy.abc import a, b, c, d, e, f, g, h, i, j, k, x.
Using factor(exp) you can find all the roots of your function, use these to define the 11 terms term_1 = a/(x-2), term_2 = b/(x2-)**2, ... , term_6 = (f*x + g)/(x**2 +1), ..., term_8 = (j*x + k)/(x**2 + 1) (you get the gist). Define your_sum = term_1 + ... + term_8, eq = Eq(your_sum, poly)
Define the variable your_sum = sum(term_1, ..., term_8), and use solve_undetermined_coeffs(eq, [a,b, ..., k], x))) to get the result.

Making 6 different random Numbers

I'm not that good at coding right now, i am trying to improve and learn. ATM i was trying to write a code that randomly picks 6 non-repeating numbers, but i fail at it. what should i do?
import random
a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)
x = random.randint(1, 100)
y = random.randint(1, 100)
z = random.randint(1, 100)
outa = b, c, x, y, z
outb = a, c, x, y, z
outc = a, b, x, y, z
outx = a, b, c, y, z
outy = a, b, c, x, z
outz = a, b, c, x, y
all = a, b, c, x, y, z
while a in outa or b in outb or c in outc or x in outx or y in outy or z in outz:
if a in outa:
a = random.randint(1,100)
elif b in outb:
b = random.randint(1,100)
elif c in outc:
c = random.randint(1,100)
elif x in outx:
x = random.randint(1,100)
elif y in outy:
y = random.randint(1,100)
elif z in outz:
z = random.randint(1,100)
print(all)
There is a function in random that does just that:
all = random.sample(range(1,101), 6)
If the list of possible values is too large to build, then your algorithm is fine, but better with a list:
all = []
while len(all) < 6:
x = random.randint(1, 10000000)
if not x in all:
all.append(x)
If your list is much bigger than 6 you can consider using a set instead of a list.
UPDATE: Actually, random.sample() is pretty smart, and with python3 this code:
all = random.sample(range(1,10000000001), 6)
works just fine, while this one:
all = random.sample(list(range(1,10000000001)), 6)
eats all my memory.
If you are with python2 you can use xrange instead of range to get the same effect.
all = a, b, c, x, y, z
Things like that creates a tuple of values. So at the time the line executes, that tuple has fixed values inside and cannot be changed. It especially does not change when you update one of the variables you originally used to construct it. So you cannot use all for the final result, or the outX tuples to check for any duplicates because they are fixed and will not update.
In order for your code to work, you would have to recreate all those tuples in every iteration of your while loop. But in general, you will quickly notice that having those explicit variables is not a good idea.
If you want to keep using randint, then you could just generate one number at a time, and “reroll” whenever you encounter a number you already have:
numbers = []
while len(numbers) < 6:
num = random.randint(1, 100)
if num not in numbers:
numbers.append(num)
I’m using a list here, which is a mutable data structure to collect multiple values (compared to the tuple, which is immutable).
You can also use random.sample here which offers an even easier way to get any number of unique values from a range of numbers:
numbers = random.sample(range(1, 100), 6)
Instead of creating 6 different variables, you could create a list that generates 6 unique numbers using random.sample:
import random
nums = random.sample(range(1,100), 6)
print (nums)
Output:
[2,34,5,61,99,3]
Like this:
random.sample(range(1,100), 6)

python generate a infinite list with certain condition

I know there is generator yield in python like:
def f(n):
x = n
while True:
yield x
x = x+1
So I try to convert this haskell function into python without using iterate: Haskell infinite recursion in list comprehension
I'm not sure how to define base case in python, also not sure how to combine if statement with this yield staff! here is what I try to do:
def orbit(x,y):
while True:
yield p (u,v)
p (u,v) = (u^2 - v^2 + x, 2 * u * v + y)
I dont see where you're getting the p from. As far as I can see you can almost literally translate it from Haskell:
def orbit(x, y):
u, v = 0, 0
while True:
u, v = u**2 − v**2 + x, 2*u*v + y
yield u, v
In their example, calling the function as orbit(1, 2), u will be bound to 1 and v to 2 in the first round, then that ((1, 2)) is yielded. In the next iteration, u = 1**2 - 2**2 + 1 = 1 - 4 + 1 = -2 and v = 2*1*2 + 2 = 6.

A function that takes two matrices as input, and returns a matrix with A * B. In Python

I am trying to figure out how to create a dot product matrix. Here is the code I have made so far:
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]
def prettyPrint(A):
for i in range(len(A)):
line = "{0: >7}".format("|"+str(A[i][0]))
for j in range(1, len(A[i])):
line = line + "{0: >7}".format(str(A[i][j]))
line = line + "|"
print(line)
#for addition of vectors
def matrixADD(A,B):
Z = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j]+B[i][j])
Z.append(row)
return Z
#for subtraction of vectors
def matrixSUB(A,B):
Z = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j]-B[i][j])
Z.append(row)
return Z
#for multiplication of vectors
def row(A,i):
Z = []
Z.extend(A[i])
return Z
def col(B,j):
Z = []
for row in B:
Z.append(row[j])
return Z
def dotProduct(x,y):
prod = 0
prod = sum(p*q for p,q in zip(x,y))
return prod
def matrixMUL(A,B):
Z = []
#Need to do.
return Z
print("\nC * D:")
prettyPrint(matrixMUL(C,D))
It's the matrixMUL(A,B) part that I am having trouble with.
The program is supposed to go through this kind of calculation:
Example:
Z = C * D =
row(C,0) • col(D,0) row(C,0) • col(D,1)
row(C,1) • col(D,0) row(C,1) • col(D,1)
row(C,2) • col(D,0) row(C,2) • col(D,1)
Z =
(4*2 + 1*5 + 9*1) (4*9 + 1*2 + 9*0)
(6*2 + 2*5 + 8*1) (6*9 + 2*2 + 8*0)
(7*2 + 3*5 + 5*1) (7*9 + 3*2 + 5*0)
Z =
22 38
30 58
34 69
and then have just this print statement:
C * D:
|22 38|
|30 58|
|34 69|
I NEED to use the other tree (or three? don't know if there is a typo or not) functions.
I've been trying this for the last three days and have looked up about everything I can think of. This is some of the code I have tried which have failed (I just comment out the stuff that went wrong):
def matrixMUL(A,B):
Z = []
Z.append(int(dotProduct(row(A,B),col(A,B))))
#if len(col(B,j)) != len(row(A,i)):
#print("Cannot multiply the two matrices. Incorrect dimensions.")
#else:
#for n in range(row(A,i)):
#for m in range(col(B,j)):
#Z.append(dotProduct(x,y))
return Z
#mult = sum(p*q for p,q in zip(x,y))
#Z.append(mult)
#Z = []
#for i in range(len(A)):
#row = []
#for j in range(len(A[0])):
#row.append(A[i][j]+B[i][j])
#Z.append(row)
#return Z
I don't know what else I can try. Can someone help?
You can do it this way:
def matrixMUL(A,B):
Z = [[0] * len(B[0]) for zz in range(len(A))]
for i in range(0,len(A)):
a = row(A,i)
for j in range(0,len(B[0])):
b = col(B,j)
Z[i][j] = sum(p*q for p,q in zip(a,b))
return Z
A difficulty that I've encountered when writing code like this is initialising the matrix correctly in the first place.
If we use code like Z = [[0] * len(B[0])] * len(A), then we end up creating a list Z that contains len(A) references to the same list of length len(B[0]) zeros. Thus, code like z[0][0] = 1 will appear to "magically" change Z[1][0] and Z[2][0] to equal 1 at the same time, because all of these refer to the same element in the same list.
By initialising the matrix Z with a list comprehension as shown above, we can be sure we have a set of unique lists referred to in Z.
Another approach that avoids the need to initialise all of Z (and thus avoids the list reference problem entirely) is:
def matrixMUL2(A,B):
Z = []
for i in range(0,len(A)):
a = row(A,i)
r = []
for j in range(0,len(B[0])):
b = col(B,j)
r.append(sum(p*q for p,q in zip(a,b)))
Z.append(r)
return Z
Neither function does as much error checking as it should (e.g. checking that the matrices have corresponding dimension sizes, as is required for multiplication), so they are not up to a good production-code standard as yet. Also, as has been suggested in comments, if numpy was available, I'd highly recommend using numpy instead of writing one's own code for this.

Categories