Home > Blockchain >  Python, function for an arithmetic sequence
Python, function for an arithmetic sequence

Time:11-25

The sequence goes like this: 1 1/2! 1/3! 1/4!...... 1/n! It's basically 1 divided by some factorial until it reaches n!

I have figured out how to calculate the factorial, example: 5! That code looks like this:

def factorial(n):
    if n == 1:
        return n
    return n * factorial(n-1) 

I've tried to google a solution but can't seem to find any :(

How would I code this?

CodePudding user response:

Using the math module:

import math

def seq(t=100):
    out = 0
    for i in range(1,t):
        out  = 1 / math.factorial(i)
    return out

CodePudding user response:

Once you have the factorial function (yours or math.factorial), the rest is almost plain English ;)

sum(1/factorial(i 1) for i in range(n))

CodePudding user response:

Well, clearly you can return the inverse factorial by just returning the inverse:

    return factorial(n-1) / n

But for a sequence, that's wasteful. Look at your sequence:

    1   1 1   1 1 1
1   -   - -   - - -   ...
    2   2 3   2 3 4

Notice that each step is just the previous step times the new value. It would be better not to have "factorial" as a separate function:

def sequence(steps):
    term = 1
    sumx = 1
    for i in range(2,steps):
        term /= i
        sumx  = term
    return sumx

CodePudding user response:

You can build a second function using recursion and the existing factorial function:

def compute_sequence(n):
    num = 1/factorial(n)
    if n == 1:
        return num
    return num   compute_sequence(n-1)

Then you would just call: compute_sequence(n)

CodePudding user response:

def factorial(n):
    if n==0:
        return 1
    else:
        return n * factorial(n-1)

def sequence(p):
    sum = 0
    while(p>0):
        fact = factorial(p)
        sum  = (1/fact)
        p -=1
    return sum

print(sequence(3))

output:

1.6666666666666665
  • Related