Question

In Chapter 4, we developed an algorithm for converting from binary to decimal.

1.

In Chapter 4, we developed an algorithm for converting from binary to decimal. You can generalize this algorithm to work for a representation in any base. Instead of using a power of 2, this time you use a power of the base. Also, you use digits greater than 9, such as A . . . F, when they occur.

In convert.py, define a function named repToDecimal that expects two arguments, a string, and an integer. The second argument should be the base. For example, repToDecimal("10", 8) returns 8, whereas repToDecimal("10", 16) returns 16.

  • The function should use a lookup table to find the value of any digit. Make sure that this table (it is actually a dictionary) is initialized before the function is defined.

  • For its keys, use the 10 decimal digits (all strings) and the letters A . . . F (all uppercase). The value stored with each key should be the integer that the digit represents. (The letter A associates with the integer value 10, and so on.)

  • The main loop of the function should convert each digit to uppercase, look up its value in the table, and use this value in the computation.

  • Include a main function that tests the conversion function with numbers in several bases.

image.png


2.

package Newtor's method for approximating square roots (Case Study: Approximating Square Roots) 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

An example of the program input and output is shown below:

image.png

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

1.

alpha .0123456789ABCDEFGHĪJKLMNOPORSTUVWXYZ #initializing dictionary as empty 3 val 0 4 5 def repToDecimal(num, base): 6 7 #f

2.

A little background.

Newton Raphson's method states that if we have a function

f(x) = 0

and we wish to find an x that is as close to the solution as possible

and we have an initial guess xk.

Then xk+1 = xk - f(xk) / f '(xk) provides a better solution

Doing this in repetition will take us to an approximated solution.

In our case x2 = A can be written as x2 - A = 0

with f(x) = x2 - A

f '(x) = 2x

hence,  xk+1 = 0.5 * (xk + A / xk)

CODE:

#1 cheated a bit by using default arguments in the function definition #Because I wanted to make this a recursive function #B

RAW CODES:

alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

#initializing dictionary as empty

val = {}

def repToDecimal(num, base):

#following loop fills in the value for each digit

for i in range(base):

val[alpha[i]] = i

# m here is pow(base, i)

# to avoid raising to power each time

# we multiply m with base in every iteration

m = 1

res = 0

# iterate string in reverse order so that LSB is read first

for i in num[: : -1]:

#dictionary val is used to get corresponding value of current digit

d = val[i.upper()]

res += d * m

m *= base

return res

def main():

print(repToDecimal('10', 10))

print(repToDecimal('10', 8))

print(repToDecimal('10', 2))

print(repToDecimal('10', 16))

main()

2.

#I cheated a bit by using default arguments in the function definition

#Because I wanted to make this a recursive function

#But I believe these arguments are important and

#User must be allowed to change these values to see how the working changes

def newton(A, it = 0, max_iter = 100, guess = 1):

#break when done a specific number of iterations

#increase max_iter for more precise result

if it >= max_iter:

return guess

new_guess = 0.5 * (guess + A / guess)

#pass on the updated guess value to next iteration

return newton(A, it + 1, max_iter, new_guess)

def main():

while True:

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

if not a:

return

print("The program's estimate is", newton(int(a)))

print("Python's estimate is", int(a)**0.5)

main()

Add a comment
Answer #2

1.

def repToDecimal(str,base):
    result = 0
    #initializing a dictionary
    dict={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
    for i in str:
        n = dict[i]
        result = base * result + n
    return result

#calling the method and displaying the result
print(repToDecimal('10',10))
print(repToDecimal('10',8))
print(repToDecimal('10',2))
print(repToDecimal('10',16))


answered by: anonymous
Add a comment
Know the answer?
Add Answer to:
In Chapter 4, we developed an algorithm for converting from binary to decimal.
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
  • newton.py

    Package Newton’s method for approximating square roots (Case Study: Approximating Square Roots) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The program should also include a main function that allows the user to compute the square roots of inputs from the user and python's estimate of its square roots until the enter/return key is pressed.

  • 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 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...

  • Write a Python function, called counting, that takes two arguments (a string and an integer), and...

    Write a Python function, called counting, that takes two arguments (a string and an integer), and returns the number of digits in the string argument that are not the same as the integer argument. Include a main function that inputs the two values (string and integer) and outputs the result, with appropriate labelling. You are not permitted to use the Python string methods (such as count(), etc.). Sample input/output: Please enter a string of digits: 34598205 Please enter a 1-digit...

  • **DO IT AS PYTHON PLEASE** The Trifid Cipher General Problem Description The Trifid cipher (not to be confused with the...

    **DO IT AS PYTHON PLEASE** The Trifid Cipher General Problem Description The Trifid cipher (not to be confused with the creatures from the classic science-fiction film "The Day of the Triffids") is an algorithm that enciphers a plaintext message by encoding each letter as a three-digit number and then breaking up and rearranging the digits from each letter's encoded form. For this assignment, you will create a set of Python functions that can encode messages using this cipher (these functions...

  • c++ pleased Assignment 6a (15 points] - Character and String related processing... Listed below are two...

    c++ pleased Assignment 6a (15 points] - Character and String related processing... Listed below are two interesting programming challenges that will require a bit of character and/or string related processing with functions. (Carefully read the specifications for each programming challenge and select ONE.) (1) Sum of Digits in a String Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. Read the input as a C-string or a string object. The program...

  • Write a Java program to convert octal (integer) numbers into their decimal number equivalents (exactly the...

    Write a Java program to convert octal (integer) numbers into their decimal number equivalents (exactly the opposite of what you have done in Assignment 4). Make sure that you create a new Project and Java class file for this assignment. Your file should be named “Main.java”. You can read about octal-to-decimal number conversions on wikepedia Assignment 4 is at the bottom Objective Your program should prompt the user to enter a number of no greater than 8 digits. If the...

  • 3. [5 marks] Suppose T is a binary tree that stores an integer key value in...

    3. [5 marks] Suppose T is a binary tree that stores an integer key value in each node. Assume the following notation/operations on a binary tree. » the key T.key is the root node's integer key value . the left child T.left is T's left subtree, which is possibly an empty tree (or null) the right child T.right is T's right subtree, which is possibly an empty tree (or null) (a) Write an efficient algorithm FINDMAxPrODuCT(T) in pseudocode that returns...

  • We have a function F : {0, . . . , n − 1} → {0,...

    We have a function F : {0, . . . , n − 1} → {0, . . . , m − 1}. We know that, for 0 ≤ x, y ≤ n − 1, F((x + y) mod n) = (F(x) + F(y)) mod m. The only way we have for evaluating F is to use a lookup table that stores the values of F. Unfortunately, an Evil Adversary has changed the value of 1/5 of the table entries...

  • C++ language only. Thank you C++ language (cout <). NO atoi function. And please pay attention...

    C++ language only. Thank you C++ language (cout <). NO atoi function. And please pay attention to the rules at the bottom. Extra good rating to whoever can help me with this. TIA. In certain programming situations, such as getting information from web forms, via text boxes, the data coming in may need to be numerical (we want to perform arithmetic on it), but it is stored in the form of a list of characters (the numerical value stored is...

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