Question

python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a...

python 2..fundamentals of python

1.Package Newton’s method for approximating square roots (Case Study 3.6) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script should also include a main function that allows the user to compute square roots of inputs until she presses the enter/return key.

2.Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton. (Hint: The estimate of the square root should be passed as a second argument to the function.)

3.Elena complains that the recursive newton function in Project 2 includes an extra argument for the estimate. The function’s users should not have to provide this value, which is always the same, when they call this function. Modify the definition of the function so that it uses a keyword parameter with the appropriate default value for this argument, and call the function without a second argument to demonstrate that it solves this problem.

4.Restructure Newton’s method (Case Study 3.6) by decomposing it into three cooperating functions. The newton function can use either the recursive strategy of Project 1 or the iterative strategy of Case Study 3.6. The task of testing for the limit is assigned to a function named limitReached, whereas the task of computing a new approximation is assigned to a function named improveEstimate. Each function expects the relevant arguments and returns an appropriate value.

5.A list is sorted in ascending order if it is empty or each item except the last one is less than or equal to its successor. Define a predicate isSorted that expects a list as an argument and returns True if the list is sorted, or returns False otherwise. (Hint: For a list of length 2 or greater, loop through the list and compare pairs of items, from left to right, and return False if the first item in a pair is greater.)

6. Add a command to this chapter’s case study program that allows the user to view the contents of a file in the current working directory. When the command is selected, the program should display a list of filenames and a prompt for the name of the file to be viewed. Be sure to include error recovery.

7. Write a recursive function that expects a pathname as an argument. The path- name can be either the name of a file or the name of a directory. If the pathname refers to a file, its name is displayed, followed by its contents. Otherwise, if the pathname refers to a directory, the function is applied to each name in the direc- tory. Test this function in a new program.

8. Lee has discovered what he thinks is a clever recursive strategy for printing the elements in a sequence (string, tuple, or list). He reasons that he can get at the first element in a sequence using the 0 index, and he can obtain a sequence of the rest of the elements by slicing from index 1. This strategy is realized in a function that expects just the sequence as an argument. If the sequence is not empty, the first element in the sequence is printed and then a recursive call is executed. On each recursive call, the sequence argument is sliced using the range 1:. Here is Lee’s function definition:

def printAll(seq):
if seq:

print(seq[0])

printAll(seq[1:])

Write a script that tests this function and add code to trace the argument on each call. Does this function work as expected? If so, explain how it actually works, and describe any hidden costs in running it.

9. Write a program that computes and prints the average of the numbers in a text file. You should make use of two higher-order functions to simplify the design.

10. Define and test a function myRange. This function should behave like Python’s standard range function, with the required and optional arguments, but it should return a list. Do not use the range function in your implementation! (Hints: Study Python’s help on range to determine the names, positions, and what to do with your function’s parameters. Use a default value of None for the two optional parameters. If these parameters both equal None, then the function has been called with just the stop value. If just the third parameter equals None, then the function has been called with a start value as well. Thus, the first part of the func- tion’s code establishes what the values of the parameters are or should be. The rest of the code uses those values to build a list by counting up or down.)

1 0
Add a comment Improve this question Transcribed image text
Answer #1

1.

Program screenshot:

def newton (number): approx 0.5 * number better 0.5 *(approx number/approx) while better-approx: approx = better better = 0.5 * (approx + number/approx) return approx def main) while True: try: number=int (input (Enter the number [For exit: Press Enter] : print (The approximating square root:, newton (number)) )) except ValueError: break if name = main : main ()

Sample output screenshot:

Code to copy:

def newton(number):
    approx = 0.5 * number
    better = 0.5 * (approx + number/approx)
    while better != approx:
        approx = better
        better = 0.5 * (approx + number/approx)
    return approx

def main():
    while True:
        try:           
            number=int(input("Enter the number [For exit: Press Enter]: "))
            print("The approximating square root:",newton(number))
        except ValueError:
            break
       
if __name__ == '__main__':
    main()

2.

Program screenshot:

Sample output screenshot:

Code to copy:

import math

tolerance=0.00001
estimate=1.0

x = float(input("Enter a positive number:"))


# this is the Newton's function
def newton(num,estimate):
    estimate=(estimate+num/estimate)/2
    difference =abs(num-estimate**2)
    #print(estimate)
    if difference<= tolerance:
        # we are returning the value of estimate if the difference is less than the tolerance value set
        return estimate
    else:
        # we are calling the newton function passing the user input and the new estimate value,
        # we are passing the estimate value as the second argument to the function
        return newton(num,estimate)

print("The program's estimate:",newton(x, estimate))
print("Python's estimate",math.sqrt(x))

3.

Program screenshot:

Sample output screenshot:

Code to copy:

# below we are taking the default value of parameter

# estimate as 1, which means if a user passes a valid Value

# then estimate variable will get that value, else default

# value of 1 will be considered.

def newtonSquare(x, estimate=1.0):

    if abs(x-estimate ** 2) <= 0.000001:

        return estimate

    else:

        return newtonSquare(x, (estimate + x / estimate) / 2)

def main():

    while(True):

        num = input('Enter a positive number or enter/return to quit: ')

        if num.strip() == '' or num == '/return':

             break

        print()

        # note below, we are not passing estimate's value

        print('%-35s%s' % ('The Program\'s estimate is', str(newtonSquare(int(num)))))

        print('%-35s%s\n' % ('Python\'s estimate is', str(int(num)**0.5)))

main()

4.

Program screenshot:

Sample output screenshot:

Code to copy:

# below we are taking the default value of parameter
# estimate as 1, which means if a user passes a valid Value
# then estimate variable will get that value, else default
# value of 1 will be considered.
def newtonSquare(x, estimate=1.0):
    if abs(x-estimate ** 2) <= 0.000001:
        return estimate
    else:
        return newtonSquare(x, (estimate + x / estimate) / 2)

def main():
    while(True):
        num = input('Enter a positive number or enter/return to quit: ')
        if num.strip() == '' or num == '/return':
             break

        print()
        # note below, we are not passing estimate's value
        print('%-35s%s' % ('The Program\'s estimate is', str(newtonSquare(int(num)))))
        print('%-35s%s\n' % ('Python\'s estimate is', str(int(num)**0.5)))
main()

5.

Program screenshot:

Sample output screenshot:

Code to copy:

# function to test whether the list lyst is
# in ascending order or not. If it is in ascending
# order returns true otherwise returns false
def isSorted(lyst):
     # condition to check whether the length is
     # 0 or less than 2 then return true
     if len(lyst) >= 0 and len(lyst) < 2:
          return True

   
     # if the length of the list is greater than
     # or equal to 2 check whether the list is
     # in ascending order or not
     else:
          # loop through each value in the list        
          for i in range(len(lyst)-1):
             
               # check the condition of the i'th
               # position value with the (i+1)'th
               # position. If it i'th is greater
               # than the (i+1)'th position return
               # false.
               if lyst[i] > lyst[i+1]:
                    return False
             
          # if the above loop does not return
          # false, that means the list is in
          # sorted order. So return true
          return True

def main():
     lyst = []
     print(isSorted(lyst))
     lyst = [1]
     print(isSorted(lyst))   
     lyst = list(range(10))   
     print(isSorted(lyst))
     lyst[9] = 3   
     print(isSorted(lyst))

main()

6.

Program screenshot:

Sample output screenshot:

Code to copy:

import os, os.path

QUIT = '8'

COMMANDS = ('1', '2', '3', '4', '5', '6', '7', '8')

MENU = """1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a file name
7 View the contents of a file
8 Quit the program"""

def main():
    while True:
        print()
        print(os.getcwd())
        print(MENU)
        command = acceptCommand()
        runCommand(command)
        if command == QUIT:
            print("Have a nice day!")
            break

def acceptCommand():
    """Inputs and returns a legitimate command number."""
    while True:
        command = input("Enter a number: ")
        if not command in COMMANDS:
            print("Error: command not recognized")
        else:
            return command

def runCommand(command):
    """Selects and runs a command."""
    if command == '1':
        listCurrentDir(os.getcwd())
    elif command == '2':
        moveUp()
    elif command == '3':
        moveDown(os.getcwd())
    elif command == '4':
        print("The total number of files is", \
        countFiles(os.getcwd()))
    elif command == '5':
        print("The total number of bytes is", \
        countBytes(os.getcwd()))
    elif command == '6':
        target = input("Enter the search string: ")
        fileList = findFiles(target, os.getcwd())
        if not fileList:
            print("String not found")
        else:
            for f in fileList:
                print(f)
    elif command == '7':
        viewFile(os.getcwd())

def viewFile(dirName):
    lyst = list(filter(os.path.isfile, os.listdir(dirName)))
    if len(lyst) == 0:
        print("There are no files in this directory")
    else:
        while True:
            print("Files in " + dirName + ":")
            for element in lyst:
                print(element)
            fileName = input("Enter a file name from these names: ")
            if not fileName in lyst:
                print("Sorry, there is an error in your file name.")
            else:
                f = open(fileName, 'r')
                print(f.read())
            break

def listCurrentDir(dirName):
    """Prints a list of the cwd's contents."""
    lyst = os.listdir(dirName)
    for element in lyst:
        print(element)

def moveUp():
    """Moves up to the parent directory."""
    os.chdir("..")

def moveDown(currentDir):
    """Moves down to the named subdirectory if it exists."""
    newDir = input("Enter the directory name: ")
    if os.path.exists(currentDir + os.sep + newDir) and os.path.isdir(newDir):
        os.chdir(newDir)
    else:
        print("ERROR: no such name")

def countFiles(path):
    """Returns the number of files in the cwd and
    all its subdirectories."""
    count = 0
    lyst = os.listdir(path)
    for element in lyst:
        if os.path.isfile(element):
            count += 1
        else:
            os.chdir(element)
            count += countFiles(os.getcwd())
    os.chdir("..")
    return count

def countBytes(path):
    """Returns the number of bytes in the cwd and
    all its subdirectories."""
    count = 0
    lyst = os.listdir(path)
    for element in lyst:
        if os.path.isfile(element):
            count += os.path.getsize(element)
        else:
            os.chdir(element)
            count += countBytes(os.getcwd())
    os.chdir("..")
    return count

def findFiles(target, path):
    """Returns a list of the file names that contain
    the target string in the cwd and all its subdirectories."""
    files = []
    lyst = os.listdir(path)
    for element in lyst:
        if os.path.isfile(element):
            if target in element:
                files.append(path + os.sep + element)
        else:
            os.chdir(element)
            files.extend(findFiles(target, os.getcwd()))
            os.chdir("..")
    return files

if __name__ == "__main__":
    main()

7.

Program screenshot:

Code to copy:

import os
def readFile(filename):
    with open(filename, "r") as f:
        for line in f:
            print(line)
def findFile(pathname, d):
    indent = ''
    for i in range(d):
        indent = indent + ' '
    if (os.path.isdir(pathname)):
        for item in os.listdir(pathname):
            newItem = os.path.join(pathname, item)
            print(indent + newItem)
            if (os.path.isdir(newItem)):
                findFile(newItem,d+1)
    else:
        print(indent + pathname)
        readFile(pathname)

try:       
    findFile('tests\hello.txt', 0);
except FileNotFoundError:
    print("File not present in your computer.")

8.

Program screenshot:

Sample output screenshot:

Code to copy:

# function definition by lee
def printAll(seq):
    # untill the last element of parameter passed
    if seq:
        # prting first element
        print (seq[0])
        printAll(seq[1:])
       
# works for string
printAll("Hello World!")
printAll((1,2,3,4))
printAll([1,2,3,4])

