Unlock the world of Backend development with ALX! Dive into Python and access expert solutions, guides, and explanations for ALX tasks. Supercharge your learning journey and excel in your projects. 
#!/usr/bin/env python3
"""Write a type-annotated function add that takes a float a and a
float b as arguments and returns their sum as a float.
"""


def add(a: float, b: float) -> float:
    """Add two floats"""
    return (a + b)

0x00-python_variable_annotations/0-add.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Augment the following code with the correct duck-typed annotations:

# The types of the elements of the input are not know
def safe_first_element(lst):
    if lst:
        return lst[0]
    else:
        return None

{'lst': typing.Sequence[typing.Any], 'return': \
    typing.Union[typing.Any, NoneType]}
"""


import typing


def safe_first_element(lst: typing.Sequence[typing.Any]) -> \
        typing.Union[typing.Any, None]:
    """Duck-typed annotation"""
    if lst:
        return lst[0]
    else:
        return None

0x00-python_variable_annotations/100-safe_first_element.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Given the parameters and the return values, add type
annotations to the function

Hint: look into TypeVar

def safely_get_value(dct, key, default = None):
    if key in dct:
        return dct[key]
    else:
        return default
"""


import typing


T = typing.TypeVar('T')


def safely_get_value(dct: typing.Mapping, key: typing.Any, default:
                     typing.Union[T, None] = None) -> \
        typing.Union[typing.Any, T]:
    """annotations of the function"""
    if key in dct:
        return dct[key]
    else:
        return default

0x00-python_variable_annotations/101-safely_get_value.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Use mypy to validate the following piece of code
and apply any necessary changes.
"""

from typing import Tuple, List, Any


def zoom_array(lst: Tuple, factor: int = 2) -> List:
    """Corrected annotations"""
    zoomed_in: List = [
        item for item in lst
        for i in range(factor)
    ]
    return zoomed_in


array = (12, 72, 91)

zoom_2x = zoom_array(array)

zoom_3x = zoom_array(array, 3)

0x00-python_variable_annotations/102-type_checking.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function floor which takes a float
n as argument and returns the floor of the float.
"""


def floor(n: float) -> int:
    """Returns the floor of the float"""
    return int(n)

0x00-python_variable_annotations/2-floor.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function to_str that takes a float n
as argument and returns the string representation of the float.
"""


def to_str(n: float) -> str:
    """Returns the string representation of the float"""
    return str(n)

0x00-python_variable_annotations/3-to_str.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function sum_list which takes a list
input_list of floats as argument and returns their sum as a float.
"""


from typing import List


def sum_list(input_list: List[float]) -> float:
    '''returns their sum as a float
    '''
    return float(sum(input_list))

0x00-python_variable_annotations/5-sum_list.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function sum_mixed_list which takes a list
mxd_lst of integers and floats and returns their sum as a float.
"""

import typing


def sum_mixed_list(mxd_lst: typing.List[typing.Union[int, float]]) -> float:
    """Returns the sum of the list as a float"""
    return float(sum(mxd_lst))

0x00-python_variable_annotations/6-sum_mixed_list.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function to_kv that takes a string k
and an int OR float v as arguments and returns a tuple.The first
element of the tuple is the string k. The second element is the
square of the int/float v and should be annotated as a float.
"""


import typing


def to_kv(k: str, v: typing.Union[int, float]) -> typing.Tuple[str, float]:
    """returns a tuple of the string & square of v as float"""
    return (k, float(v * v))

0x00-python_variable_annotations/7-to_kv.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a type-annotated function make_multiplier that takes
a float multiplier as argument and returns a function that
multiplies a float by multiplier.
"""


import typing


def make_multiplier(multiplier: float) -> typing.Callable[[float], float]:
    """Returns a function that multiplies a float by multiplier"""
    def float_multiply(x: float) -> float:
        return multiplier * x

    return float_multiply

0x00-python_variable_annotations/8-make_multiplier.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Annotate the below function’s parameters and return
values with the appropriate types

def element_length(lst):
    return [(i, len(i)) for i in lst]

{'lst': typing.Iterable[typing.Sequence], 'return': \
    typing.List[typing.Tuple[typing.Sequence, int]]}
"""


import typing


def element_length(lst: typing.Iterable[typing.Sequence]) -> \
        typing.List[typing.Tuple[typing.Sequence, int]]:
    """Returns a list of tuples"""
    return [(i, len(i)) for i in lst]

0x00-python_variable_annotations/9-element_length.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write an asynchronous coroutine that takes in an integer argument
(max_delay, with a default value of 10) named wait_random that waits
for a random delay between 0 and max_delay (included and float value)
seconds and eventually returns it.

