Python: Functions (Solutions)ΒΆ

  1. Solution: the same type of the value I pass to the function! The function returns the value of the argument without any change.

    1. an integer.
    2. a dictionary.
    3. a list.
    4. a rational.
  2. Solution: the sum, or concatenation, of the two arguments, therefore:

    1. an integer.
    2. a list.
    3. a string.
  3. Solution:

    def print_even_odd(number):
        if number % 2 == 0:
            print "even"
        else:
            print "odd"
    
    print_even_odd(98)
    print_even_odd(99)
    

    Note that print_even_odd() already prints to screen, it’s not necessary to write:

    print print_even_odd(99)
    

    otherwise Python will print:

    even
    None
    

    The None comes from the additional print. Since print_even_odd() doesn’t have a return, its result will always be None. The additional print prints exactly this None.

  4. Solution:

    def determine_even_odd(number):
        if number % 2 == 0:
            return "even"
        else:
            return "odd"
    
    print determine_even_odd(98)
    print determine_even_odd(99)
    

    In this example, since there is no print inside determine_even_odd(), it’s necessary to add an additional print in order to print the result.

  5. Solution:

    def check_alphanumeric(string):
        alphanumeric_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
        alphanumeric_flag = True
        for character in string:
            if not character.upper() in alphanumeric_chars:
                alphanumeric_flag = False
    
        return alphanumeric_flag
    
    # Let's test the function
    print check_alphanumeric("ABC123")
    print check_alphanumeric("A!%$*@")
    

    We can also use break to interrupt the for cycle as soon as we find a non-alphanumeric character (once we find a non-alphanumeric character, it is impossible that alphanumeric_flag returns to True again):

    def check_alphanumeric(string):
        alphanumeric_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
        alphanumeric_flag = True
        for character in string:
            if not character.upper() in alphanumeric_chars:
                alphanumeric_flag = False
                break # <-- exit from the cycle
        return alphanumeric_flag
    
    # Let's test the function
    print check_alphanumeric("ABC123")
    print check_alphanumeric("A!%$*@")
    

    Alternatively, since upon executing break we directly arrive to return, we can skip a step and write directly return:

    def check_alphanumeric(string):
        alphanumeric_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
        for character in string:
            if not character.upper() in alphanumeric_chars:
                # upon meetin a not alphanumeric character,
                                # we can answer False
                return False
    
        # we arrive to the end of the for cycle only if `return` was never executed,
        # this happens only if the `if` condition has always been False for all characters
        # this means that all characters were alphanumeric
        # we can answer True
        return True
    
    # Let's test the function
    print check_alphanumeric("ABC123")
    print check_alphanumeric("A!%$*@")
    
  6. Solution:

    def question():
        path = raw_input("write a path: ")
        print open(path).readlines()
    
    # Let's test the function
    question()
    
  7. Solution:

    def wc(string):
        num_chars = len(string)
        num_newlines = string.count("\n")
        num_words = len(string.split()) # split splits upon both spaces and newlines
        return (num_chars, num_newlines, num_words)
    
    # Let's test the function
    print wc("I am\nan awesome\nstring")
    
  8. Solution:

    def print_dictionary(a_dictionary):
        # here the printing order doesn't matter,
        # we can use the natural order provided by
        # `items()`
        for key, value in a_dictionary.items():
            print key, "->", (str(value * 100.0) + "%")
    
    # Let's test the function
    
    dictionary = {
        "Arg": 0.7,
        "Lys": 0.1,
        "Cys": 0.1,
        "His": 0.1,
    }
    
    print_dictionary(dictionary)
    
  9. Solution:

    def print_ordered_dictionary(a_dictionary):
        # extract and order keys
        ordered_keys = a_dictionary.keys()
        ordered_keys.sort()
    
        # now let's print key-value pairs in the correct order
        for key in ordered_keys:
            value = a_dictionary[key]
    
            print key, "->", (str(value * 100.0) + "%")
    
    # Let's test the function
    
    dictionary = {
        "Arg": 0.7,
        "Lys": 0.1,
        "Cys": 0.1,
        "His": 0.1,
    }
    
    print_ordered_dictionary(dictionary)
    
  10. Solution:

    # taken from the example
    def factorial(n):
        fact = 1
        for k in range(1, n+1):
            fact = fact * k
        return fact
    
    def create_list_of_factorials(n):
        list_of_factorials = []
        for i in range(n):
            list_of_factorials.append(factorial(i))
        return list_of_factorials
    
    # Let's test the function
    print create_list_of_factorials(2)
    print create_list_of_factorials(4)
    print create_list_of_factorials(6)
    

    here we reused the function factorial() defined in a previous example.

  11. Solution:

    def count_character(text, search_char):
        counts = 0
        for character in text:
            if character == search_char:
                counts += 1
        return counts
    
    # Let's test the function
    print count_character("abbaa", "a")
    print count_character("abbaa", "b")
    print count_character("abbaa", "?")
    

    or, more simply, we can use count():

    def count_character(text, search_char):
        return text.count(search_char)
    
    # Let's test the function
    print count_character("abbaa", "a")
    print count_character("abbaa", "b")
    print count_character("abbaa", "?")
    
  12. Solution:

    def count_characters(text, search_chars):
        counts = {}
        for search_char in search_chars:
            counts[search_char] = count_character(text, search_char)
        return counts
    
    # Let's test the function
    print count_characters("abbaa", "ab?")
    

    Here, we reused the function defined in the previous exercise.

  13. Solution:

    def distance(pair1, pair2):
        x1, y1 = pair1
        x2, y2 = pair2
    
        dx = x1 - x2
        dy = y1 - y2
    
        return (float(dx)**2 + float(dy)**2)**0.5
    
    # Let's test the function
    print distance((0, 0), (1, 1))
    print distance((2, 3), (3, 2))
    
  14. Solution:

    def substring(first, second):
        return second in first
    
    # Let's test the function
    print substring("ACGT", "T")
    print substring("ACGT", "x")
    
  15. Solution:

    def non_empty_substrings(input_string):
        substrings = []
    
        # all the possible positions to start a substring
        for start in range(len(input_string)):
    
            # all the possible positions to end a substring
            for end in range(start + 1, len(input_string) + 1):
    
                # extract the substring and update the list
                substrings.append(input_string[start:end])
        return substrings
    
    # Let's test the function
    print non_empty_substrings("ACTG")
    
  16. Soluzione:

    def count_substrings(haystack, needle):
        occurrences = 0
        for start in range(len(haystack)):
            for end in range(start+1, len(haystack)+1):
    
                # to be sure, we print the substring
                print start, end, ":", haystack[start:end], "==", needle, "?"
    
                # check whether the substring is equal to `needle`
                if haystack[start:end] == needle:
                    print "here is an occurrence!"
                    occurrences += 1
    
        return occurrences
    
    # Let's test the function
    print count_substrings("ACTGXACTG", "ACTG")
    
  17. Solution:

    def longest_substring(string1, string2):
    
        # let's reuse the previous function
        substrings1 = non_empty_substrings(string1)
        substrings2 = non_empty_substrings(string2)
    
        # find the longest common substring
        longest_sub = ""
        for substring1 in substrings1:
            for substring2 in substrings2:
    
                if substring1 == substring2 and \
                   len(substring1) > len(longest_sub):
    
                    # aggiorno
                    longest_sub = substring1
    
        return longest_sub
    
    # Let's test the function
    print longest_substring("ACTG", "GCTA")
    print longest_substring("", "ACTG")
    print longest_substring("ACTG", "")