Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from numpy.linalg import inv
- import sys
- import math
- #Gets a valid input an returns it as a list of tuples
- def get_input():
- #The message that wil be displayed to the inputter
- print('Type \'exit\' to exit')
- input_message = 'Write you coordinates: '
- #The characters of the input to be replaced, and the characters they should be replaced with
- replace_chars = [(' ', ''), ('(', ''), (')', ' '), (',', ' ')]
- #Repeatedly gets the input, until it is valid
- while True:
- s = input(input_message)
- if (s.lower() == 'exit'):
- sys.exit()
- #Replaces the replace_chars with nothing (deletes them)
- for char_pair in replace_chars:
- s = s.replace(char_pair[0], char_pair[1])
- #Replaces the ',' that split the coordinates, with a space
- s = s.replace(',', ' ')
- #Splits the string into words
- s_list = s.split()
- #Is the input valid?
- is_valid = validate_if_float(s_list) and (len(s_list) % 2 == 0)
- #If yes, the function should return the input
- if (is_valid):
- #Initializes the result list
- result = []
- #Loops through the input list, with iterates of two
- for i in range(0, len(s_list), 2):
- #Appends a touple of the coordinate pair to the result list
- result.append((float(s_list[i]), float(s_list[i + 1])))
- return result
- input_message = 'That input is invalid. Try again: '
- #Validates if string every entry of a list can be converted to a float
- def validate_if_float(number_list):
- is_all_numbers = True
- for n in number_list:
- if not is_number(n):
- is_all_numbers = False
- break
- return is_all_numbers
- def is_number(s):
- try:
- float(s)
- return True
- except ValueError:
- return False
- def create_matrix (coordinates):
- matrix_list = []
- for i in range(len(coordinates)):
- matrix_list.append(list())
- for j in range(len(coordinates)):
- num = math.pow(coordinates[i][0], j)
- matrix_list[i].append(num)
- return np.matrix(matrix_list)
- def create_vector (coordinates):
- vector_list = []
- for i in range(len(coordinates)):
- vector_list.append([coordinates[i][1]])
- return np.matrix(vector_list)
- def calculate_coefficients (A, b):
- v = inv(A) * b
- return v
- def main ():
- coordinates = get_input()
- A = create_matrix(coordinates)
- b = create_vector(coordinates)
- v = calculate_coefficients (A, b)
- formula = 'f(x) = '
- for i in range(len(v)):
- formula = formula + str(float(v[i][0])) + ' * x^' + str(i) + ' + '
- formula = formula[:len(formula)-3]
- print(formula)
- input()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement