Data Visualisation with Matplotlib || Fresco Play || 56869

Data Visualisation with Matplotlib - 56869

Matplotlib-1 - My First Plot

Task1

  • Create a function named test_the_plot.
  • Create a figure of size 12 inches in width, and 6 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a list t with values [7, 14, 21, 28, 35]
  • Create a list d with values [i*6 for i in t]
  • Draw a line, by plotting t values on X-Axis and d values on Y-Axis. Use the plot function. Label the line as d = 6t.
  • Label X-Axis as time (seconds).
  • Label Y-Axis as distance (meters).
  • Set Title as Time vs Distance Covered.
  • Limit data points on X-Axis from 0 to 40.
  • Limit data points on Y-Axis from 0 to 220.
  • Add a legend.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands
python3 prog.py
  1. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def test_the_plot():
    fig = plt.figure(figsize=(12, 6))
    ax = fig.add_subplot(111)
    t = [7, 14, 21, 28, 35]
    d = [i * 6 for i in t]
    ax.plot(t, d, label='d = 6t')
    ax.set_xlabel('time (seconds)')
    ax.set_ylabel('distance (meters)')
    ax.set_title('Time vs Distance Covered')
    ax.set_xlim(0, 40)
    ax.set_ylim(0, 220)
    ax.legend("My First Plot")
    return fig

# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot1-0.2-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot1 import matplotlib1
    usr_fig = test_the_plot()
    matplotlib1.save_answer(usr_fig)

Matplotlib-2 - Scatter Plots

Task1

  • Create a function named sine_wave_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a numpy array arr_t with 250 values between 0.0 and 3.0. Use the 'linspace' method to generate 250 values.
  • Create a numpy array arr_v, such that arr_v = np.sin(2.5*np.pi*arr_t).
  • Pass arr_t and arr_v as variables to plot function and draw a red line passing through the selected 250 points. Label the line as sin(arr_t).
  • Label X-Axis as Time (seconds).
  • Label Y-Axis as Voltage (mv).
  • Set Title as Sine Wave.
  • Limit data on X-Axis from 0 to 2.
  • Limit data on Y-Axis from -1 to 1.
  • Mark major ticks on X-Axis at 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, and 2.0.
  • Mark major ticks on Y-Axis at -1, 0, and 1.
  • Add a grid, whose linestyle is dashdot.
  • Add a legend.
  • return the figure object

Task2

  • Create a function named multi_curve_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a numpy array arr_x with 25 values between 0.0 and 7.0. Use the 'linspace' method to generate 25 values.
  • Create three numpy arrays arr_y1, arr_y2 and arr_y3, using the expressions arr_y1 = arr_x, arr_y2 = arr_x**2 and arr_y3 = arr_x**3 respectively.
  • Draw a green colored line passing through arr_x and arr_y1, using the plot function. Mark the 25 data points on the line as upward pointed triangles. Label the line as y = arr_x.
  • Draw a blue colored line passing through arr_x and arr_y2, using the plot function. Mark the 25 data points on the line as squares. Label the line as y = arr_x**2.
  • Draw a red colored line passing through arr_x and arr_y3, using the plot function. Mark the 25 data points on the line as circles.
  • Label the line as y = arr_x**3.
  • Label X-Axis as arr_x.
  • Label Y-Axis as f(arr_x).
  • Set Title as Linear, Quadratic, & Cubic Equations.
  • Add a legend.
  • return the figure object

Task3

  • Create a function named scatter_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Consider the list car_sales = [40, 65, 70, 40, 55, 60, 75, 60, 80, 95, 96, 105]. It represents the number of cars sold by a Company 'X' in each month of 2021, starting from January, 2021.
  • Create a list months containing numbers from 1 to 12.
  • Draw a scatter plot with variables months and car_sales as arguments. Mark the data points in green color. Use the scatter function for plotting.Label the points as car sales.
  • Limit data on X-Axis from 0 to 13.
  • Limit data on Y-Axis from 10 to 110.
  • Mark ticks on X-Axis at 1, 3, 5, 7, 9, and 11.
  • Label the X-Axis ticks as January, March, May, July, September, and November respectively.
  • Label X-Axis as Months
  • Label Y-Axis as No. of Cars Sold
  • Set Title as "Cars Sold by Company 'Z' in 2021".
  • Add a legend.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def sine_wave_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    arr_t = np.linspace(0.0, 3.0, num = 250)
    arr_v = np.sin(2.5 * np.pi * arr_t)
    ax.plot(arr_t, arr_v, label="sin(arr_t)")
    ax.set_xlabel("Time (seconds)")
    ax.set_ylabel("Voltage (mv)")
    ax.set_title("Sine Wave")
    ax.set_xlim(0, 2)
    ax.set_ylim(-1, 1)
    ax.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])
    ax.set_yticks([-1, 0, 1])
    ax.grid(linestyle="dashdot")
    ax.legend(["Voltage Speed"])
    return fig


def multi_curve_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    arr_x = np.linspace(0.0, 7.0, num = 25)
    arr_y1 = arr_x
    arr_y2 = arr_x ** 2
    arr_y3 = arr_x ** 3

    ax.plot(arr_x, arr_y1, color="green", marker="^", label ="y = arr_x")
    ax.plot(arr_x, arr_y2, color="blue", marker="s", label ="y = arr_x**2")
    ax.plot(arr_x, arr_y3, color="red", marker="o", label ="y = arr_x**3")
    ax.set_xlabel("arr_x")
    ax.set_ylabel("f(arr_x)")
    ax.set_title("Linear, Quadratic, & Cubic Equations")
    ax.legend(["Linear", "Quadratic", "Cubic"])
    return fig



def scatter_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    car_sales = [40, 65, 70, 40, 55, 60, 75, 60, 80, 95, 96, 105]
    months = np.array(range(1, 13))
    ax.scatter(months, car_sales, color="green", label="car sales")
    ax.set_xlim(0, 13)
    ax.set_ylim(10, 110)
    ax.set_xticks(np.array(range(1, 13, 2)), ["January", "March", "May", "July", "September", "November"])
    ax.set_xlabel("Months")
    ax.set_ylabel("No. of Cars Sold")
    ax.set_title("Cars Sold by Company 'Z' in 2021")
    ax.legend(["Count of Cars Sold"])
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot2-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot2 import matplotlib2
    usr_fig1 = sine_wave_plot()
    usr_fig2 = multi_curve_plot()
    usr_fig3 = scatter_plot()
    matplotlib2.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-3 - Bar Plots

Task1

  • Create a function named barplot_of_iris_sepal_length.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define a list species, with elements ['setosa', 'versicolor', 'virginica'].
  • Define a list index, with values [0.4, 1.4, 2.4].
  • Define another list sepal_len with values [6.01, 6.94, 7.69]. These values represent the mean sepal length of iris flowers belonging to three species.
  • Draw a bar plot using the bar function, such that the height of each vertical bar displays the sepal length of a species label it as Sepal Length.
  • Use index and sepal_len as variables. Set bar width as 0.4, color as blue, and border color of the bar as red.
  • Label X-Axis as Species.
  • Label Y-Axis as Sepal Length (cm).
  • Set Title as Mean Sepal Length of Iris Species.
  • Limit X-Axis from 0 to 3.
  • Limit Y-Axis from 0 to 9.
  • Set ticks on X-Axis at 0.4, 1.4, and 2.4.
  • Set X-Axis tick labels to ['setosa', 'versicolor', 'virginica'].
  • Add a legend.
  • return the figure object.

Task2

  • Create a function named barplot_of_iris_measurements.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define the following lists:
  • sepal_len = [6.01, 6.94, 7.59]
  • sepal_wd = [4.42, 3.77, 3.97]
  • petal_len = [2.46, 5.26, 6.55]
  • petal_wd = [1.24, 2.33, 3.03]
  • species = ['setosa', 'versicolor', 'virginica']
  • species_index1 = [0.7, 1.7, 2.7]
  • species_index2 = [0.9, 1.9, 2.9]
  • species_index3 = [1.1, 2.1, 3.1]
  • species_index4 = [1.3, 2.3, 3.3]
  • Draw vertical bars showing the mean sepal length of a species. Set the color of the bars to m, boundary line color to grey, width of bars as 0.2, and label it as Sepal Length. Use bar with species_index1 and sepal_len.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to y, boundary line color to grey, width of bars as 0.2, and label it as Sepal Width. Use bar with species_index2 and sepal_wd.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to c, boundary line color to grey, width of bars as 0.2, and label it as Petal Length. Use bar with species_index3 and petal_len.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to orange, boundary line color to grey, width of bars as 0.2, and label it as Petal Width. Use bar with species_index4 and petal_wd.
  • Label X-Axis as Species.
  • Label Y-Axis as Iris Measurements (cm).
  • Set Title as Mean Measurements of Iris Species.
  • Limit X-Axis from 0.5 to 3.5 .
  • Limit Y-Axis from 0 to 10.
  • Mark major ticks on X-Axis at 1.0, 2.0, and 3.0.
  • Label the major ticks on X-Axis as setosa, versicolor and virginica respectively.
  • Add a legend.
  • return the figure object.

