Question

class Leibniz:    def __init__(self):        self.total=0               def calculate_pi(self,n):       ...

class Leibniz:
   def __init__(self):
       self.total=0
          
   def calculate_pi(self,n):
       try:
           self.total, sign = 0, 1
           for i in range(n):
               term = 1 / (2 * i + 1)
               self.total += term * sign
               sign *= -1
               self.total *= 4
           return self.total
       except Exception as e:
           print("Exception occurred..")
           return 0
class Main_Calc():
   choice = "yes"
   while(choice!="no"):
       try:
           n = int(input("How many terms: "))
           Object_pi=Leibniz()
           print(Object_pi.calculate_pi(n))
           choice = input("Want to run it again (yes/no)? ")
       except:
           print("Enter the Integer")
          
if __name__=="__main__":
       Call_class=Main_Calc()

  1. Add methods which do calculations based on the pi attribute to the class which you wrote above.

  1. Modify your program module so that it demonstrates those new class methods. Be sure to correct any issues found with Homework 3
0 0
Add a comment Improve this question Transcribed image text
Answer #1
class Leibniz:
    def __init__(self):
        self.total = 0

    def calculate_pi(self, n):
        self.total, sign = 0, 1
        for i in range(n):
            term = 1 / (2 * i + 1)
            self.total += term * sign
            sign *= -1
        self.total *= 4
        return self.total


class Main_Calc:
    choice = "yes"
    while choice != "no":
        try:
            n = int(input("How many terms: "))
            Object_pi = Leibniz()
            print(Object_pi.calculate_pi(n))
            choice = input("Want to run it again (yes/no)? ")
        except:
            print("Enter the Integer")


if __name__ == "__main__":
    Call_class = Main_Calc()

Add a comment
Know the answer?
Add Answer to:
class Leibniz:    def __init__(self):        self.total=0               def calculate_pi(self,n):       ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Code Example 14-3 class Multiplier:     def __init__(self):         self.num1 = 0         self.num2 = 0     def...

    Code Example 14-3 class Multiplier:     def __init__(self):         self.num1 = 0         self.num2 = 0     def getProduct(self):         return self.num1 * self.num2 def main():     m = Multiplier()     m.num1 = 7     m.num2 = 3     print(m.num1, "X", m.num2, "=", m.getProduct()) if __name__ == "__main__":     main() Refer to Code Example 14-3: When this code is executed, what does it print to the console? a. 7 X 3 = 0 b. 3 X 7 = 0 c. 7 X 3...

  • Take the class Person. class Person: """Person class""" def __init__(self, lname, fname, addy=''): self._last_name = lname...

    Take the class Person. class Person: """Person class""" def __init__(self, lname, fname, addy=''): self._last_name = lname self._first_name = fname self._address = addy def display(self): return self._last_name + ", " + self._first_name + ":" + self._address Implement derived class Student In the constructor Add attribute major, default value 'Computer Science' Add attribute gpa, default value '0.0' Add attribute student_id, not optional Consider all private Override method display() Test your code with the following driver: # Driver my_student = Student(900111111, 'Song', 'River')...

  • Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...

    Write a class called TemperatureFile. • The class has one data attribute: __filename • Write getter and setter for the data attribute. • Write a “calculateAverage” function (signature below) to calculate and return average temperature of all temperatures in the file. def calculateAverage(self): • Handle possible exceptions Write a main function: • Create a file ('Temperatures.txt’) and then use “write” method to write temperature values on each line. • Create an object of the TemperaureFile with the filename (‘Temperatures.txt’) just...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value):...

    ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value): self.value = value self.next = None def __repr__(self): return "{}".format(self.value) def __init__(self): self.top = None def shuffle(self): card_list = 4 * [x for x in range(2, 12)] + 12 * [10] random.shuffle(card_list) self.top = None for card in card_list: new_card = self.Card(card) new_card.next = self.top self.top = new_card def __repr__(self): curr = self.top out = "" card_list = [] while curr is not None:...

  • class Population: def __init__(self, m=0, n=0, k=0): # 1 self.m = m self.n = n self.k...

    class Population: def __init__(self, m=0, n=0, k=0): # 1 self.m = m self.n = n self.k = k self.encounter = 0 bac = [] bac = bac + [1] * self.m + [2] * self.n + [3] * self.k self.bac = bac def plasmids(self): # 2 set = (self.m, self.n, self.k) return set def __str__(self): # 3 return "type I: {}, type II: {}, type III: {} (after {} encounters)".format(self.m, self.n, self.k, self.encounter) def __repr__(self): # 4 return "Population({}, {},...

  • COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

    COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild): self.value, self.lchild, self.rchild = value, lchild, rchild def __init__(self): self.treeRoot = None    #utility functions for constructTree def mask(self, s): nestLevel = 0 masked = list(s) for i in range(len(s)): if s[i]==")": nestLevel -=1 elif s[i]=="(": nestLevel += 1 if nestLevel>0 and not (s[i]=="(" and nestLevel==1): masked[i]=" " return "".join(masked) def isNumber(self, expr): mys=s.strip() if len(mys)==0 or not isinstance(mys, str): print("type mismatch error: isNumber")...

  • (python please!) [21] The following code demonstrates the concept of method class Employee: def _init__(self): def...

    (python please!) [21] The following code demonstrates the concept of method class Employee: def _init__(self): def bonus(self): return self.salary * 0.05 class Staff(Employee): def __init__(self): def bonus(self): return self.salary * 0.10

  • Consider following flower class. class Flower: def __init__(self, Fname, numberofpetals, Fprice): self.Fname = Fname self.numberofpetals =...

    Consider following flower class. class Flower: def __init__(self, Fname, numberofpetals, Fprice): self.Fname = Fname self.numberofpetals = numberofpetals self.Fprice = Fprice def getName(self): return self.Fname def getPetalsCount(self): return self.numberofpetals def getPrice(self): return self.Fprice def setName(self, Fname): self.Fname = Fname def setPetalsCount(self, numberofpetals): self.numberofpetals = numberofpetals def setPrice(self, Fprice): self.Fprice = Fprice def main(): flower f, print("name = ", flower.getName()) flower.setName("jasmine") print("name = ", flower.getName()) main() Q. What is the statement to set an object flower with rose , 4 and price...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT