ASSIGNMENT 1¶

q1a

In [3]:
def convert_from_celcius_to_fahrenheit_with_input():
    celcius = float(input("Enter the temperature in celcius: "))
    fahrenheit = round(celcius * 1.8 + 32, 2)
    print("The temperature in fahrenheit is: ", fahrenheit)
In [4]:
convert_from_celcius_to_fahrenheit_with_input()
The temperature in fahrenheit is:  32.0
In [5]:
convert_from_celcius_to_fahrenheit_with_input()
The temperature in fahrenheit is:  212.0
In [6]:
convert_from_celcius_to_fahrenheit_with_input()
The temperature in fahrenheit is:  -40.0
In [7]:
convert_from_celcius_to_fahrenheit_with_input()
The temperature in fahrenheit is:  98.6

q1b

In [9]:
def convert_from_fahrenheit_by_array(celcius_array):
    fahrenheit_array = [round(c * 1.8 + 32,2) for c in celcius_array]
    print(f"{'Celsius':<10}{'Fahrenheit':<10}")
    print("-" * 20)
    for i in range(len(celcius_array)):
        print(f"{celcius_array[i]:<10}{fahrenheit_array[i]:<10}")
In [10]:
celcius_array = [20,21,22,23,24,25,26,27,28,29,30]
convert_from_fahrenheit_by_array(celcius_array)
Celsius   Fahrenheit
--------------------
20        68.0      
21        69.8      
22        71.6      
23        73.4      
24        75.2      
25        77.0      
26        78.8      
27        80.6      
28        82.4      
29        84.2      
30        86.0      

q2

By hand:

n=4:
s=0
for k in [1,4]
    s = s + 1 / (k^2)
end

k=1 => s = 0 + 1/(1) = 1
k=2 => s = 1 + 1/(4) = 5/4
k=3 => s = 5/4 + 1/(9) = 49/36
k=4 => s = 49/36 + 1/(16) = 205/144
In [17]:
def calculate_for_n(n):
    s=0
    for k in range(1,n+1):
        s += 1 / (k ** 2)
    print("Sum is:{}".format(s))
In [19]:
calculate_for_n(10)
calculate_for_n(100)
calculate_for_n(1000)
calculate_for_n(100000)
calculate_for_n(1000000)
calculate_for_n(10000000)
Sum is:1.5497677311665408
Sum is:1.6349839001848923
Sum is:1.6439345666815615
Sum is:1.6449240668982423
Sum is:1.64493306684877
Sum is:1.6449339668472596

As seen above the given series converges to 1.644934 ≈ π²/6 .

The given series is:

$$ S_n = \sum_{k=1}^{n} \frac{1}{k^2} = 1 + \frac{1}{4} + \frac{1}{9} + \frac{1}{16} + \frac{1}{25} + \cdots $$

Taking the limit of the series as n goes to infinity:

$$ \lim_{n \to \infty} S_n = \frac{\pi^2}{6} \approx 1.644934 $$

This is known as the Basel problem.

q3

By hand:

v=j=3 -> i=1+1=2 then i≠3

v=j=1 -> i=2+1=3 then i=3 -> i=3+2=5, m=5+1=6

v=j=5 -> i=5+1=6 then i≠3
In [20]:
v = [3, 1, 5]
i = 1
table = []

for j in v:
    i = i + 1
    if i == 3:
        i = i + 2
        m = i + j
    else:
        m = None
    table.append((i, j, m))

print(" i | j | m ")
print("---|---|---")
for row in table:
    print(f"{row[0]:2} | {row[1]:1} | {row[2]}")
 i | j | m 
---|---|---
 2 | 3 | None
 5 | 1 | 6
 6 | 5 | None

q4

In [21]:
def calculate_total_charge(consumption):
    if consumption <= 500:
        cost = consumption * 0.02 # 2 cents per unit
    elif consumption <= 1000:
        cost = 10 + (consumption - 500) * 0.05   # 10$ for first 500, 5 cents for excess
    else:  # consumption > 1000
        cost = 35 + (consumption - 1000) * 0.10  # 35$ for first 1000, 10 cents for excess
    total_charge = cost + 5
    print(f"Consumption: {consumption} units --> Total charge: ${total_charge:.2f}")
In [22]:
consumptions = [200, 500, 700, 1000, 1500]
for unit in consumptions:
    calculate_total_charge(unit)
Consumption: 200 units --> Total charge: $9.00
Consumption: 500 units --> Total charge: $15.00
Consumption: 700 units --> Total charge: $25.00
Consumption: 1000 units --> Total charge: $40.00
Consumption: 1500 units --> Total charge: $90.00

q5

In [23]:
import numpy as np
import matplotlib.pyplot as plt

def population(t):
    return 197273000 / (1 + np.exp(-0.03134 * (t - 1913.25)))

years = np.arange(1790, 2001, 10)
pop_values = population(years) # population array

for year, pop in zip(years, pop_values):
    print(f"Year {year}: Population ≈ {int(pop):,}")

plt.plot(years, pop_values, marker='o')
plt.xlabel("Year")
plt.ylabel("Population")
plt.title("US Population (1790-2000)")
plt.grid(True)
plt.show()
Year 1790: Population ≈ 4,059,821
Year 1800: Population ≈ 5,512,360
Year 1810: Population ≈ 7,464,515
Year 1820: Population ≈ 10,071,699
Year 1830: Population ≈ 13,524,627
Year 1840: Population ≈ 18,047,215
Year 1850: Population ≈ 23,885,550
Year 1860: Population ≈ 31,282,940
Year 1870: Population ≈ 40,437,014
Year 1880: Population ≈ 51,439,659
Year 1890: Population ≈ 64,210,378
Year 1900: Population ≈ 78,446,149
Year 1910: Population ≈ 93,617,527
Year 1920: Population ≈ 109,030,794
Year 1930: Population ≈ 123,947,285
Year 1940: Population ≈ 137,719,544
Year 1950: Population ≈ 149,893,845
Year 1960: Population ≈ 160,248,473
Year 1970: Population ≈ 168,770,426
Year 1980: Population ≈ 175,596,210
Year 1990: Population ≈ 180,945,498
Year 2000: Population ≈ 185,066,481
No description has been provided for this image
In [24]:
# Steady state check
delta = np.diff(pop_values)
steady_state_years = years[1:][delta < 1]  # check if the diff is less than 1 person
if len(steady_state_years) > 0:
    print("Population approximately reaches steady state around years:", steady_state_years)
else:
    print("Population does not reach a true steady state within given range.")
Population does not reach a true steady state within given range.

q6

In [25]:
import cmath
import math

def solve_quadratic(a, b, c):
    if a == 0:
        if b == 0:
            if c == 0:
                print("Solution indeterminate")
            else:
                print("There is no solution")
        else:
            # Linear equation bx + c = 0
            x = -c / b
            print(f"Linear equation, one root: x = {x}")
    else:
        discriminant = b**2 - 4*a*c

        if discriminant < 0:
            print("Complex roots")
            x1 = (-b + cmath.sqrt(discriminant)) / (2*a)
            x2 = (-b - cmath.sqrt(discriminant)) / (2*a)
            print(f"x1 = {x1}, x2 = {x2}")
        elif discriminant == 0:
            x = -b / (2*a)
            print(f"Equal roots: x = {x}")
        else:
            x1 = (-b + math.sqrt(discriminant)) / (2*a)
            x2 = (-b - math.sqrt(discriminant)) / (2*a)
            print(f"Distinct real roots: x1 = {x1}, x2 = {x2}")
In [26]:
solve_quadratic(1, 1, 1)
Complex roots
x1 = (-0.5+0.8660254037844386j), x2 = (-0.5-0.8660254037844386j)
In [27]:
solve_quadratic(2, 4, 2)
Equal roots: x = -1.0
In [28]:
solve_quadratic(2, 2, -12)
Distinct real roots: x1 = 2.0, x2 = -3.0

q7

In [30]:
x = np.linspace(-10, 10, 400)

# for c = 5
c1 = 5
y1 = np.cosh(x / c1)

# for c = 4
c2 = 4
y2 = np.cosh(x / c2)

# Plot
plt.plot(x, y1, label='c = 5')
plt.plot(x, y2, label='c = 4', linestyle='--')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Uniform Catenary y = cosh(x/c)')
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

q8

Turkish Lira Change Algorithm¶

Turkish Lira¶

Banknotes: 100₺, 50₺, 20₺, 10₺, 5₺, 1₺

Coins: 50 kuruş (0.5₺), 25 kuruş (0.25₺), 10 kuruş (0.10₺), 5 kuruş (0.05₺), 1 kuruş (0.01₺)


Algorithm: Giving Change from a 100₺ Note¶

Start with the largest denomination to minimize total number of banknotes and coins; round fractional parts to the nearest kuruş.

Input: cost, 0 ≤ cost < 100₺

Step 1: Compute total change

  • change = 100 - cost

Step 2: Initialize counters for each denomination

  • notes_50 = notes_20 = notes_10 = notes_5 = notes_1 = 0
  • coin_50 = coin_25 = coin_10 = coin_5 = coin_1 = 0

Step 3: Handle banknotes (largest first)

  • While change ≥ 50₺ → subtract 50, increment notes_50
  • While change ≥ 20₺ → subtract 20, increment notes_20
  • While change ≥ 10₺ → subtract 10, increment notes_10
  • While change ≥ 5₺ → subtract 5, increment notes_5
  • While change ≥ 1₺ → subtract 1, increment notes_1

Step 4: Handle coins -> kurus = round(change * 100)

  • While kurus ≥ 50 → subtract 50, increment coin_50
  • While kurus ≥ 25 → subtract 25, increment coin_25
  • While kurus ≥ 10 → subtract 10, increment coin_10
  • While kurus ≥ 5 → subtract 5, increment coin_5
  • While kurus ≥ 1 → subtract 1, increment coin_1

Step 5: Output

  • Display the number of each banknote and coin
In [42]:
def give_change(cost):
    if cost >= 100 or cost < 0:
        return "Invalid cost, must be between 0 and 100₺"

    change = 100 - cost

    change_dict = {
        "50 TL": 0,
        "20 TL": 0,
        "10 TL": 0,
        "5 TL": 0,
        "1 TL": 0,
        "50 kuruş": 0,
        "25 kuruş": 0,
        "10 kuruş": 0,
        "5 kuruş": 0,
        "1 kuruş": 0
    }

    for value, key in [(50, "50 TL"), (20, "20 TL"), (10, "10 TL"),
                       (5, "5 TL"), (1, "1 TL")]:
        count = int(change // value)
        change -= count * value
        change_dict[key] = count

    cents = round(change * 100)
    for value, key in [(50, "50 kuruş"), (25, "25 kuruş"), (10, "10 kuruş"),
                       (5, "5 kuruş"), (1, "1 kuruş")]:
        count = cents // value
        cents -= count * value
        change_dict[key] = int(count)

    return change_dict
In [46]:
input = 37.68
change = 100 - input
print(f"\nChange to give from 100 TL: {change} TL")
change = give_change(input)
for denom, num in change.items():
    if num != 0:
        print(f"{denom}: {num}")
Change to give from 100 TL: 62.32 TL
50 TL: 1
10 TL: 1
1 TL: 2
25 kuruş: 1
5 kuruş: 1
1 kuruş: 2
In [47]:
input = 73.25
change = 100 - input
print(f"\nChange to give from 100 TL: {change} TL")
change = give_change(input)
for denom, num in change.items():
    if num != 0:
        print(f"{denom}: {num}")
Change to give from 100 TL: 26.75 TL
20 TL: 1
5 TL: 1
1 TL: 1
50 kuruş: 1
25 kuruş: 1
In [49]:
input = 99.99
change = round(100 - input,2)
print(f"\nChange to give from 100 TL: {change} TL")
change = give_change(input)
for denom, num in change.items():
    if num != 0:
        print(f"{denom}: {num}")
Change to give from 100 TL: 0.01 TL
1 kuruş: 1