Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | Python3 program for above approach ; Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Driver Code ; Given N ; Given arr [ ] ; Function calling
import sys NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE raised = 1 / ( n - 1 ) NEW_LINE temp = pow ( arr [ n - 1 ] , raised ) NEW_LINE r = round ( temp ) + 1 NEW_LINE min_cost = sys . maxsize NEW_LINE common_ratio = 1 NEW_LINE for j in range ( 1 , r + 1 ) : NEW_LINE INDENT curr_cost = 0 NEW_LINE prod = 1 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT curr_cost += abs ( arr [ i ] - prod ) NEW_LINE prod *= j NEW_LINE if ( curr_cost >= min_cost ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT min_cost = min ( min_cost , curr_cost ) NEW_LINE common_ratio = j NEW_LINE DEDENT DEDENT print ( min_cost , common_ratio ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 1 , 11 , 4 , 27 , 15 , 33 ] NEW_LINE minCost ( arr , N ) NEW_LINE DEDENT