Task3

  • Create a function named hbarplot_of_iris_petal_length.
  • Create a figure of size 15 inches in width, and 5 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define a list species, with elements ['setosa', 'versicolor', 'virginica'].
  • Define a list index, with values [0.1, 1.1, 2.1].
  • Define another list petal_len with values [2.67, 5.49, 6.37]. These values represent the mean petal length of iris flowers belonging to three species.
  • Draw a horizontal bar plot using barh function, such that the width of each bar display the petal length of a species and label it as Petal Length.
  • Use index and petal_len as variables. Set bar height as 0.4, color as m, and border color of the bar as c.
  • Label Y-Axis as Species
  • Label X-Axis as `Petal Length (cm).
  • Set Title as Mean Petal Length of Iris Species.
  • Mark major ticks on Y-Axis at 0.10, 1.10 and 2.10.
  • Label the major ticks on Y-Axis as setosa, versicolor and virginica respectively.
  • Add a legend.
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def barplot_of_iris_sepal_length():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    ax = fig.add_subplot(111)
    species = ['setosa', 'versicolor', 'virginica']
    index = [0.4, 1.4, 2.4]
    sepal_len = [6.01, 6.94, 7.69]
    ax.bar(index, sepal_len, label="Sepal Length", width=0.4, color="blue", edgecolor="red")
    ax.set_xlabel("Species")
    ax.set_ylabel("Sepal Length (cm)")
    ax.set_title("Mean Sepal Length of Iris Species")
    ax.set_xlim(0, 3)
    ax.set_ylim(0, 9)
    ax.set_xticks(index)
    ax.set_xticklabels(species)
    ax.legend(["Sepal Length"])
    return fig


def barplot_of_iris_measurements():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    ax = fig.add_subplot(111)
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.7, 1.7, 2.7]
    species_index2 = [0.9, 1.9, 2.9]
    species_index3 = [1.1, 2.1, 3.1]
    species_index4 = [1.3, 2.3, 3.3]

    ax.bar(species_index1, sepal_len, color="m", edgecolor="grey", width=0.2, label="Sepal Length")
    ax.bar(species_index2, sepal_wd, color="y", edgecolor="grey", width=0.2, label="Sepal Width")
    ax.bar(species_index3, petal_len, color="c", edgecolor="grey", width=0.2, label="Petal Length")
    ax.bar(species_index4, petal_wd, color="orange", edgecolor="grey", width=0.2, label="Petal Width")
    ax.set_xlabel("Species")
    ax.set_ylabel("Iris Measurements (cm)")
    ax.set_title("Mean Measurements of Iris Species")
    ax.set_xlim(0.5, 3.5)
    ax.set_ylim(0, 10)
    ax.set_xticks([1.0, 2.0, 3.0])
    ax.set_xticklabels(species)
    ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


def hbarplot_of_iris_petal_length():

    # Write your functionality below
    fig = plt.figure(figsize=(15, 5))
    ax = fig.add_subplot(111)
    species = ['setosa', 'versicolor', 'virginica']
    index = [0.1, 1.1, 2.1]
    petal_len = [2.67, 5.49, 6.37]

    ax.barh(index, petal_len, height=0.4, label="Petal Length", color="m", edgecolor="c")
    ax.set_xlabel("Species")
    ax.set_ylabel("Petal Length (cm)")
    ax.set_title("Mean Petal Length of Iris Species")
    ax.set_yticks(index)
    ax.set_yticklabels(species)
    ax.legend(["Petal Length"])

    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot3-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot3 import matplotlib3
    usr_fig1 = barplot_of_iris_sepal_length()
    usr_fig2 = barplot_of_iris_measurements()
    usr_fig3 = hbarplot_of_iris_petal_length()
    matplotlib3.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-4 - Histograms and Box Plots

Task1

  • Create a function named hist_of_a_sample_normal_distribution.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Set random seed to 100 using the expression np.random.seed(100).
  • Create a normal distribution dist_arr of 1000 values, with mean 35 and standard deviation 3.0. Use np.random.randn.
  • Draw a histogram of dist_arr with 35 bins. Use the hist function.
  • Label X-Axis as dist_arr
  • Label Y-Axis as Bin Count
  • Set Title as Histogram of a Single Dataset
  • return the figure object.

Task2

  • Create a function named boxplot_of_four_normal_distribution.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Set random seed to 100 using the expression np.random.seed(100).
  • Create a normal distribution arr_1 of 2000 values, with mean 35 and standard deviation 6.0. Use np.random.randn.
  • Create a normal distribution arr_2 of 2000 values, with mean 25 and standard deviation 4.0. Use np.random.randn.
  • Create a normal distribution arr_3 of 2000 values, with mean 45 and standard deviation 8.0. Use np.random.randn.
  • Create a normal distribution arr_4 of 2000 values, with mean 55 and standard deviation 10.0. Use np.random.randn.
  • Create a list labels with elements ['arr_1', 'arr_2', 'arr_3', 'arr_4].
  • Draw a Boxplot arr_1, arr_2, arr_3, arr_4 with notches and label it using the labels list. Use the boxplot function.
  • Choose o symbol for outlier, and fill color inside boxes by setting patch_artist argument to True.
  • Label X-Axis as Dataset
  • Label Y-Axis as Value
  • Set Title as Box plot of Multiple Datasets
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def hist_of_a_sample_normal_distribution():

    # Write your functionality below
    fig = plt.figure(figsize=(9,7))
    ax = fig.add_subplot(111)
    np.random.seed(100)
    dist_arr = np.random.randn(1000) * 3.0 + 35
    ax.hist(dist_arr, bins=35)
    ax.set_xlabel("dist_arr")
    ax.set_ylabel("Bin Count")
    ax.set_title("Histogram of a Single Dataset")
    return fig


def boxplot_of_four_normal_distribution():

    # Write your functionality below
    fig = plt.figure(figsize=(9,7))
    ax = fig.add_subplot(111)
    np.random.seed(100)
    arr_1 = np.random.randn(2000) * 6.0 + 35
    arr_2 = np.random.randn(2000) * 4.0 + 25
    arr_3 = np.random.randn(2000) * 8.0 + 45
    arr_4 = np.random.randn(2000) * 10.0 + 55
    elements = ['arr_1', 'arr_2', 'arr_3', 'arr_4']
    ax.boxplot([arr_1, arr_2, arr_3, arr_4], labels=elements, patch_artist=True, sym='o')
    ax.set_xlabel("Dataset")
    ax.set_ylabel("Value")
    ax.set_title("Box plot of Multiple Datasets")
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot4-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot4 import matplotlib4
    usr_fig1 = hist_of_a_sample_normal_distribution()
    usr_fig2 = boxplot_of_four_normal_distribution()
    matplotlib4.save_answer(usr_fig1, usr_fig2)

Matplotlib-5 - Applying Styles

Task1

  • Create a function named generate_plot_with_style1.
  • Generate the following barplot with 'ggplot' style. Use 'with' to apply the style to the code generating the barplot.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define the following lists
  • sepal_len = [6.01, 6.94, 7.59]
  • sepal_wd = [4.42, 3.77, 3.97]
  • petal_len = [2.46, 5.26, 6.55]
  • petal_wd = [1.24, 2.33, 3.03]
  • species = ['setosa', 'versicolor', 'virginica']
  • species_index1 = [0.8, 1.8, 2.8]
  • species_index2 = [1.0, 2.0, 3.0]
  • species_index3 = [1.2, 2.2, 3.2]
  • species_index4 = [1.4, 2.4, 3.4]
  • Draw vertical bars showing mean sepal length of a species. Set width of the bars as 0.2, and label it as Sepal Length. Use bar with species_index1 and sepal_len.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Sepal Width. Use bar with species_index2 and sepal_wd.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Petal Length. Use bar with species_index3 and petal_len.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Petal Width. Use bar with species_index4 and petal_wd.
  • Label X-Axis as Species.
  • Label Y-Axis as Iris Measurements (cm).
  • Set Title as Mean Measurements of Iris Species.
  • Limit X-Axis from 0.5 to 3.7.
  • Limit Y-Axis from 0 to 10.
  • Mark major ticks on X-Axis at 1.0, 2.0, and 3.0.
  • Label the major ticks on X-Axis as setosa, versicolor, and virginica respectively.
  • Add a legend.
  • return the figure object.

Task2

  • Create a function named generate_plot_with_style2.
  • Regenerate the barplot defined in 'generate_plot_with_style1' using 'seaborn-colorblind' style. Use 'with' for applying the style.
  • Limit X-Axis from 0.5 to 3.5.
  • return the figure object.

Task3

  • Create a function named generate_plot_with_style3.
  • Regenerate the barplot defined in 'generate_plot_with_style1' using 'grayscale' style. Use 'with' for applying the style.
  • Limit X-Axis from 0.5 to 3.5.
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def generate_plot_with_style1():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('ggplot'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.7)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])
    return fig


def generate_plot_with_style2():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('seaborn-colorblind'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.5)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


def generate_plot_with_style3():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('grayscale'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.5)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot5-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot5 import matplotlib5
    usr_fig1 = generate_plot_with_style1()
    usr_fig2 = generate_plot_with_style2()
    usr_fig3 = generate_plot_with_style3()
    matplotlib5.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-6 - Multiple Plots

Task1

  • Create a function named generate_figure1.
  • Define a numpy array 'x' with expression 'np.arange(0.0, 10.0, 0.01)'.
  • Define another numpy array 'arr_s1' with expression 'np.sin(3*np.pi*x)'
  • Define one more numpy array 'arr_s2' with expression 'np.sin(6*np.pi*x)'.
  • Create a figure of size 12 inches in width, and 7 inches in height. Name it as fig.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must point to the first virtual grid created by 2 rows and 1 column. Set 'title' argument to 'Sin(3*pi*x)'.
  • Draw a line plot of 'x' and 'arr_s1' using the 'plot' function on 'axes1`.
  • Create another axes, using the plt.subplot function. Name it as axes2. The subplot must point to the second virtual grid created by 2 rows and 1 column. Set 'title' argument to 'Sin(6*pi*x)'. Set 'sharex' argument to 'axes1' and 'sharey' argument to 'axes1'.
  • Draw a line plot of 'x' and 'arr_s2' using the 'plot' function on 'axes2`.
  • return the figure object

Task2

  • Create a function named generate_figure2.
  • Set random seed to 1500 using the expression 'np.random.seed(1500)'.
  • Define a numpy array 'x' with expression 'np.random.rand(10)'.
  • Define another numpy array 'y' with expression 'np.random.rand(10)'.
  • Define one more numpy array 'z' with expression 'np.sqrt(x**2 + y**2)'.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must point to the first virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Diamond Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes1`. Set argument 's' to 80, 'c' to z and 'marker' to 'd'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively
  • Create an axes, using plt.subplot function. Name it as axes2. The subplot must point to the Second virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Circle Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes2`. Set argument 's' to 80, 'c' to 'z' and 'marker' to 'o'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively.
  • Create an axes, using plt.subplot function. Name it as axes3. The subplot must point to the Third virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Plus Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes3`. Set argument 's' to 80, 'c' to 'z' and 'marker' to '+'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively.
  • Create an axes, using plt.subplot function. Name it as axes4. The subplot must point to the Fourth virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Upper Triangle Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes4`. Set argument 's' to 80, 'c' to 'z' and 'marker' to '^'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively
  • Adjust the entire layout with expression 'plt.tight_layout()'.
  • return the figure object

Task3

  • Create a function named generate_figure3.
  • Define a numpy array 'x' with expression 'np.arange(1, 301, 3)'.
  • Define another numpy array 'y1' with expression 'y1 = x'.
  • Define another numpy array 'y2' with expression 'y2 = x**2'.
  • Define another numpy array 'y3' with expression 'y3 = x**3'.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Define a grid 'gr' of 2 rows and 2 columns, using 'GridSpec' function. Ensure that 'matplotlib.gridspec' is imported, before defining the grid.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must span the 1st row and 1st column of the defined grid 'gr'. Set 'title' argument to 'y = x'.
  • Draw a line plot of 'x' and 'y1' using 'plot' function on 'axes1`.
  • Create an axes, using plt.subplot function. Name it as axes2. The subplot must span 2nd row and 1st column of defined grid 'gr'. Set 'title' argument to 'y = x**2'.
  • Draw a line plot of 'x' and 'y2' using 'plot' function on 'axes2`.
  • Create an axes, using plt.subplot function. Name it as axes3. The subplot must span all rows of 2nd column of defined grid 'gr'. Set 'title' argument to 'y = x**3'.
  • Draw a line plot of 'x' and 'y3' using 'plot' function on 'axes3`.
  • Adjust the entire layout with the expression 'plt.tight_layout()'.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def generate_figure1():

    # Write your functionality below
    fig = plt.figure(figsize=(12, 7))
    x = np.arange(0.0, 10.0, 0.01)
    arr_s1 = np.sin(3 * np.pi * x)
    arr_s2 = np.sin(6 * np.pi * x)

    axes1 = plt.subplot(2,1,1,title="Sin(3*pi*x)")
    axes1.plot(x, arr_s1)

    axes2 = plt.subplot(2,1,2,title="Sin(6*pi*x)")
    axes2.plot(x, arr_s2)
    return fig


def generate_figure2():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    np.random.seed(1500)
    x = np.random.rand(10)
    y = np.random.rand(10)
    z = np.sqrt(x**2 + y**2)

    axes1 = plt.subplot(2, 2, 1, title="Scatter plot with Diamond Markers")
    axes1.scatter(x, y, s=80, c=z, marker='d')
    axes1.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes1.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes2 = plt.subplot(2, 2, 2, title="Scatter plot with Circle Markers")
    axes2.scatter(x, y, s=80, c=z, marker='o')
    axes2.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes2.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes3 = plt.subplot(2, 2, 3, title="Scatter plot with Plus Markers")
    axes3.scatter(x, y, s=80, c=z, marker='+')
    axes3.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes3.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes4 = plt.subplot(2, 2, 4, title="Scatter plot with Upper Triangle Markers")
    axes4.scatter(x, y, s=80, c=z, marker='^')
    axes4.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes4.set_yticks([-0.2, 0.2, 0.6, 1.0])

    plt.tight_layout()
    return fig


