Question

In: Computer Science

Python Programming, Below included the Skeleton, input and output. Could you also include indents in the...

Python Programming, Below included the Skeleton, input and output. Could you also include indents in the solutions.

In this programming laboratory you will create a Python program that evaluates the sum of the following mathematical series:

Sum = x0 / 0! + x1 / 1! + x2 / 2! + x3 / 3! + … + xn / n!                 

The variable x is a real (float) number and the variable n is an integer that can assume values greater than or equal to 0. You program is to consist of a main program that allows the user to input values of x and n and then executes a loop with an index going from 1 to n. Your program should also include two functions, factorial and power, that calculate (respectively) factorial values and numbers to a power. The main program should call the factorial and power functions, from within the loop, to evaluate the expression for relevant values and add the value of the current term to the running sum. You may use the factorial function that was introduced in the examples in this week’s module (included in the skeleton of the program). You will need to write your own power function. The power function should compute x to the 0 power or x to positive integer powers. Do not worry about negative powers of x.

# Function to compute x to the k power

def power(x,k):

You will need to complete this function here

If x is 0 then return 0

Otherwise if n is 0 return 1

Otherwise use a loop to multiply x times itself n times and return the product

# The function below is the factorial function used in the Week Six examples

def factorial(num):

      if num < 0:

            print('Number must be >= 0')

            exit()

      else:

            fac = 1

            while num >= 1:

                 fac = fac * num

                 num = num - 1

            return fac

# Main program

sum = 0.0

x = input("Enter x value ")

x = float(x)

n = input("Enter n value ")

n = int(n)

if n < 0:

    print("n must be < 0")

    quit()

You will need to complete your main program here. It will
need to include a while loop that goes from 0 to n and calls to the factorial and power functions.

After the loop, you will need to print the sum value

Your program should produce the results shown below when executed. Multiple executions with different x and n values are displayed.

Enter x value 2

Enter n value 0

Sum is 1.0

Enter x value 2

Enter n value 1

Sum is 3.0

Enter x value 2

Enter n value 2

Sum is 5.0

Enter x value 2

Enter n value 3

Sum is 6.333333333333333

Solutions

Expert Solution

*****

Following python code will take the value of x and n as input from user .Then the value of sum is calculated as

sum += power(x, n) / factorial(n)

where power method will return the value of x^n and factorial method will return the value of n!

*****

def power(x, n):
    '''
    this method will compute x^n. If x is 0 it will return 0 , if n is 0  it will return 1
    :param x:
    :param n:
    :return:
    '''
    if x == 0:
        return 0
    if n == 0:
        return 1
    return x ** n


def factorial(num):
    '''
    this method will compute the factorial of a number
    :param num:
    :return:
    '''
    if num < 0:
        return 0
    else:
        fac = 1
        while num >= 1:
            fac = fac * num
            num = num - 1
        return fac


if __name__ == '__main__':
    '''
    this method is triggered when you run this python script. It will prompt the user to enter input values
    Then it will call power method and factorial method to compute the sum.
    Finally it will display the sum.
    '''
    sum = 0.0
    x = float(input('Enter x value'))
    n = int(input('Enter n value'))
    if n < 0:
        print("value of n must be greater than 0")
        print(f'sum = {sum}')
        exit()
    while n >= 0:
        sum += power(x, n) / factorial(n)
        n -= 1
    print(f'sum = {sum}')

For any query or modification you require in the code , comment on my answer , i will be happy to resolve any of your query.


Related Solutions

Python Programming, Could you also show the right indents in Python Shell. Below are the skeleton...
Python Programming, Could you also show the right indents in Python Shell. Below are the skeleton of the program, and the input and output. # Initialize list mylist = [ ] # Set up loop to put menu on screen num = 1 while num != 0:      print(" ")     print(" ")     print("            Menu ")      print ("0 - Quit")     print ("1 - Add item to list")     print ("2 - Pop item off list and print...
Please in C++ thank you! Please also include the screenshot of the output. I have included...
Please in C++ thank you! Please also include the screenshot of the output. I have included everything that's needed for this. Pls and thank you! Write a simple class and use it in a vector. Begin by writing a Student class. The public section has the following methods: Student::Student() Constructor. Initializes all data elements: name to empty string(s), numeric variables to 0. bool Student::ReadData(istream& in) Data input. The istream should already be open. Reads the following data, in this order:...
Python programming: Instructions: The python program should respond to user input on a command line Below...
Python programming: Instructions: The python program should respond to user input on a command line Below are the four options - if the user input is A, the program will quit -if the user input is B, the program will display the number of times the prompt has been displayed -if the user input is C, will display whatever is stored. -if the user inputs something else, it will store that user input as a string and append it to...
JAVA * This is a skeleton file. Complete the functions below. You * may also edit...
JAVA * This is a skeleton file. Complete the functions below. You * may also edit the function "main" to test your code. * * You should not use any loops or recursions. Your code needs to run in * constant time. It is OK if your testing code has loops (like in checkInvariants). * * You must not add fields or static variables. As always, you must not change * the declaration of any method nor the name of...
Python Programming I have a skeleton code here for this project but do not know exactly...
Python Programming I have a skeleton code here for this project but do not know exactly where to start. My task is to implement a reliable File Transfer Protocol (FTP) service over UDP. I need help to write the reliable FTP client and server programs based on an Alternating Bit Protocol (ABP) that will communicate with a specially designated server. In socket-level programming as well... # program description # Library imports from socket import * import sys import time #...
Writing a Modular Program in Python In this lab, you add the input and output statements...
Writing a Modular Program in Python In this lab, you add the input and output statements to a partially completed Python program. When completed, the user should be able to enter a year, a month, and a day. The program then determines if the date is valid. Valid years are those that are greater than 0, valid months include the values 1 through 12, and valid days include the values 1 through 31. Instructions Notice that variables have been declared...
In this assignment, you are going to write a Python program to demonstrate the IPO (Input-Process-Output)...
In this assignment, you are going to write a Python program to demonstrate the IPO (Input-Process-Output) cycle that is the heart of many imperative programs used for processing large amount of data. Daisy is recently hired by a warehouse. One of her job is to keep track the items ordered by all the branches of the company. The company wants to automate the task using a computer program. Being a friend of Daisy, she knows you are a Computer Science...
The input-output (consumption) matrix for a closed economy is given below. Solve the associated input- output...
The input-output (consumption) matrix for a closed economy is given below. Solve the associated input- output model. Use r if you need a variable in your answer. [0.07 0.05 0.27] [0.17 0.48 0.19] [0.76 0.47 0.54]
in python programming language, please include the proper identation This homework will allow you to demonstrate...
in python programming language, please include the proper identation This homework will allow you to demonstrate understanding and engagement with the following topics: graph representations object oriented programming graph processing,such as finding shortest paths and finding tree traversals Your task is to implement a Graph class. The edges in the graph are undirected, but you must implement an Edge class. In addition, you will have a Graph class, and a Node class. You can choose to implement graphs with any...
C programming assignment. instructions are given below and please edit this code only. also include screenshot...
C programming assignment. instructions are given below and please edit this code only. also include screenshot of the output //In this assignment, we write code to convert decimal integers into hexadecimal numbers //We pratice using arrays in this assignment #include <stdio.h> #include <stdlib.h> #include <assert.h> //convert the decimal integer d to hexadecimal, the result is stored in hex[] void dec_hex(int d, char hex[]) {    char digits[] ={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT