• + 0 comments

    Even not strictly necessary for this challenge, i got back to theory and implentation of least square regression, as this method opens solutions for a lot of problems, including this one.

    I super recommned this book: https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter16.04-Least-Squares-Regression-in-Python.html

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    import pandas as pd
    import numpy as np
    from scipy import optimize
    from io import StringIO
    
    
    if __name__ == '__main__':
        timeCharged = float(input().strip())
        
        # Read the data using pandas
        data = pd.read_csv('trainingdata.txt', header=None, names=["TimeCharged", "TimeLasted"])
    
        # training data: Range when not fully charge range
        index_values = data.query("TimeCharged <= 4.01").index.tolist()
        x = data.TimeCharged[index_values]
        y = data.TimeLasted[index_values]
       
        # create basis functions for least square regression 
        def basis_func_lin (x, b1):
            return b1 * pow(x,1)
            
        # or
        def basis_func_quad (x, b1, b2):
            return b1 * pow(x,1) + b2 * pow(x,2)
    
        #choose func
        func = basis_func_lin
        
        # do training (least square regression)
        beta_params, covariance = optimize.curve_fit(func, x, y)
        
       # Make prediction
        if timeCharged > 4.01:  # Battery fully charged
            print(8)  
        else:
            predicted_time = func(timeCharged, *beta_params)
            print(predicted_time)  # Output the predicted battery life