Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions calculator_app/Question 2 and 3.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
{
"cells": [
{
"cell_type": "markdown",
"source": [
"Question 2 : Examine the code\n",
"First, we define a check_array function with input as an argument. We iterate and check each time if the first character of each element is 1. If it is, we assign the value none and return the modified input list. Then, we create the object original_array and we call the check_array function with the original_array as an argument before printing both the original array and the new array which should assign the returned value to new_array. Here, when we call check_array it is the reference to original_array which is passed. \n",
"In the lecture 3, we saw the concepts of pointers, garbage collection and passing by value and by reference. Here, this last concept is important since we need to differentiate passing by value which would mean passing the data itself, from passing by reference, which would pass a pointer to data. Here, the variable is referenced to objects which are in memory and when passing a list to a function, we are passing the reference to the list. Thus, not only the final list will be modified inside the function but also the original list outside the function. Thus, when the function check_array is applied to our original array and that the element, if it is 1 is passed to None, the original list referenced is modified by both original_array and new_array once we called check_array. For 1_3, the first character is a 1 which will be replaced with None both in the list referenced by both original_array and new_array. However, for 5_2, it will remain unchanged. Thus, the output will be [None, '5_2'] [None, '5_2']. "
],
"metadata": {
"collapsed": false
},
"id": "77530f474d4464c7"
},
{
"cell_type": "markdown",
"source": [
"Question 3 : Considering the algorithm, which takes an array (assumed to be non-empty) named array and finds the subarray (contiguous elements of that array of any size) with the largest sum and outputs that sum. Is the algorithm defined above ”efficient” in the sense we defined in lecture 5 (slide 30)? That is, is its runtime polynomial in the size of the array? If not, explain why not. If it is, give the runtime in Big-O notation with the smallest d such that O(nd) is true.\n",
"\n",
"In the Lecture 3, we defined an Algorithm as efficient if its runtime is polynomial ie if the runtime grows no faster than a polynomial function of input size. \n",
"In this code, the algorithm iterates over each element of the non-empty array and then for each element, iterates over the array and calculate the sum of the subarray starting from the first index of the outer loop tio the current index of the inner loop. If the sum given is greater than the max_sum it updates max_sum. Here, we have an outer loop and a inner loop (nested loop). The outer loop iterates the same number of times as the length of the input array. The inner loop iterates also the number of times as the length of the array, but the starting index changes with each iteration of the outer loop ie n times for the first iteration, n-1 for the second ... and one for the last iteration. The outer loop controls the number of times the inner loop will execute. Thus, if we say that the length of the array is n we will have n(n+1)/2 iterations. In O notation, it gives O(n2). The runtime complexity of the algorithm is O(n2) where n is the input array. Thus, we meet the criteria of efficiency defined in the class. However, it could be more efficient if with lower polynomial degree. \n"
],
"metadata": {
"collapsed": false
},
"id": "a6c3d5c4a5a5ac57"
},
{
"cell_type": "code",
"execution_count": null,
"id": "initial_id",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"collapsed": false
},
"id": "8b8f24c4b17ec595"
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"collapsed": false
},
"id": "1e1a487c35d4bb3b"
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"collapsed": false
},
"id": "eb47194c85030014"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Binary file added calculator_app/__pycache__/circle.cpython-311.pyc
Binary file not shown.
Binary file added calculator_app/__pycache__/circle.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file added calculator_app/__pycache__/helper.cpython-312.pyc
Binary file not shown.
Binary file not shown.
48 changes: 48 additions & 0 deletions calculator_app/circle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# create function to calculate the perimeter of a circle by inputting the radius
import math
import unittest


# create helper functions for calculations


def circle_calculation(value1: float, operation: str) -> float:
"""
Perform a mathematical operation on two values.

Parameters:
value1 (float): radius

operation (str): The operation to perform. Can be 'area', 'perimeter"

Returns:
float: The result of the operation.

Raises:
ZeroDivisionError: If attempting to divide by zero.
"""
if operation == 'Area':
result = math.pi * value1 ** 2 # πr^2
else:
result = 2 * math.pi * value1 # 2πr

return result


def convert_to_float(value: str) -> float:
"""
Convert string to floating point number.

Parameters:
value (str): The value to convert.

Returns:
float: The converted float value of input value.

Raises:
ValueError: If value cannot be converted to a float.
"""

float_value = float(value)

return float_value
70 changes: 70 additions & 0 deletions calculator_app/flask_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from flask import Flask, render_template, request

from helper import perform_calculation, convert_to_float
from circle import circle_calculation, convert_to_float


app = Flask(__name__) # create the instance of the flask class


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


@app.route('/calculate', methods=['GET', 'POST']) # associating the GET and POST method with this route
def calculate():
if request.method == 'POST':
# using the request method from flask to request the values that were sent to the server through the POST method
value1 = request.form['value1']
value2 = request.form['value2']
operation = str(request.form['operation'])

# make sure the input is one of the allowed inputs (not absolutely necessary in the drop-down case)
if operation not in ['add', 'subtract', 'divide', 'multiply']:
return render_template('calculator.html',
printed_result='Operation must be one of "add", "subtract", "divide", or "multiply".')

try:
value1 = convert_to_float(value=value1)
value2 = convert_to_float(value=value2)
except ValueError:
return render_template('calculator.html', printed_result="Cannot perform operation with this input")

try:
result = perform_calculation(value1=value1, value2=value2, operation=operation)
#result = perform_calculation(value1=value1, operation=operation)
return render_template('calculator.html', printed_result=str(result))

except ZeroDivisionError:
return render_template('calculator.html', printed_result="You cannot divide by zero")

return render_template('calculator.html')


@app.route('/circle_calculator', methods=['GET', 'POST']) # associating the GET and POST method with this route
def perimeter():
if request.method == 'POST':
# using the request method from flask to request the values that were sent to the server through the POST method
value1 = request.form['value1']
operation = str(request.form['operation'])

# make sure the input is one of the allowed inputs (not absolutely necessary in the drop-down case)
if operation not in ['Area', 'Perimeter']:
return render_template('circle_calculator.html',
printed_result='Operation must be one of "Area", "Perimeter".')

try:
value1 = convert_to_float(value=value1)
except ValueError:
return render_template('circle_calculator.html', printed_result="Cannot perform operation with this input")

try:
result = circle_calculation(value1=value1, operation=operation)
return render_template('circle_calculator.html', printed_result=str(result))

except ZeroDivisionError:
return render_template('circle_calculator.html', printed_result="You cannot divide by zero")

return render_template('circle_calculator.html')
47 changes: 47 additions & 0 deletions calculator_app/helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# create helper functions for calculations


def perform_calculation(value1: float, value2: float, operation: str) -> float:
"""
Perform a mathematical operation on two values.

Parameters:
value1 (float): The first value.
value2 (float): The second value.
operation (str): The operation to perform. Can be 'add', 'subtract', 'divide', or 'multiply'.

Returns:
float: The result of the operation.

Raises:
ZeroDivisionError: If attempting to divide by zero.
"""
if operation == 'add':
result = value1 + value2
elif operation == 'subtract':
result = value1 - value2
elif operation == 'divide':
result = value1 / value2
else:
result = value1 * value2

return result


def convert_to_float(value: str) -> float:
"""
Convert string to floating point number.

Parameters:
value (str): The value to convert.

Returns:
float: The converted float value of input value.

Raises:
ValueError: If value cannot be converted to a float.
"""

float_value = float(value)

return float_value
99 changes: 99 additions & 0 deletions calculator_app/static/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/* Global Styles */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f8f9fa;
color: #333;
margin: 0;
padding: 0;
}

.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}

/* Header Styles */
header {
background-color: #343a40; /* Dark neutral color for header */
color: #fff; /* Light text color for header */
padding: 10px 0;
}

#navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 20px;
padding-right: 20px;
}

.logo {
margin: 0;
font-size: 24px;
}

.menu {
list-style-type: none;
padding: 0;
}

.menu li {
display: inline-block;
margin-right: 20px;
}

.menu li a {
color: #fff;
text-decoration: none;
font-weight: bold;
font-size: 18px;
}

h1 a {
color: #ffc8dd;
}

h1 a:hover {
color: #ffafcc;
}

.menu li a:hover {
color: #bde0fe; /* Light pastel color on hover */
}

/* Calculator Styles */
h1 {
text-align: center;
margin-top: 0;
font-size: 36px;
color: #343a40; /* Dark neutral color for heading */
}

form {
max-width: 400px;
margin: 0 auto;
}

input[type="text"],
select,
button {
margin: 10px 0;
padding: 10px;
width: 100%;
box-sizing: border-box;
font-size: 16px;
}

button {
background-color: #343a40; /* Dark neutral color for button */
color: #fff;
border: none;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease; /* Smooth transition for background color change */
}

button:hover {
background-color: #23272b; /* Slightly darker color on hover */
}
23 changes: 23 additions & 0 deletions calculator_app/templates/calculator.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{% extends 'layout.html' %}
{% block content %}
<h1>Calculator</h1>
<form method="post">
<input type="text" name="value1" placeholder="Enter the first number" required="required" />
<input type="text" name="value2" placeholder="Enter the second number" required="required" />

<label for="operation">Operation</label>
<select id="operation" name="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="divide">Divide</option>
<option value="multiply">Multiply</option>
</select>

<button type="submit">Calculate</button>
</form>

<br>

{{ printed_result }}

{% endblock %}
Loading