Appearance
question:Optimize this code in Python to reduce the time complexity from O(n^2) to O(nlogn). def maximum_two(arr): m1 = m2 = float('inf') for n in arr: if n > m2: if n > m1: m1, m2 = n, m1 else: m2 = n return (m1, m2)
answer:def maximum_two(arr): arr.sort(reverse=True) m1 = arr[0] m2 = arr[1] return (m1, m2)
question:Generate a new Python program to be able to classify a list of emails.
answer:def classify_email(email_list): classified_list = [] for email in email_list: if '@' in email: classified_list.append('Valid') else: classified_list.append('Invalid') return classified_list
question:Create a machine learning program using Python to predict values from a linear regression model.
answer:import pandas as pd import numpy as np import matplotlib.pyplot as plt # Generate some random data x = np.random.randint(0,100,20) y = np.random.randint(0,100,20) # Plotting the points plt.plot(x, y, "ro") # Generating the linear regression model #X = X1.reshape(-1, 1) X = np.array(x).reshape(-1, 1) # Create linear regression object from sklearn.linear_model import LinearRegression reg = LinearRegression() #Train the model using the data reg = reg.fit(X, y) #Calculate the coefficient print("Coefficient: ", reg.coef_[0]) #Prediction predicted = reg.predict(np.array(x).reshape(-1, 1)) print("Predicted Values: ", predicted)
question:Create a python data structure that stores the following three values: apple: 0, orange: 25, and banana: 52.
answer:numbers = {"apple": 0, "orange": 25, "banana": 52}