class Program:
    def __init__(self):
        # Placeholder messages; user will fill these in.
        self.messages = {
            1: """import pandas as pd
                col_list=["id","first","last","gender","marks","selected"]
                import pandas as pd
                df=pd.read_csv("/content/dataset exp1.csv")
                print(df)
                mean1=df['physics'].mean()
                sum1=df['physics'].sum()
                max1=df['physics'].max()
                min1=df['physics'].min()
                count1=df['physics'].count()
                median1=df['physics'].median()
                sd1=df['physics'].std()
                var1=df['physics'].var()
                print("Mean Marks \n"+str(mean1))
                print("Sum of the marks \n"+str(sum1))
                print("Maximum of marks \n"+str(max1))
                print("Minimum of marks \n"+str(min1))
                print("count of marks \n"+str(count1))
                print("Standard deviation of marks \n"+str(sd1))
                print("variance of marks \n"+str(var1))
                print("End of summary\n\n\n")
                import pandas as pd
                col_list=["id","first","last","gender","marks","selected"]
                df=pd.read_csv("/content/dataset2 e1.csv",usecols=col_list)
                print(df)
                print(df.shape)
                print(df.head(5))
                print(df.describe())
                import pandas as pd
                from matplotlib import pyplot as plt
                col_list=["id","name","gender","physics","chemistry","maths","biology","language","selected"]
                df=pd.read_csv("/content/dataset exp1.csv",usecols=col_list)
                print(df)
                marks1=df['physics'].values.tolist()
                marks_scored=df['physics'].hist()
                plt.title("Histogram for physics marks")
                plt.xlabel("physics marks")
                plt.ylabel("Frequency of physics marks")
                che1=df['chemistry'].values.tolist()
                print(che1)
                plt.scatter(che1,marks1,alpha=1)
                plt.title("Scatter plot chemistry vs physics")
                plt.xlabel("chemistry marks")
                plt.ylabel("physics marks")
                plt.show()
                df.plot.box(title="Box and Whisker plot of Marks",grid=False);
                plt.show()
                sums=df.selected.groupby(df.gender).sum()
                plt.pie(sums,labels=sums.index);
                plt.show()
                import pandas as pd
                col_list=["id","first","last","gender","marks","selected"]
                df=pd.read_csv("/content/dataset exp2.csv",usecols=col_list)
                print(df)
                print("End of listing\n\n\n")
                from sklearn.preprocessing import LabelEncoder
                df_gender_encode=LabelEncoder()
                df.gender=df_gender_encode.fit_transform(df.gender)
                print(df)
                print("End of listing\n\n\n")""",
            2: """from sklearn import preprocessing
                    df.marks=preprocessing.scale(df.marks)
                    scaled_df=preprocessing.scale(df.marks)
                    print(df)
                    print("Scaling of marks is completed\n\n\n")
                    newarr=scaled_df.reshape(-1,1)
                    scaled_df_bin=preprocessing.Binarizer(threshold=0.5).transform(newarr)
                    df['marks']=scaled_df_bin
                    print(df)
                    print("Binarizarion of marks is completed\n\n\n\n");
                    import pandas as pd
                    col_list=["id","first","last","gender","marks","selected"]
                    df=pd.read_csv("/content/dataset.csv",usecols=col_list)
                    print(df)
                    print("End of listing\n\n\n")
                    df_duplicated=pd.concat([df]*2,ignore_index=True)
                    print(df_duplicated)
                    print("Display before duplication\n\n\n\n")
                    df_duplicates_removed=pd.DataFrame.drop_duplicates(df_duplicated)
                    print(df_duplicates_removed)
                    print("Display after duplication\n\n\n\n")
                    import pandas as pd
                    df=pd.DataFrame({
                        'm1':[50,'A',60,'A',80],
                        'm2':[60,'A','60','A',80],
                        'm3':[50,70,'A','A',60],
                        'm4':[60,'A','A','A',60],
                        'm5':['A','A','A',10,20]

                    })
                    df=df.apply(pd.to_numeric,errors='coerce')
                    print(df)
                    print("Dataframe with NaN\n\n\n")
                    df['m5']=df['m5'].fillna(0)
                    print(df)
                    print("Making m5 NaN as 0 using fillna() function\n\n\n\n")
                    df1=df.copy()
                    df1['m2'].fillna(df1['m2'].mean(),inplace=True)
                    print(df1)
                    print('Making m5 NaN as mean using fillna() function\n\n\n\n')
                    df2=df.copy()
                    df1['m3'].fillna(df1['m2'].median(),inplace=True)
                    print(df2)
                    print('Making m5 NaN as median using fillna() function\n\n\n\n')
                    df=df.dropna(axis=1)
                    print(df)
                    print("Droping all columns having NaN\n\n\n\n")""",
            3: """ import numpy as np
                import matplotlib.pyplot as plt
                from sklearn.decomposition import PCA, TruncatedSVD
                from sklearn.datasets import load_iris
                from sklearn.preprocessing import StandardScaler
                iris = load_iris()
                X = iris.data
                y = iris.target
                feature_names = iris.feature_names

                print(f"Original data shape: {X.shape}")
                print(f"Feature names: {feature_names}")
                scaler = StandardScaler()
                X_scaled = scaler.fit_transform(X)
                print("\n--- PCA (Principal Component Analysis) ---")
                pca = PCA(n_components=2)
                X_pca = pca.fit_transform(X_scaled)
                print(f"PCA reduced data shape: {X_pca.shape}")
                print(f"Explained variance ratio by principal components: {pca.explained_variance_ratio_}")
                print(f"Cumulative explained variance: {np.sum(pca.explained_variance_ratio_)}")
                plt.figure(figsize=(8, 6))
                scatter = plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', edgecolor='k', s=50)
                plt.xlabel('Principal Component 1')
                plt.ylabel('Principal Component 2')
                plt.title('PCA of Iris Dataset (2 Components)')
                plt.colorbar(scatter, label='Species')
                plt.grid(True)
                plt.show()
                print("\n--- Truncated SVD (Singular Value Decomposition) ---")
                svd = TruncatedSVD(n_components=2)
                X_svd = svd.fit_transform(X_scaled)

                print(f"SVD reduced data shape: {X_svd.shape}")
                print(f"Explained variance ratio by SVD components: {svd.explained_variance_ratio_}")
                print(f"Cumulative explained variance: {np.sum(svd.explained_variance_ratio_)}")
                plt.figure(figsize=(8, 6))
                scatter = plt.scatter(X_svd[:, 0], X_svd[:, 1], c=y, cmap='viridis', edgecolor='k', s=50)
                plt.xlabel('Singular Component 1')
                plt.ylabel('Singular Component 2')
                plt.title('Truncated SVD of Iris Dataset (2 Components)')
                plt.colorbar(scatter, label='Species')
                plt.grid(True)
                plt.show()
                print("\n --- Comparison ---\n")
                print("PCA is essentially a specialized case of SVD applied to the covariance matrix.")
                print("For dense data, the results of PCA and SVD (specifically, `TruncatedSVD` on centered data) are often very similar.")
                print("PCA works by finding orthogonal components that explain the maximum variance in the data.")
                print("SVD decomposes a matrix into three other matrices, revealing latent factors.")
                print("Truncated SVD is particularly useful for sparse matrices (e.g., in natural language processing for topic modeling).")""",
            4: """from sklearn.model_selection import train_test_split
                    from sklearn.neighbors import KNeighborsClassifier
                    from sklearn.metrics import classification_report, confusion_matrix
                    from sklearn.preprocessing import StandardScaler
                    import pandas as pd
                    dataset = pd.read_csv("/content/sample-4 ex4.csv")
                    print(dataset.shape)
                    print(dataset.head())
                    print(dataset.tail(2))
                    X = dataset.iloc[:, :-1].values
                    y = dataset.iloc[:, 3].values
                    print(X)
                    print(y)
                    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
                    scaler = StandardScaler()
                    scaler.fit(X_train)
                    X_train = scaler.transform(X_train)
                    X_test = scaler.transform(X_test)
                    classifier = KNeighborsClassifier(n_neighbors=3)
                    classifier.fit(X_train, y_train)
                    y_pred = classifier.predict(X_test)

                    print(confusion_matrix(y_test, y_pred))
                    print(classification_report(y_test, y_pred))
                    sample = [[9.1, 85, 8.0, 5.5]]
                    sample_scaled = scaler.transform(sample)
                    predicted = classifier.predict(sample_scaled)
                    print(predicted)""",
            5: """import matplotlib.pyplot as plt
                    import pandas as pd
                    from sklearn.linear_model import LinearRegression
                    from sklearn import linear_model

                    salesdata = {'week': [1,2,3,4,5],
                    'sales': [1.2,1.8,2.6,3.2,3.8]
                    }

                    df = pd.DataFrame(salesdata,columns=['week','sales'])

                    plt.scatter(df['week'], df['sales'], color='green')
                    plt.title('Regression among week and sales')
                    plt.xlabel('X - axis - Week')
                    plt.ylabel('Y- Dependent - Sales')
                    week = df['week'].values.reshape(1,-1)
                    sales = df['sales'].values.reshape(1,-1)
                    X = df[['week']]
                    y = df['sales']

                    regr = linear_model.LinearRegression()
                    regr.fit(X,y)

                    print('Intercept: \n', regr.intercept_)
                    print('Coefficients: \n', regr.coef_)

                    print('\nThe Regression Equation is',regr.coef_,'* X+',regr.intercept_)
                    import matplotlib.pyplot as plt
                    from sklearn import linear_model
                    from sklearn.datasets import make_regression

                    X,y = make_regression(n_samples = 50,n_features=1,noise=0.1)

                    plt.scatter(X,y,color='green')
                    plt.title('Regression among X and y')
                    plt.xlabel('X - axis - X')
                    plt.ylabel('Y- Dependent - y')
                    regr = linear_model.LinearRegression()
                    regr.fit(X,y)

                    print('Intercept: \n', regr.intercept_)
                    print('Coefficients: \n', regr.coef_)
                    print('\nThe Regression Equation is',regr.coef_,'* X +',regr.intercept_)
                    pred = regr.predict(X)
                    plt.plot(X,pred)
                    print("\nAdjusted R Squared for Regression model:",regr.score(X,y))

                    from sklearn import linear_model
                    from sklearn.datasets import make_regression

                    print("Multiple regression \n\n")

                    X,y = make_regression(n_samples = 50,n_features=2,noise=0.1)
                    regr = linear_model.LinearRegression()
                    regr.fit(X,y)

                    print('Intercept: \n', regr.intercept_)
                    print('Coefficients: \n', regr.coef_)
                    print("\nAdjusted R Squared for Regression model:",regr.score(X,y))""",
            6: """ import pandas
                    from sklearn.tree import DecisionTreeClassifier
                    from sklearn.preprocessing import LabelEncoder
                    from sklearn.model_selection import train_test_split
                    from sklearn import metrics
                    from sklearn.metrics import classification_report, confusion_matrix

                    data = {'CGPA':['g9','g8','g9','l8','g8','g9','l8','g9','g8','g8'],
                            'Inter':['Y','N','N','N','Y','Y','Y','N','Y','Y'],
                            'PK':['+++','+','==','==','+','+','+','+++','+','=='],
                            'CS':['G','M','P','G','M','M','P','G','G','G'],
                            'Job':['Y','Y','N','N','Y','Y','N','Y','Y','Y']}

                    table=pandas.DataFrame(data,columns=["CGPA","Inter","PK","CS","Job"])
                    table.where(table["CGPA"]=="g9").count()
                    encoder=LabelEncoder()

                    for i in table:
                        table[i]=encoder.fit_transform(table[i])

                    X=table.iloc[:,0:4].values
                    y=table.iloc[:,4].values

                    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size= 0.20,random_state=2)
                    model=DecisionTreeClassifier(criterion='entropy', max_depth=3)
                    model = model.fit(X_train,y_train)

                    y_pred = model.predict(X_test)
                    print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
                    print(confusion_matrix(y_test, y_pred))
                    print(classification_report(y_test, y_pred))

                    print([1,0,0,1])
                    if model.predict([[1,0,0,1]])==1:
                        print("Got JOB")
                    else:
                        print("Didn’t get JOB")
                    print([2,0,2,0])
                    if model.predict([[2,0,2,0]])==1:
                        print("Got JOB")
                    else:
                        print("Didn’t get JOB")
                    from matplotlib import pyplot as plt
                    from sklearn import datasets
                    from sklearn.tree import DecisionTreeClassifier
                    from sklearn import tree
                    import graphviz
                    iris = datasets.load_iris()
                    X = iris.data
                    y = iris.target
                    clf = DecisionTreeClassifier(criterion='entropy', max_depth=3)
                    model = clf.fit(X, y)
                    fig = plt.figure(figsize=(10,8))
                    _ = tree.plot_tree(clf,
                                    feature_names=iris.feature_names,
                                    class_names=iris.target_names,
                                    filled=True)
                    plt.show()""",
            7: """from sklearn.preprocessing import LabelEncoder
                    from sklearn.model_selection import train_test_split
                    from sklearn.naive_bayes import GaussianNB
                    from sklearn import preprocessing
                    from sklearn.metrics import classification_report, confusion_matrix
                    CGPA = ['g9','g8','g9','l8','g8','g9','l8','g9','g8','g8']
                    Inter = ['Y','N','N','N','Y','Y','Y','N','Y','Y']
                    PK = ['+++','+','==','==','+','+','+','+++','+','==']
                    CS = ['G','M','P','G','M','M','P','G','G','G']
                    Job = ['Y','Y','N','N','Y','Y','N','Y','Y','Y']
                    le = preprocessing.LabelEncoder()
                    CGPA_encoded = le.fit_transform(CGPA)
                    print("CGPA:", CGPA_encoded)
                    Inter_encoded = le.fit_transform(Inter)
                    PK_encoded = le.fit_transform(PK)
                    CS_encoded = le.fit_transform(CS)
                    label = le.fit_transform(Job)
                    print("Inter:",Inter_encoded)
                    print ("PK:",PK_encoded)
                    print ("CS:",CS_encoded)
                    print("Job:",label)
                    features = []
                    for i in range(len(CGPA_encoded)):
                            features.append([CGPA_encoded[i], Inter_encoded[i], PK_encoded[i], CS_encoded[i]])

                    X_train,X_test,y_train,y_test=train_test_split(features,label,test_size=0.30,random_state=2)
                    model = GaussianNB()
                    model.fit(features,label)
                    y_pred = model.predict(X_test)
                    print(classification_report(y_test, y_pred))
                    print(confusion_matrix(y_test, y_pred))
                    print([2,0,2,0])
                    if model.predict([[2,0,2,0]])==1:
                        print("Predicted Value:Got JOB")
                    else:
                        print("Predicted Value:Didn't get JOB")

                    print([0,1,0,1])
                    if model.predict([[0,1,0,1]])==1:
                        print("Predicted Value:Got JOB")
                    else:
                        print("Predicted Value:Didn't get JOB")
                    from sklearn import datasets
                    from sklearn import metrics
                    from sklearn.naive_bayes import GaussianNB
                    from sklearn.metrics import classification_report, confusion_matrix
                    from sklearn.model_selection import train_test_split
                    dataset = datasets.load_iris()
                    model = GaussianNB()
                    X_train,X_test,y_train,y_test=train_test_split(dataset.data,dataset.target,test_size=0.30,random_state=2)
                    model.fit(X_train, y_train)
                    print(model)
                    y_expected = y_test
                    y_predicted = model.predict(X_test)
                    print(metrics.classification_report(y_expected, y_predicted))
                    print(metrics.confusion_matrix(y_expected, y_predicted)) """,
            8: """import pandas as pd
                    from sklearn.svm import SVC
                    from sklearn.model_selection import train_test_split
                    from sklearn.metrics import confusion_matrix
                    from sklearn.metrics import classification_report
                    from sklearn.metrics import accuracy_score
                    df = pd.read_csv("/content/Iris_dataset.csv")
                    print(df.head(10))
                    model.fit(X_train,y_train)a
                    print("\n\nAccuracy is")
                    accuracy = accuracy_score(y_test,pred)
                    print(accuracy)
                    print('\n Classification Report')
                    report = classification_report(y_test,pred)
                    print(report)
                    model1 = SVC(kernel='rbf',random_state=0)
                    model1.fit(X_train,y_train)
                    pred = model1.predict(X_test)
                    print("\n\nThe confusion matrix for RBF kernel is \n\n")
                    conf = confusion_matrix(y_test,pred)
                    print(conf)
                    print("\n\nAccuracy for RBF kernel is")
                    accuracy = accuracy_score(y_test,pred)
                    print(accuracy)""",
            9: """ import pandas
                    from sklearn.tree import DecisionTreeClassifier
                    from sklearn.ensemble import AdaBoostClassifier
                    from sklearn.preprocessing import LabelEncoder
                    from sklearn.model_selection import train_test_split
                    data = {'CGPA':['g9','l9','g9','l9','g9','g9'],
                            'Inter':['Y','N','N','N','Y','Y'],
                            'PK':['++','++','==','==','++','++'],
                            'CS':['G','M','M','G','M','M'],
                            'Job':['Y','Y','N','N','Y','Y']}
                    table=pandas.DataFrame(data,columns=["CGPA","Inter","PK","CS","Job"])
                    encoder=LabelEncoder()
                    for i in table:
                        table[i]=encoder.fit_transform(table[i])
                    X=table.iloc[:,0:4].values
                    y=table.iloc[:,4].values
                    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)
                    model = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=4)
                    model.fit(X_train, y_train)
                    print([1, 1, 0, 1])
                    if model.predict([[1, 1, 0, 1]]) == 1:
                        print("Got JOB")
                    else:
                        print("Didn't get JOB")

                    print([0, 0, 1, 0])
                    if model.predict([[0, 0, 1, 0]]) == 1:
                        print("Got JOB")
                    else:
                        print("Didn't get JOB")
                    import numpy as np
                    import pandas as pd
                    import seaborn as sns
                    import matplotlib.pyplot as plt
                    from sklearn.tree import DecisionTreeClassifier
                    from sklearn.ensemble import AdaBoostClassifier
                    from sklearn.model_selection import train_test_split
                    from sklearn.metrics import confusion_matrix
                    iris = sns.load_dataset('iris')
                    sns.set_style("whitegrid")
                    sns.FacetGrid(iris, hue="species", height=6).map(plt.scatter, 'sepal_length', 'petal_length').add_legend()
                    plt.show()
                    iris = pd.read_csv("/content/Iris_dataset.csv")   # make sure your file name is Iris.csv
                    print(iris.head(10))
                    # Rename columns if needed (optional)
                    iris.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'flower_name']
                    X = iris.iloc[:, :-1].values
                    y = iris.iloc[:, -1].values
                    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)
                    adaboost = AdaBoostClassifier(n_estimators=100, learning_rate=1, random_state=1)
                    adaboost.fit(X_train, y_train)
                    y_pred = adaboost.predict(X_test)
                    print("\nActual Labels :", y_test)
                    print("Predicted Labels :", y_pred)
                    plt.title('Actual vs Predicted (AdaBoost on Iris Data)')
                    plt.xlabel('Actual')
                    plt.ylabel('Predicted')
                    plt.scatter(y_test, y_pred)
                    plt.show()
                    cm = confusion_matrix(y_test, y_pred)
                    accuracy = float(cm.diagonal().sum()) / len(y_test)
                    print("\nAccuracy Of AdaBoost For The Given Dataset :", round(accuracy, 3))
                    import pandas as pd
                    import numpy as np
                    import matplotlib.pyplot as plt
                    from sklearn.datasets import make_blobs
                    from sklearn.tree import DecisionTreeClassifier
                    from sklearn.ensemble import AdaBoostClassifier
                    from sklearn.model_selection import train_test_split
                    X, y = make_blobs(n_samples=30, centers=2, n_features=2, center_box=(10, 20), random_state=0)
                    df = pd.DataFrame(dict(x=X[:, 0], y=X[:, 1], label=y))
                    print(X.shape)
                    print("\nTop five Records:\n")
                    print(df.head(10))
                    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40, random_state=0)
                    model = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=10)
                    model.fit(X_train, y_train)
                    plt.figure(figsize=(10, 5))
                    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
                    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
                    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
                                        np.arange(y_min, y_max, 0.02))

                    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
                    Z = Z.reshape(xx.shape)
                    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
                    plt.axis("tight")
                    for i, c in zip(range(2), ['r', 'b']):
                        idx = np.where(y == i)
                        plt.scatter(X[idx, 0], X[idx, 1], c=c, edgecolor='k', s=40, label=f"Class {i}")

                    plt.legend(loc='upper right')
                    plt.xlabel('x')
                    plt.ylabel('y')
                    plt.title('Decision Boundary using AdaBoost')
                    plt.show()""",
            10: """import pandas as pd
                    from sklearn.cluster import KMeans
                    from sklearn import metrics
                    import matplotlib.pyplot as plt
                    import seaborn as sns

                    data = [[2,4],[4,6],[6,8],[10,4],[12,4]]
                    df = pd.DataFrame(data, columns = ['X','Y'])

                    plt.scatter(df['X'],df['Y'],color='green')
                    plt.title('Scatter Diagram')
                    plt.xlabel('X - axis   - X')
                    plt.ylabel('Y- Dependent - Y')

                    kmeans = KMeans(n_clusters = 2)
                    kmeans.fit(df)
                    df['pred'] = kmeans.predict(df)
                    sns.lmplot(x='X',y='Y',fit_reg=False,data=df,hue='pred')
                    labels = kmeans.labels_
                    score=metrics.silhouette_score(df, labels, metric='euclidean')
                    print('\nSilhouette score is:',score)

                    import pandas as pd
                    from sklearn.cluster import KMeans
                    import seaborn as sns

                    df = pd.read_csv("/content/Iris_dataset.csv")
                    df.columns = ['x1', 'x2', 'x3', 'x4', 'y']
                    df = df.drop(['x3', 'x4'], axis=1)
                    print(df.head(10))

                    kmeans = KMeans(n_clusters=3, random_state=42)
                    X = df[['x1', 'x2']]
                    kmeans.fit(X)
                    df['pred'] = kmeans.predict(X)
                    sns.lmplot(x='x1', y='x2', data=df, hue='pred', fit_reg=False)
                    labels = kmeans.labels_
                    score = metrics.silhouette_score(X, labels, metric='euclidean')
                    print("\nSilhouette Score is:", score)""",
        }

    def run(self, x):
        """Return the message for program number x or an error message."""
        return self.messages.get(x, "Invalid program number")
