Floating loop. Issues with understanding for loop and split [closed]

18 hours ago 4
ARTICLE AD BOX

Function

eval_string def eval_string(s, base=2): assert type(s) is str assert 2 <= base <= 36 ### ### YOUR CODE HERE ### return int(s, base)

You should apply the function eval_string for the question related to eval_strfrac.

Question

Your task: define eval_strfrac as follows:

Suppose a string of digits s in base base contains up to one fractional point. Complete the function, eval_strfrac(s, base), so that it returns its corresponding floating-point value.

Your function should always return a value of type float, even if the input happens to correspond to an exact integer.

Examples:

eval_strfrac('3.14', base=10) ~= 3.14 eval_strfrac('100.101', base=2) == 4.625 eval_strfrac('2c', base=16) ~= 44.0 # Note: Must be a float even with an integer input!

Comment. Because of potential floating-point roundoff errors, as explained in the videos, conversions based on the general polynomial formula given previously will not be exact. The testing code will include a built-in tolerance to account for such errors.

Hint. You should be able to construct a solution that reuses the function, eval_string(), from Exercise 0.

Output

The demo should display this printed output.

eval_strfrac(3.14, 10) --> 3.14 eval_strfrac(100.101, 2) --> 4.625 eval_strfrac(2c, 16) --> 44.0 eval_strfrac(2C, 16) --> 44.0

My output (My code has issues, and I have trouble understanding)

### Solution - Exercise 1 def eval_strfrac(s, base=2): ### ### YOUR CODE HERE ### a = s.split(".") list = [] for index, value in enumerate(a): if len(a) < 2: first = eval_string(value, base) #this is for the first part. e.g. 3.14 - 3 else: first = eval_string(value, base) if index == 1: second = eval_string(value, base) result = first + second print(result) ### Demo function call demo_ex1_tuples = [('3.14', 10), ('100.101', 2), ('2c', 16), ('2C', 16)] results = [] for i, scenario in enumerate(demo_ex1_tuples): result = eval_strfrac(scenario[0], scenario[1]) print(f"eval_strfrac({demo_ex1_tuples[i][0]}, {demo_ex1_tuples[i][1]})") print(f"--> {result}") results.append(result)
Read Entire Article