"""
Compute the mean and variance of a list, as well as find the minimum and maximum values.
"""

# List of numbers to calculate statistics on
l = [1, 7, 3, 2, 4]

# a.1) Calculate the mean of the list manually (without using built-in sum())
list_sum = 0

# Iterate through the list and accumulate the sum of all elements
for x in l:
    list_sum += x

# Calculate the mean by dividing the sum by the number of elements
list_mean = list_sum / len(l)

# Output the calculated mean
print(f"mean = {list_mean}")

# a.1) - Alternative approach: using Python's built-in sum() function to calculate the mean
list_mean = sum(l) / len(l)

# Output the calculated mean
print(f"mean (using sum function) = {list_mean}")

# a.2) Calculate the variance manually (variance = average of squared differences from the mean)
temp = 0

# Iterate through the list and compute the squared difference from the mean for each element
for x in l:
    temp += (x - list_mean) ** 2

# Calculate the variance by dividing the accumulated squared differences by the number of elements
list_variance = temp / (len(l) - 1)

# Output the calculated variance
print(f"variance = {list_variance}")

# a.2) - Alternative approach: using list comprehension to calculate variance more concisely
# This approach uses list comprehension inside sum() to get squared differences in a single line
temp = sum([(x - list_mean) ** 2 for x in l])

# Calculate the variance
list_variance = temp / (len(l) - 1)

# Output the calculated variance
print(f"variance (using list comprehension) = {list_variance}")

"""
Find the maximum and minimum elements of a list without using Python's built-in max() or min() functions.
"""

# Initialize the first element as the temporary maximum
temp = l[0]

# Iterate through the list and find the maximum value
for x in l:
    if x > temp:
        temp = x
maximum = temp

# Output the calculated maximum
print(f"maximum = {maximum}")

# Initialize the first element as the temporary minimum
temp = l[0]

# Iterate through the list and find the minimum value
for x in l:
    if x < temp:
        temp = x
minimum = temp

# Output the calculated minimum
print(f"minimum = {minimum}")

# b) - Alternative approach: find the minimum and maximum by sorting the list first
# Python's sorted() function performs a quicksort, returning a sorted version of the list
res = sorted(l)

# The first element in the sorted list is the minimum, and the last element is the maximum
maximum = res[-1]
minimum = res[0]

# Output the sorted list's maximum and minimum values
print(f"maximum, minimum (using a sorted list) = {maximum}, {minimum}")