9.

Program screenshot:

Code to copy:

def getAverage(l):

    total = 0

    for number in l:

        total += float(number)

    return total/len(l)

def main():

    fname = input("Enter a file name:")

    try:

        numbers = open(fname,"r").read().split()

        avg = getAverage(numbers)

        print("Average is", avg)

    except:

        print("Something went wrong")

main()

10.

Program screenshot:

Sample output screenshot:

Code to copy:

def myRange(param1, param2=None, param3=None):

   # List that holds the list values
   myList = []

   # Only one parameter is given
   if param2 == None and param3 == None:
       # Updating parameters
       start = 0;
       end = param1;
       step = 1;
   # Two parameters given
   elif param3 == None:
       # Updating parameters
       start = param1;
       end = param2;
       step = 1;
   # Three parameters given
   else:
       # Updating parameters
       start = param1;
       end = param2;
       step = param3;
     
   # Positive step count
   if step > 0:
       #Updating start value
       temp = start;
     
       # Adding elements to list
       while temp < end:
           myList.append(temp);
           temp += step;
   else:
       #Updating start value
       temp = start;
     
       # Adding elements to list
       while temp > end:
           myList.append(temp);
           temp += step;

   # return list
   return myList;

print(myRange(5))
print(myRange(5,20))

Add a comment
Know the answer?
Add Answer to:
python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a...
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
  • Restructure Newton's method (Case Study: Approximating Square Roots) by decomposing it into three...

    Restructure Newton's method (Case Study: Approximating Square Roots) by decomposing it into three cooperating functions. The newton function can use either the recursive strategy of Project 2 or the iterative strategy of the Approximating Square Roots Case Study. The task of testing for the limit is assigned to a function named limitReached, whereas the task of computing a new approximation is assigned to a function named improveEstimate. Each function expects the relevant arguments and returns an appropriate value. An example...

  • Python 3.6 Question 12 (2θ points) write a function named uniqueWords that counts how many different...

    Python 3.6 Question 12 (2θ points) write a function named uniqueWords that counts how many different words there are in each line of an input file and writes that count to a corresponding line of an output file. The input file already exists when uniqueWords is called. uniquewords creates the output file. Input. The function uniquewords takes two parameters: ◆ inFile, a string that is the name of text file that is to be read. The file that inFile refers...

  • Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from...

    Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs. txt, articles.txt, and prepositions.txt. (HINT: Define a single new function, getWords. This function should expect a filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list...

  • Roadmap To start, use the provided template file (on Blackboard): project_01_template.py. Replace the pass statements with...

    Roadmap To start, use the provided template file (on Blackboard): project_01_template.py. Replace the pass statements with your code. Notice that we included test cases under every function. If you run the project_01_template.py file at this point it should print False for each test. After you write the correct code for each function, and then run the file, it should print True for each test. 1. Write a function named gc_content that takes one argument sed and performs the following tasks:...

  • IT PYTHON QUESTION1 Consider the following Python code, where infile.txt and outfile.txt both exist in the current directory 'z' ) 。1d = open ( ' infile. txt ' , for line in o...

    IT PYTHON QUESTION1 Consider the following Python code, where infile.txt and outfile.txt both exist in the current directory 'z' ) 。1d = open ( ' infile. txt ' , for line in old: new.write (line) new.write') ne«.close () old.close) Which of the following options best describes the purpose or outcome of this code? O A copy of the file infile.txt is made (except in double line spacing) and saved as outfile.txt in the current directory. O A copy of the...

  • Assignment 2 In this assignment, you will write two short programs to solve problems using recursion....

    Assignment 2 In this assignment, you will write two short programs to solve problems using recursion. 1. Initial Setup Log in to Unix. Run the setup script for Assignment 2 by typing: setup 2 2. Towers of Hanoi Legend has it that in a temple in the Far East, priests are attempting to move a stack of disks from one peg to another. The initial stack had 64 disks threaded onto one peg and arranged from bottom to top by...

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