def generate_figure3():
    import matplotlib.gridspec as gridspec
    # Write your functionality below
    x = np.arange(1, 301, 3)
    y1 = x
    y2 = x**2
    y3 = x**3

    fig = plt.figure(figsize=(9, 7))
    gr = gridspec.GridSpec(2,2)

    axes1 = plt.subplot(gr[0,0], title='y = x')
    axes1.plot(x, y1)

    axes2 = plt.subplot(gr[1,0], title="y = x**2")
    axes2.plot(x, y2)

    axes3 = plt.subplot(gr[:,1], title="y = x**3")
    axes3.plot(x, y3)

    plt.tight_layout()
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot6-0.2-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot6 import matplotlib6
    usr_fig1 = generate_figure1()
    usr_fig2 = generate_figure2()
    usr_fig3 = generate_figure3()
    matplotlib6.save_answer(usr_fig1, usr_fig2, usr_fig3)
Share:

PySpark || Fresco Play || 58339

Pyspark - Creating Dataframe

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create a DataFrame using SparkSession object, and display the DataFrame.

Step4: Create a simple passenger instance with 4 fields, Name, age, source, destination.

Step5: Create 2 passenger fields with following values

  • David , 22, London, Paris
  • Steve, 22, New York , Sydney

Step 6: Display the DataFrame to check the data.

NOTE:

Don't edit the line at the bottom of the answer.py file which will save the created DataFrame into a file.

Steps to complete the Handson:

1. Install all the necessary dependencies using the INSTALL option from the Project menu.

2. Run your solution using the RUN -> Run option.

3. Run the tests to check using the TEST option from the Project menu.

#IMP : In order to execute your code in answer.py file, please open a new terminal and use the command "spark-submit answer.py"

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

echo "Installation not needed"

Solution

from pyspark.sql import SparkSession, Row

sc = SparkSession.builder.appName("Example App").getOrCreate()
Passenger = Row("Name", "age", "source", "destination")
p1 = Passenger("David" , 22, "London", "Paris")
p2 = Passenger("Steve", 22, "New York", "Sydney")
passData = [p1, p2]
df = sc.createDataFrame(passData)
df.show()
# Don't Remove this line 
df.coalesce(1).write.parquet("PassengerData")

Reading files in PySpark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Read the json file, and create a DataFrame with the json data. Display the DataFrame. Save the DataFrame to a parquet file with name Employees.

Step 4: From the DataFrame, display the associates who are mapped to `JAVA` stream. Save the resultant DataFrame to a parquet file with name JavaEmployees.

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result folders.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

echo "No need to install"

Solution

# Put your code here
from pyspark.sql import SparkSession

sc = SparkSession.builder.appName("Example App").getOrCreate()
df = sc.read.load("emp.json", format="json")

df.show(2)
df.coalesce(1).write.parquet("Employees")

df_java = df.filter(df.stream == 'JAVA')
df_java.coalesce(1).write.parquet("JavaEmployees")

Statistical and Mathematical Functions with DataFrames in Apache Spark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the pyspark and SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create 10 random values as a column and name the column as rand1

Step 4: Create another 10 random values as column and name the column as rand2.

Step 4: Calculate the co-variance and correlation between these two columns.

Step5: Create a new Dataframe with Header names as "Stats" and "Value"

Step6: Fill the new Dataframe with the obtained values as "Co-variance" and "Correlation"

Step7: Save the resultant DataFrame to a CSV file with name Result

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result files.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

#IMP : In order to execute your code in answer.py file, please open a new terminal and use the command "spark-submit answer.py"

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

bash install.sh

Solution

# Put your code here
from pyspark.sql import SparkSession, Row
from pyspark.sql.functions import rand

sc = SparkSession.builder.appName("Example App").getOrCreate()
df = sc.range(0, 10).withColumn('rand1', rand(seed=11)).withColumn('rand2', rand(seed=31))

Stat = Row("Stats", "Value")
stat1 = Stat("Co-variance", df.stat.cov('rand1', 'rand2'))
stat2 = Stat("Correlation", df.stat.corr('rand1', 'rand2'))
stat_df = sc.createDataFrame([stat1, stat2])
stat_df.write.csv("Result", header = True)

More operations in PySpark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create a DataFrame with the following details under the headers as "ID", "Name","Age","Area of Interest"

Step 4: Fill the Dataframe with the following data:

  • "1","Jack", 22,"Data Science"
  • "2","Luke", 21,"Data Analytics"
  • "3","Leo", 24,"Micro Services"
  • "4","Mark", 21,"Data Analytics"

Step 5: Use describe method on Age column and observe the statistical parameters and save the data into a parquet file under the folder with name "Age" inside /projects/challenge/.

Step 6: Select the columns ID, Name, and Age, and Name should be in descending order. Save the resultant into a parquet file under the folder with name "NameSorted" inside /projects/challenge/.

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result folders.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

bash install.sh

Solution

from pyspark.sql import SparkSession, Row

sc = SparkSession.builder.appName("Example App").getOrCreate()
Employee = Row("ID", "Name","Age","Area of Interest")
emp1 = Employee("1","Jack", 22,"Data Science")
emp2 = Employee("2","Luke", 21,"Data Analytics")
emp3 = Employee("3","Leo", 24,"Micro Services")
emp4 = Employee("4","Mark", 21,"Data Analytics")
empData = [emp1, emp2, emp3, emp4]
df = sc.createDataFrame(empData)

df.describe("Age").coalesce(1).write.parquet("Age")

df.sort("Name", ascending=False).coalesce(1).write.parquet("NameSorted")
Share:

Flask - Python Web Framework || Fresco Play || 57963

Creating a Virtual Python Environment

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run --> Install` to install the required dependencies.

Task 2 : Create a Virtual Environment

  • Open a new terminal by clicking 'File ---> New Terminal'.
  • Create a virtual environment named 'myprojectenv'.
    Hint: Use 'virtualenv'.
  • Activate the virtual environment 'myprojectenv'.
    Hint:
    Use the 'source' command.
  • Install the flask module in the activated virtual environment. Hint: Use 'pip' command to install the 'flask' module.
  • Exit from the virtual environment 'myprojectenv'.
    Hint:
    Use the 'deactiavte' command.

Task 3: Verify the Virtual Environment

  • Verify if the virtual environment 'myprojectenv' is successfully created or not by clicking `Run -> Test`.

Task 4: Submit the Solution

  • After successful verification of the virtual environment, submit the solution by clicking the 'Submit' button.

Git Instructions

Use the following commands to work with this project

echo start

bash .test.sh

python -m pip install --user --upgrade pip

Solution

python -m virtualenv myprojectenv
source myprojectenv/bin/activate
pip install flask
deactivate

Creating a Basic Flask Application

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run -> Install` to install the required dependencies.

Task 2 : Create a Basic Flask Application

  • After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
  • Create a flask application named 'app'.
  • Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
  • Ensure that the view function 'hello' is routed when a user accesses the URL '/'.
  • Run the application at 0.0.0.0 and port 8000.

Task 3: View the Application

  • After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
  • Click PreviewApp to open the home page of the flask application in the HackerRank browser.
  • If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.

Task 4: Test the Application

  • Test the application by clicking 'Run -> Test'.
  • The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
  • If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.

Task 4: Submit the Solution

  • Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.

Git Instructions

Use the following commands to work with this project

python3 helloapp/hello.py

py.test helloapp/tests.py

python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt

Solution

from flask import Flask

## Define a flask application name 'app' below
app = Flask(__name__)


## Define below a view function 'hello', which displays the message 
## "Hello World!!! I've run my first Flask application."
@app.route('/')
def hello():
  return "Hello World!!! I've run my first Flask application."


## Write the required code below which runs flask applictaion 'app' defined above
## on host 0.0.0.0 and port 8000
if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000)

Writing View Functions in Flask

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run -> Install` to install the required dependencies.

Task 2 : Create a Basic Flask Application

  • After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
  • Create a flask application named 'app'.

Task 3 : Define 'hello' View Function

  • Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
  • Ensure that the view function 'hello' is routed when a user accesses the URL '/' .

Task 4 : Define 'hello_user' View Function

  • Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
  • After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list.
  • Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
  • Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.

Task 5 : Define 'quotes' View Function

  • Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
  • Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
  • Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.

Task 6 : Launch the Application

  • Write a function to launch the application at 0.0.0.0 and port 8000.

Task 7: View the Application

  • After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
  • Click PreviewApp to open the home page of the flask application in the HackerRank browser.
  • If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.

Task 8: Test the Application

  • Test the application by clicking 'Run -> Test'.
  • The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
  • If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.

Task 9: Submit the Solution

  • Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.

Git Instructions

Use the following commands to work with this project

python3 helloapp/hello.py

py.test helloapp/tests.py

python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt

Solution

from flask import Flask
import random

# Define a flask application name 'app' below
app = Flask(__name__)


# Define below a view function 'hello', which displays the message
## "Hello World!!! I've run my first Flask application."
# The view function 'hello' should be mapped to URL '/' .
@app.route("/")
def hello():
    return "Hello World!!! I've run my first Flask application."


# Define below a view function 'hello_user', which takes 'username' as an argument
# and returns the html string containing a 'h2' header  "Hello <username>"
# After displaying the hello message, the html string must also display one quote,
# randomly chosen from the provided list `quotes`
# Before displaying the quote, the html string must contain the 'h3' header 'Quote of the Day for You'
# The view function 'hello_user' should be mapped to URL '/hello/<username>/' .
# Use the below list 'quotes' in 'hello_user'  function
# quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who has been swimming naked."
# ]
@app.route("/hello/<username>/")
def hello_user(username):
    quotes = [
        "Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
        "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Listen to many, speak to a few.",
        "Only when the tide goes out do you discover who has been swimming naked.",
    ]
    return """<h2>Hello {}</h2>
    <h3>Quote of the Day for You</h3>
    <p>{}</p>""".format(username, random.choice(quotes))


# Define below a view function 'display_quotes', which returns an html string
# that displays all the quotes present in 'quotes' list in a unordered list.
# Before displaying 'quotes' as an unordered list, the html string must also include a 'h1' header "Famous Quotes".
# The view function 'display_quotes' should be mapped to URL '/quotes/' .
# Use the below list 'quotes' in 'display_quotes'  function
# quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who has been swimming naked."
# ]
@app.route("/quotes/")
def display_quotes():
    quotes = [
        "Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
        "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Listen to many, speak to a few.",
        "Only when the tide goes out do you discover who has been swimming naked.",
    ]
    quotes_list = ""
    for quote in quotes:
        quotes_list += "<li>{}</li>".format(quote)
    return """<h1>Famous Quotes</h1>
  <ul>
  {}
  </ul>""".format(quotes_list)


# Write the required code below which runs flask applictaion 'app' defined above
# on host 0.0.0.0 and port 8000
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Using Templates in Flask

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run -> Install` to install the required dependencies.

Task 2 : Create a Basic Flask Application

  • After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
  • Create a flask application named 'app'.

Task 3 : Define 'hello' View Function

  • Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
  • Ensure that the view function 'hello' is routed when a user accesses the URL '/' .

  • Ensure that the view function 'hello' renders the template 'index.hmtl'.
    Hint:
    Create 'index.html' inside the 'templates' folder.

Task 4 : Define 'hello_user' View Function

  • Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
  • After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list.
  • Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
  • Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.
  • Ensure that the view function 'hello_user' renders the template 'hello_user.hmtl'. Hint: Create 'hello_user.html' inside the 'templates' folder.

Task 5 : Define 'quotes' View Function

  • Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
  • Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
  • Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.
  • Ensure that the view function 'quotes' renders the template 'quotes.hmtl'. Hint: Create 'quotes.html' inside the 'templates' folder.

Task 6 : Launch the Application

  • Write a function to launch the application at 0.0.0.0 and port 8000.

Task 7: View the Application

  • After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
  • Click PreviewApp to open the home page of the flask application in the HackerRank browser.
  • If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.

Task 8: Test the Application

  • Test the application by clicking 'Run -> Test'.
  • The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
  • If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.

Task 9: Submit the Solution

  • Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.

Git Instructions

Use the following commands to work with this project

python3 helloapp/hello.py

py.test helloapp/tests.py

python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt

Solution

from flask import Flask, render_template
import random

# Define a flask application name 'app' below
app = Flask(__name__)


# Define below a view function 'hello', which displays the message
## "Hello World!!! I've run my first Flask application."
# The view function 'hello' should be mapped to URL '/' .
# The view function must render the template 'index.html'
@app.route("/")
def hello():
    return render_template("index.html")


# Define below a view function 'hello_user', which takes 'username' as an argument
# and returns the html string containing a 'h2' header  "Hello <username>"
# After displaying the hello message, the html string must also display one quote,
# randomly chosen from the provided list `quotes`
# Before displaying the quote, the html string must contain the 'h3' header 'Quote of the Day for You'
# The view function 'hello_user' should be mapped to URL '/hello/<username>/' .
# The view function must render the template 'hello_user.html'
# Use the below list 'quotes' in 'hello_user'  function
# quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who's been swimming naked."
# ]
@app.route("/hello/<username>/")
def hello_user(username):
    quotes = [
        "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
        "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Listen to many, speak to a few.",
        "Only when the tide goes out do you discover who's been swimming naked."
    ]
    return render_template("hello_user.html", username=username, quote=random.choice(quotes))


# Define below a view function 'display_quotes', which returns an html string
# that displays all the quotes present in 'quotes' list in a unordered list.
# Before displaying 'quotes' as an unordered list, the html string must also include a 'h1' header "Famous Quotes".
# The view function 'display_quotes' should be mapped to URL '/quotes/' .
# The view function must render the template 'quotes.html'
# Use the below list 'quotes' in 'display_quotes'  function
# quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who's been swimming naked."
# ]
@app.route("/quotes/")
def display_quotes():
    quotes = [
        "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
        "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Listen to many, speak to a few.",
        "Only when the tide goes out do you discover who's been swimming naked."
    ]
    return render_template("quotes.html", quotes=quotes)


# Write the required code below which runs flask applictaion 'app' defined above
# on host 0.0.0.0 and port 8000
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Defining Models in Flask

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run -> Install` to install the required dependencies.

Task 2 : Define 'Quotes' Model

  • After setting up the environment, define the 'Quotes' model in 'helloapp/models.py'.
  • The model must contain three columns named 'id', 'quoteauthor', and 'quotestring'.
    • 'id' must be an integer and primary key.
    • 'quoteauthor' must be a string of max 100 characters.
    • 'quotestring' must be a string of max 200 characters.
  • Define the method '__repr__' which displays a quote object as ''.
  • Perform database migrations, and insert data in the 'quotes' database from the backend.

Task 3 : Define 'hello' View Function in 'helloapp/routes.py'

  • Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
  • Ensure that the view function 'hello' is routed when a user accesses the URL '/'.
  • Ensure that the view function 'hello' renders the template 'index.hmtl'.
    Hint:
    Create 'index.html' inside the 'templates' folder.

Task 4 : Define 'hello_user' View Function in 'helloapp/routes.py'

  • Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
  • After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list in `hello.db'.
  • Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
  • Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.
  • Ensure that the view function 'hello_user' renders the template 'hello_user.hmtl'. Hint: Create 'hello_user.html' inside the 'templates' folder.

Task 5 : Define 'quotes' View Function in 'helloapp/routes.py'

  • Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
  • Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
  • Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.

  • Ensure that the view function 'quotes' renders the template 'quotes.hmtl'. Hint: Create 'quotes.html' inside the 'templates' folder.

Task 6: View the Application

  • After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
  • Click PreviewApp to open the home page of the flask application in the HackerRank browser.
  • If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.

Task 7: Test the Application

  • Test the application by clicking 'Run -> Test'.
  • The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
  • If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.

Task 8: Submit the Solution

  • Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.

Git Instructions

Use the following commands to work with this project

export LC_ALL=C.UTF-8; export LANG=C.UTF-8; export FLASK_APP=main.py; flask run --host 0.0.0.0 --port 8000

py.test helloapp/tests.py

python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt

Solution

helloapp/models.py

from helloapp import db

# Define Quotes model below
class Quotes(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  quoteauthor = db.Column(db.String(100))
  quotestring = db.Column(db.String(100))

  def __repr__(self):
    return "<Quote : [{}]>".format(self.quotestring)

helloapp/routes.py

from flask import render_template
import random
from .models import Quotes

from helloapp import app, db

## Define below a view function 'hello', which displays the message 
## "Hello World!!! I've run my first Flask application."
## The view function 'hello' should be mapped to URL '/' .
## The view function must render the template 'index.html'
@app.route('/')
def hello():
  return render_template('index.html')



## Define below a view function 'hello_user', which takes 'username' as an argument 
## and returns the html string containing a 'h2' header  "Hello <username>"
## After displaying the hello message, the html string must also display one quote, 
## randomly chosen from the provided list `quotes` 
## Before displaying the quote, the html string must contain the 'h3' header 'Quote of the Day for You' 
## The view function 'hello_user' should be mapped to URL '/hello/<username>/' .
## The view function must render the template 'hello_user.html'
## Use the below list 'quotes' in 'hello_user'  function
## quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who's been swimming naked."
##    ]
@app.route('/hello/<username>/')
def hello_user(username):
  quotes = Quotes.query.all()
  return render_template('hello_user.html', username=username, quote=random.choice(quotes))


## Define below a view function 'display_quotes', which returns an html string 
## that displays all the quotes present in 'quotes' list in a unordered list.
## Before displaying 'quotes' as an unordered list, the html string must also include a 'h1' header "Famous Quotes".
## The view function 'display_quotes' should be mapped to URL '/quotes/' .
## The view function must render the template 'quotes.html'
## Use the below list 'quotes' in 'display_quotes'  function
## quotes = [
##                "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
##                "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
##                "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
##                "Listen to many, speak to a few.",
##                "Only when the tide goes out do you discover who's been swimming naked."
##    ]
@app.route('/quotes/')
def display_quotes():
  quotes = Quotes.query.all()
  return render_template("quotes.html", quotes=quotes)

helloapp/templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Quotes App{%block title %} - Home{%endblock%}</title>
</head>
<body>
  {%block content %} - Home{%endblock%}
</body>
</html>

helloapp/templates/index.html

{%extends 'base.html'%}

{%block content%}
<h2>Hello World!!! I've run my first Flask application.</h2>
{%endblock%}

helloapp/templates/quotes.html

{%extends 'base.html'%}

{%block content%}
<h1>Famous Quotes</h1>
<ul>
{% for quote in quotes %}
<li>{{quote.quotestring}} - {{quote.quoteauthor}}</li>
{% endfor %}
</ul>
{%endblock%}

helloapp/templates/hello_user.html

{%extends 'base.html'%}

{%block content%}
<h2>Hello {{username}}</h2>
<h3>Quote of the Day</h3>
<p>{{quote.quotestring}} - {{quote.quoteauthor}}</p>
{%endblock%}

Creating Web Forms in Flask

Do the following tasks:

Task 1 : Set up the Environment

  • Once the virtual server is provided, click `Run -> Install` to install the required dependencies.

Task 2 : Define 'QuoteForm' class in 'forms.py'

  • The form must have two text fields named "Quote Author" and "Quote". The corresponding field names must be "qauthor" and "qstring" respectively.

  • The form must have a Submit button with value "Add Quote".

  • Include the following validations of both the text fields:
    • The length of the input string "Quote Author" must be between 3 and 100, and must display the message "[Field must be between 3 and 100 characters long.]" to the user.
    • If the "Quote Author" field has a null value, the message "[This field is required.]" must be displayed to the user.
    • The length of "Quote" must be between 3 and 200, and must display the message "[Field must be between 3 and 200 characters long.]" to the user.
    • If the "Quote" field has a null value, the message "[This field is required.]" must be displayed to the user.

Task 3 : Define 'addquote.html' Template in 'helloapp/templates' Folder

  • Define the template 'addquote.html' which takes the instance of the 'QuoteForm' as an input, and displays it to the user.
  • It must also display errors (if any).

Task 4 : Define 'addquote' View Function in 'helloapp/routes.py'

  • Define a view function named 'addquote' which renders the template 'addquote.html', and then displays the above defined QuoteForm.
  • The form must take a quote string and it's author as input, and submit it to the server.
  • If the data is valid, it must be inserted in the 'quotes' table.
  • Finally, it must render 'addquote_confirmation.html' after successful submission of data.
  • If a wrong input is found, the function must render the 'addquote.html' template, highlighting the wrong input fields.
  • Ensure that the view function 'addquote.html' is routed when a user accesses the URL '/addquote/'.

Task 5: View the Application

  • After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
  • Click PreviewApp to open the home page of the flask application in the HackerRank browser.
  • If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.

Task 6: Add and View Quotes

  • Access the page '/addquote/', and add a quote.
  • View all quotes by accessing the page '/quotes/'.

Task 7: Test the Application

  • Test the application by clicking 'Run -> Test'.
  • The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
  • If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.

Task 8: Submit the Solution

  • Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.

Git Instructions

Use the following commands to work with this project

export LC_ALL=C.UTF-8; export LANG=C.UTF-8; export FLASK_APP=main.py; flask run --host 0.0.0.0 --port 8000

py.test helloapp/tests.py

python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt

Solution

helloapp/routes.py

from flask import render_template, request
import random
from .models import Quotes
from .forms import QuoteForm
from helloapp import app, db


@app.route('/')
def hello():
    return render_template('index.html')


@app.route('/hello/<string:username>/')
def hello_user(username):

    quotes = Quotes.query.all()
    quotes = [quote.quotestring for quote in quotes]

    random_quote = random.choice(quotes)

    return render_template('hello_user.html', username=username, quote=random_quote)


@app.route('/quotes/')
def display_quotes():

    quotes = Quotes.query.all()
    quotes = [quote.quotestring for quote in quotes]

    return render_template('quotes.html', quotes=quotes)

# Define below a view function 'add_quote', which renders 'addquote.html' template that displays the form , QuoteForm
# The form takes a quote and it's author information and submit's it to server.
# The server process the input data and if found valid, the data is inserted into quotes table.
# and finally renders 'addquote_confirmation.html' template.
# In case if any error is found in input, it renders 'addquote.html' template highlighting errors.
# that displays all the quotes present in 'quotes' list in a unordered list.


@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
    form = QuoteForm()
    if request.method == 'POST' and form.validate_on_submit():
        quote = Quotes(quoteauthor=form.qauthor.data,
                       quotestring=form.qstring.data)
        try:
            db.session.add(quote)
            db.session.commit()
        except Exception:
            db.session.rollback()
        return render_template("addquote_confirmation.html", title="Quote Added")
    return render_template("addquote.html", form=form, title="Add Quote")

helloapp/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators

# Define QuoteForm below
class QuoteForm(FlaskForm):
  qauthor = StringField("Quote Author", validators=[validators.Length(3, 100), validators.DataRequired()])
  qstring = StringField("Quote", validators=[validators.Length(3, 200), validators.DataRequired()])
  submit = SubmitField("AddQuote")

helloapp/templates/addquote.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
  <h2>Quote Form</h2>
  <form action="" method="post">
    {{form.csrf_token}}
    {{ form.qauthor.label }} : {{ form.qauthor }} <br><br>
    {% for error in form.qauthor.errors %}
      <span style="color: red;">[{{ error }}]</span><br>
    {% endfor %}
    <br>
    {{ form.qstring.label }} : {{ form.qstring }} <br><br>
    {% for error in form.qstring.errors %}
      <span style="color: red;">[{{ error }}]</span><br>
    {% endfor %}
    <br>
    {{ form.submit }}
  </form>
</body>
</html>
Share: