Categories:Viewed: 13 - Published at: a few seconds ago

Write a python function that would read the given input file path and print its contents

def read_and_print_file(filepath):
    with open(filepath, "r") as infile:
        print( infile.read() )

Write a python program that would print the first n positive integers using a for loop

n = 62
for num in range(n):
    print(num)

Write a python function that returns the input list sorted in ascending order

def sort_ascending(list_to_be_sorted):
    return sorted(list_to_be_sorted)

Write a python function that returns the input list sorted in descending order

def sort_descending(list_to_be_sorted):
    return sorted(list_to_be_sorted, reverse=True)

Write a python function that would return the sum of first n natural numbers, where n is the input

def sum_first_n(n):
    return ( n * (n+1) ) // 2

Write a recursive python function that would return the sum of first n natural numbers, where n is the input

def sum_first_n_recursive(n):
    if n == 0:
        return 0
    return sum_first_n_recursive(n-1) + n

Write a python function that would filter a list of dictionaries where a specified key equals given value, listofdictionaries, key and value are inputs to this function.

def filter_with_key_value(list_of_dicts, key, value):
    return list( filter( lambda x: x.get(key) == value, list_of_dicts ) )

Write a recursive python function that takes either a list or tuple as input and reverses the order of its elements

def reverse(seq):
    SeqType = type(seq)
    emptySeq = SeqType()
    if seq == emptySeq:
        return emptySeq
    restrev = reverse(seq[1:])
    first = seq[0:1]
    result = restrev + first
    return result

Write a python function that returns the square of a given input number

def square(x):
    return x**2

Write a python function that performs selection sort on the given list or tuple or string and returns the new sorted sequence

def selection_sort(list_to_be_sorted):
    sorted_list = list_to_be_sorted[:]
    for i in range(len(sorted_list)):
        new_min = sorted_list[i]
        new_min_old_place = i
        for j in range(i+1, len(sorted_list)):
            if new_min > sorted_list[j]:
                new_min = sorted_list[j]
                new_min_old_place = j
        old_val = sorted_list[i]
        sorted_list[i] = new_min
        sorted_list[new_min_old_place] = old_val
    return sorted_list