Use the random module.
"""


import random
import asyncio


async def wait_random(max_delay: int = 10) -> float:
    """Wait for some time"""
    wait_time = random.random() * max_delay
    await asyncio.sleep(wait_time)
    return wait_time

0x01-python_async_function/0-basic_async_syntax.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Import wait_random from the previous python file that you’ve
written and write an async routine called wait_n that takes in 2
int arguments (in this order): n and max_delay. You will spawn
wait_random n times with the specified max_delay.

wait_n should return the list of all the delays (float values).
The list of the delays should be in ascending order without using
sort() because of concurrency.
"""


import asyncio
from typing import List
wait_random = __import__('0-basic_async_syntax').wait_random


async def wait_n(n: int, max_delay: int) -> List[float]:
    """Spawn wait_random n times"""
    tasks = []
    delays = []

    for i in range(n):
        task = wait_random(max_delay)
        tasks.append(task)

    for task in asyncio.as_completed((tasks)):
        delay = await task
        delays.append(delay)

    return delays

0x01-python_async_function/1-concurrent_coroutines.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""From the previous file, import wait_n into 2-measure_runtime.py.

Create a measure_time function with integers n and max_delay as
arguments that measures the total execution time for wait_n(n, max_delay),
and returns total_time / n. Your function should return a float.

Use the time module to measure an approximate elapsed time.
"""


import time
import asyncio
wait_n = __import__('1-concurrent_coroutines').wait_n


def measure_time(n: int, max_delay: int) -> float:
    """Returns total execution time"""
    start_time = time.time()
    asyncio.run(wait_n(n, max_delay))
    end_time = time.time()

    total_time = end_time - start_time
    return (total_time/n)

0x01-python_async_function/2-measure_runtime.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Import wait_random from 0-basic_async_syntax.

Write a function (do not create an async function, use the regular
function syntax to do this) task_wait_random that takes an integer
max_delay and returns a asyncio.Task.
"""


import asyncio
wait_random = __import__('0-basic_async_syntax').wait_random


def task_wait_random(max_delay: int) -> asyncio.Task:
    """Returns a asyncio.Task"""
    return asyncio.create_task(wait_random(max_delay))

0x01-python_async_function/3-tasks.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Take the code from wait_n and alter it into a new function
task_wait_n. The code is nearly identical to wait_n except
task_wait_random is being called.
"""


import asyncio
from typing import List
task_wait_random = __import__('3-tasks').task_wait_random


async def task_wait_n(n: int, max_delay: int) -> List[float]:
    """Spawn wait_random n times"""
    tasks = []
    delays = []

    for i in range(n):
        task = task_wait_random(max_delay)
        tasks.append(task)

    for task in asyncio.as_completed((tasks)):
        delay = await task
        delays.append(delay)

    return delays

0x01-python_async_function/4-tasks.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Write a coroutine called async_generator that takes no arguments.

The coroutine will loop 10 times, each time asynchronously wait 1 second,
then yield a random number between 0 and 10. Use the random module.
"""


import asyncio
import random
from typing import Generator


async def async_generator() -> Generator[float, None, None]:
    """Loop 10 times, wait 1 sec each time"""
    for i in range(10):
        await asyncio.sleep(1)
        yield random.random() * 10

0x02-python_async_comprehension/0-async_generator.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Import async_generator from the previous task and then write a coroutine
called async_comprehension that takes no arguments.

The coroutine will collect 10 random numbers using an async comprehensing
over async_generator, then return the 10 random numbers.
"""


from typing import List
async_generator = __import__('0-async_generator').async_generator


async def async_comprehension() -> List[float]:
    """Return the 10 random numbers"""
    results = [i async for i in async_generator()]
    return results

0x02-python_async_comprehension/1-async_comprehension.py
Innocentsax/alx-backend-python
#!/usr/bin/env python3
"""Import async_comprehension from the previous file and
write a measure_runtime coroutine that will execute async_comprehension
four times in parallel using asyncio.gather.

measure_runtime should measure the total runtime and return it.

Notice that the total runtime is roughly 10 seconds, explain it to yourself.
"""


import time
import asyncio
async_comprehension = __import__('1-async_comprehension').async_comprehension


async def measure_runtime() -> float:
    """Measure the total runtime"""
    start_time = time.time()

    await asyncio.gather(*(async_comprehension() for i in range(4)))

    end_time = time.time()
    return end_time - start_time

0x02-python_async_comprehension/2-measure_runtime.py
Innocentsax/alx-backend-python