Question

In: Computer Science

Question: Using this code as a starting point, restructure the solution so that each sub-task (there...

Question:

Using this code as a starting point, restructure the solution so that each sub-task (there are three) is performed in its own, separate function. When done, the function toDecimal should (1) do none of the actual "work" itself and (2) should call three separate functions in an appropriate order to complete the conversion process. This is similar to the work you did in exercise 6.4 (cengage mindtap) to restructure function newton. However, there is no recursion involved in this code.

CODE:

def toDecimal(rep, base):

    """

    Converts a number in any base from 2 to 16 to a decimal (base 10)

      equivalent value.

     

    Parameters

    ----------

    rep : string

        A string representation of an integer value in some base.

    base : integer

        An integer representing the base.

    Returns

    -------

    decimal : integer

        The base-10 value of the provided representation

    """

    # The conversion table for bases up to 16

    repTable = {'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}

   

    # Make sure that the offered string has SOME data, otherwise, return zero

    if len(rep) < 1:           

        return 0

    # The base must be between 2 and 16, inclusive, else return 0

    elif base < 2 or base > 16:

        return 0

    else:

        # The arguments are good, let's go

        decimal = 0

        exp = len(rep) - 1

        for digit in rep:

            decimal += repTable[digit] * base ** exp

            exp -= 1

        return decimal

Solutions

Expert Solution

# Explanation

# I have split toDecimal(rep,base) function into three functions : data_check(rep) , base_check(base) and  return_decimal(rep,base,repTable)

# data_check(rep) function checks if some data is present or not . If data is present it returns 1 otherwise it returns 0

# In the similar way base_check(base) function checks if base is between 2 and 16 inclusive , If yes then it returns 1 , otherwise it returns 0

# Finally return_decimal(rep,base,repTable) function is called only if we get 1 in return from both the above functions :  data_check(rep) and base_check(base) , which calculates the decimal value

# If we get 0 in return from any of the two functions : data_check(rep) and base_check(base) , decimal value will be set to 0

# Lastly we return decimal which can either be 0 or any value calculated from return_decimal(rep,base,repTable) function

#Functions

def toDecimal(rep, base):
  
# The conversion table for bases up to 16

repTable = {'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}

valid_data = data_check(rep)

valid_base = base_check(base)

if valid_base == 1 and valid_data == 1:
decimal = return_decimal(rep,base,repTable)
else:
decimal = 0

return decimal

#To check if data is present or not

def data_check(rep):
if len(rep) < 1:   
return 0
else:
return 1

# To check for valid base , should be between 2 and 16 inclusive

def base_check(base):
if base < 2 or base > 16:
return 0
else:
return 1

# To calculate the decimal value

def return_decimal(rep,base,repTable):
decimal = 0
exp = len(rep) - 1
for digit in rep:
decimal += repTable[digit] * base ** exp
exp -= 1
return decimal


Related Solutions

Write a code using c# Maximum Sub Array.
Write a code using c# Maximum Sub Array.
Its a single question so need full answer for each sub part. the overall answer should...
Its a single question so need full answer for each sub part. the overall answer should be between 200 and 300 words. Upvote will be given for correct answer. 1. Summarise the effect of a tariff and the effect of a quota based on the following questions: i) Does the importing country gain or lose overall from implementing a tariff or a quota? ii) Do the following groups in the importing country gain or lose from a tariff or a...
Answer the following four sub-questions. Each sub-question is independent and has no no link with the...
Answer the following four sub-questions. Each sub-question is independent and has no no link with the other sub questions. a) Two neutral spheres are spaced 3 m apart. Calculate how many electrons must be transferred from one sphere to another so that they each experience a force of 14 N, and say whether the forces will be attractive or repulsive. b) Calculate the uniform electric field to be applied parallel to a moving proton at 2⋅106 m / s in...
Using the chart below showing the age and salary of each NBA Starting Point Guard, Let...
Using the chart below showing the age and salary of each NBA Starting Point Guard, Let x = age and y = salary 1. Is there a correlation between the two variables? Explain. 2. Find the equation of the regression line THEN use it to predict the salary of a 42-year-old point guard. Age Salary 30 41358814 31 40231758 29 39200000 22 33930000 23 33930000 31 30521115 29 27977689 29 26361000 33 17000450 29 16000000 27 14000000 28 42782880 34...
Sub HW4_1_1() 'a. Using the properties window in the VB editor assign ' the code name...
Sub HW4_1_1() 'a. Using the properties window in the VB editor assign ' the code name wsEx2 to the sheet with tab name Sheet1. 'b. Using VBA code and the code name for worksheet Sheet1, ' make this worksheet the active sheet. 'c. Declare a range variable and assign to this variable ' the range from A2 to A10 in the worksheet Sheet1. 'd. Write VBA code to create a range name and call it “Scores”. ' This range name...
Titration: Calculate the pH of each solution listed below. You are starting with a solution of...
Titration: Calculate the pH of each solution listed below. You are starting with a solution of NaClO and titrating that solution with HCl. A) What is the pH of 25.0 mL of 0.035 M NaClO? The Kb of ClO- is 2.86 x 10-7? B) What is the pH when you add 12.5mL of 0.035M HCl? C) What is the pH when you add 25.0 mL of 0.035 M HCl?
Hi, I would like the numerical solution for this task so I can be able to...
Hi, I would like the numerical solution for this task so I can be able to model it in a kinetic modeling programme like Berkely Madonna (BM). This was the reason why I started my membership with Chegg Study but unfortunately, the solution to this problem was not available. I'm looking forward to hearing from you. you will find the task in de link below. With kind regards, Ahmed https://www.chegg.com/homework-help/comprehensive-problem-multiple-reactions-heat-effects-styren-chapter-12-problem-24qp-solution-9780132317160-exc in J.Snyder en B.Subramaniam, Chem. Eng. Sci., 49, 5585 (1994)....
Requirements: Code in C++. With given information, write the solution to this problem so that it...
Requirements: Code in C++. With given information, write the solution to this problem so that it is understandable to someone with basic knowledge of C++ (ex: only keep basic libraries, keep coding shortcuts to a minimum). Also leave comments in the code (plz), the logic behind solving this problem if possible, and explanation of what the keys to solving this problem is and how to run test cases to ensure correctness of code. Problem: For this problem you will compute...
Your task is to take the below code, and insert comments (using the “%” symbol) next...
Your task is to take the below code, and insert comments (using the “%” symbol) next to each line of code to make sure that you know what every line does. clc clear close all NMax = 100; partialSum = 0; exactAnswer = pi^2; for k=1:NMax partialSum = partialSum + 6/k^2; percentDiff(k) = abs(partialSum - exactAnswer)/exactAnswer*100; end NVector = [1:NMax]; plot(NVector,percentDiff); xlabel('{{Noob}}'); ylabel('% Difference');
Your task is to take the above code, and insert comments (using the “%” symbol) next...
Your task is to take the above code, and insert comments (using the “%” symbol) next to each line of code to make sure that you know what every line does. close all; clear all; clc; thetaAB = 0; angleIncrement = 0.1; numOfLoops = 360/angleIncrement; thetaABVector = [angleIncrement:angleIncrement:360]; rAB = 5; rBC = 8; for i=1:numOfLoops bothResults = SliderCrankPosn(rAB,rBC,thetaAB); rAC(i) = bothResults(1); thetaBC(i) = bothResults(2); thetaAB = thetaAB+angleIncrement; end subplot(2,1,1) plot(thetaABVector,thetaBC,'Linewidth',3); xlabel('\theta_{AB} [degrees]'); ylabel('\theta_{BC} [degrees]'); xlim([0 360]); ylim([300 400]); grid...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT