# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
# -*- coding: utf-8 -*-
import math
from statistics import mean, median, mode, variance, stdev
from collections import Counter
### Level 1: Basic Functions
def add_two_numbers(a, b):
return a + b
def area_of_circle(r):
return math.pi * r * r
def add_all_nums(*args):
if not all(isinstance(i, (int, float)) for i in args):
return "Error: all arguments must be numbers"
return sum(args)
def convert_celsius_to_fahrenheit(c):
return (c * 9/5) + 32
def check_season(month):
m = month.strip().lower()
if m in ('september', 'october', 'november'):
return 'Autumn'
elif m in ('december', 'january', 'february'):
return 'Winter'
elif m in ('march', 'april', 'may'):
return 'Spring'
elif m in ('june', 'july', 'august'):
return 'Summer'
return 'Invalid month'
def calculate_slope(x1, y1, x2, y2):
if x2 == x1:
return float('inf')
return (y2 - y1) / (x2 - x1)
def solve_quadratic_eqn(a, b, c):
d = b**2 - 4*a*c
if d < 0:
return []
root1 = (-b + math.sqrt(d)) / (2*a)
root2 = (-b - math.sqrt(d)) / (2*a)
return [root1] if d == 0 else [root1, root2]
def print_list(lst):
for el in lst:
print(el)
def reverse_list(lst):
rev = []
for i in range(len(lst)-1, -1, -1):
rev.append(lst[i])
return rev
def capitalize_list_items(lst):
return [str(item).capitalize() for item in lst]
def add_item(lst, item):
lst.append(item)
return lst
def remove_item(lst, item):
if item in lst:
lst.remove(item)
return lst
def sum_of_numbers(n):
return sum(range(n + 1))
def sum_of_odds(n):
return sum(i for i in range(n + 1) if i % 2)
def sum_of_even(n):
return sum(i for i in range(n + 1) if i % 2 == 0)
### Level 2: Intermediate Functions
def evens_and_odds(n):
evens = len([i for i in range(n + 1) if i % 2 == 0])
odds = (n + 1) - evens
print(f"The number of odds are {odds}.")
print(f"The number of evens are {evens}.")
def factorial(n):
if n < 0:
raise ValueError("n must be >= 0")
return 1 if n < 2 else n * factorial(n - 1)
def is_empty(x):
return not bool(x)
def calculate_mean(lst):
return mean(lst)
def calculate_median(lst):
return median(lst)
def calculate_mode(lst):
try:
return mode(lst)
except:
return "No unique mode"
def calculate_range(lst):
return max(lst) - min(lst)
def calculate_variance(lst):
return variance(lst)
def calculate_std(lst):
return stdev(lst)
### Level 3: Advanced Functions
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def all_unique(lst):
return len(lst) == len(set(lst))
def same_data_type(lst):
return all(isinstance(x, type(lst[0])) for x in lst)
def is_valid_variable(name):
return name.isidentifier()
# Country data exercises
# Usage: need countries_data.py with a list named 'countries_data'
try:
from countries_data import countries_data
def most_spoken_languages(n=10):
counts = Counter(lang for c in countries_data for lang in c.get('languages', []))
return [lang for lang, _ in counts.most_common(n)]
def most_populated_countries(n=10):
sorted_c = sorted(countries_data, key=lambda x: x.get('population', 0), reverse=True)
return [ {'country': c['name'], 'population': c['population']} for c in sorted_c[:n] ]
except ImportError:
countries_data = []
def most_spoken_languages(n=10):
raise ImportError("countries_data.py not found")
def most_populated_countries(n=10):
raise ImportError("countries_data.py not found")
### --> Example usage below this line
if __name__ == "__main__":
# Quick tests
print("add_two_numbers:", add_two_numbers(3, 4))
print("area_of_circle:", round(area_of_circle(2), 2))
print("add_all_nums:", add_all_nums(1, 2, 3.5))
print("C→F:", convert_celsius_to_fahrenheit(0))
print("Season for 'July':", check_season("July"))
print("Slope:", calculate_slope(2, 3, 5, 11))
print("Quadratic roots of x²−5x+6:", solve_quadratic_eqn(1, -5, 6))
print("Reverse:", reverse_list([1, 2, 3, 4, 5]))
evens_and_odds(100)
nums = [1, 2, 2, 3, 4, 4, 4]
print("Mean/Median/Mode/Range:", calculate_mean(nums), calculate_median(nums),
calculate_mode(nums), calculate_range(nums))
print("Is prime 29:", is_prime(29))