"""
    Naam      : R. Wacanno
    UvAnetID  : 11741163
    Studie    : BSc Informatica

    exercises.py
    -Contains all exercise functions describes in
     Opgave 1, 2, 3a, 3b and 4
"""
import collections


def check_list(lst):
    """Returns TRUE if the given list contains all numbers from 1 to n,
    where n is the length of the given list"""
    return sorted(lst) == list(range(1, len(lst) + 1))


def gen_list(lst):
    """Returns a generator for all numbers from 1 to n, where n is the
    length of the given list which are not present in the given list."""
    return (x for x in list(range(1, len(lst) + 1)) if x not in lst)


def read_file(path):
    """Reads a grid of numbers, separated by spaces, from a file and
    returns a list with nested lists for each row of the file.
    These nested lists contain the numbers."""
    try:
        with open(path) as grid_file:
            return [[int(x) for x in line.split()] for line in grid_file]
    except NameError:
        print("Given file is invalid")
    except ValueError:
        print("File contains non-integers")


def list_to_string(lst):
    """Convers a list with nested lists to a string which represents
    a grid with eacht nested list as a row."""
    try:
        return "\n".join(" ".join(map(str, inner)) for inner in lst)
    except TypeError:
        print("Given list is invalid")


def sum_nested_it(lst):
    """Returns the sum of all numbers contained in a given
    list and its nested lists."""
    flat_list = []
    for elem in lst:
        if isinstance(elem, collections.Iterable):
            lst.extend(elem)
        else:
            flat_list.append(elem)
    return sum(flat_list)
