-3

I'm trying to write sequences below, but it doesn't work. Could you please help me.

sequences

import math
def un(n_terms):
  def vn(n_terms):
    p = 0
    sum_un = 0
    while n_terms>=1:
      while p<=n_terms:
        sum_un = sum_un + (1//math.factorial(p))
        p = p + 1
    un(n_terms) = sum_un
    vn(n_terms) = un(n_terms) + (1//(n_terms * math.factorial(n_terms)))
  print(vn(10))
print(un(10))
JohanC
  • 71,591
  • 8
  • 33
  • 66
  • 2
    Welcome to Stack Overflow. Please read the guide on how to ask questions. Please also try to provide examples of what you have tried and what errors you are getting. – Julian Chan Dec 27 '19 at 09:47
  • What is your error message ? I feel like it can come from the `un(n_terms) = sum_un` line, it looks like you are trying do assign something to a function call – Plopp Dec 27 '19 at 09:58
  • yes un(n_terms) = sum_un SyntaxError: can't assign to function call – thecarefulone Dec 27 '19 at 09:59
  • @Plopp im beginner, that's why i have a lil bit confuses, why can i use instead? – thecarefulone Dec 27 '19 at 10:00

1 Answers1

0

You could simplify your functions like this:

import math

def u(n):
    return sum(1/math.factorial(p) for p in range(n+1))

def v(n):
    return u(n) + 1/(n * math.factorial(n))

And then you can use them like this:

print(u(10)) # 2.7182818011463845
print(v(10)) # 2.7182818287037036
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
  • and in order to get float results i added (float) to denominators and it worked! is it proper way? – thecarefulone Dec 27 '19 at 10:16
  • @thecarefulone That depends on the Python version you are using. With version >3 my code does work. Maybe you are still using version 2? – Riccardo Bucco Dec 27 '19 at 10:17
  • I did actually since im new it's written "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score." – thecarefulone Dec 27 '19 at 10:18
  • im using 2.7.15, results of your code were integer (2), then i added (float), it showed float numbers as 2.718... – thecarefulone Dec 27 '19 at 10:19
  • @thecarefulone ok then using `float` makes sense. Check this question for more details https://stackoverflow.com/questions/21316968/division-in-python-2-7-and-3-3 – Riccardo Bucco Dec 27 '19 at 10:21
  • I got! Thank you very much for your help again, bless your heart – thecarefulone Dec 27 '19 at 10:24