完成eval_strfrac(s,base),以便它返回其浮点值

时间:2019-01-15 19:18:46

标签: python-3.x string floating-point type-conversion base

我的eval_strfrac(s,base = 2)函数中的while循环出了点问题。对于3.14底数10来说非常接近,对于100.101底数2来说很远。谢谢!

#TEST to validate 
def is_valid_strfrac(s, base=2):
    return all([is_valid_strdigit(c, base) for c in s if c != '.']) \
        and (len([c for c in s if c == '.']) <= 1)

def eval_strfrac(s, base=2):
    assert is_valid_strfrac(s, base), "'{}' contains invalid digits for a base-{} number.".format(s, base)

    #
    predot,postdot = s.split('.')
    whole = eval_strint(predot,bse)
    whole = int(predot,base)
    postlist = [int(p) for p in postdot]
    print(postlist)
    i = 0
    while i <= len(postlist):
        yo = (postlist[i])*((float(base))**-(float(i + 1)))
        yo += yo
        i +=1
        return float(whole) + float(yo)


#### Test 0: `eval_strfrac_test0`#####

def check_eval_strfrac(s, v_true, base=2, tol=1e-7):
    v_you = eval_strfrac(s, base)
    assert type(v_you) is float, "Your function did not return a `float` as instructed."
    delta_v = v_you - v_true
    msg = "[{}]_{{{}}} ~= {}: You computed {}, which differs by {}.".format(s, base, v_true,
                                                                            v_you, delta_v)
    print(msg)
    assert abs(delta_v) <= tol, "Difference exceeds expected tolerance."

# Test cases from the video
check_eval_strfrac('3.14', 3.14, base=10)
check_eval_strfrac('100.101', 4.625, base=2)
check_eval_strfrac('11.0010001111', 3.1396484375, base=2)

# A hex test case
check_eval_strfrac('f.a', 15.625, base=16)

print("\n(Passed!)")

[3.14] _ {10}〜= 3.14:您计算出3.2,相差0.06000000000000005。

[100.101] _ {2}〜= 4.625:您计算出5.0,相差0.375。

1 个答案:

答案 0 :(得分:0)

在while循环中,yo = (postlist[i])*((float(base))**-(float(i + 1)))计算一位的值。然后yo += yo将其加倍。相反,您应该将数字值加到一个累加的总和中。

两行之后,return float(whole) + float(yo)从循环内部的函数返回,因此仅执行循环的一次迭代。返回应该在循环之后和循环外部(而不是循环内部的代码缩进)。