Question

Python problem.3. (6 pts) Define the following four sorting functions: each takes an argument that is a list of int or str or both values (otherwise raise an AssertionError exception with an appropriate error message) that will be sorted in a different way. Your function bodies must contain exactly one assert statement followed by one return statement. In parts a-c, create no other extra/temporary lists other than the ones returned by calling sorted. a. (2 pts) Define the mixed sort1 function, which returns the list sorted increasing by the int values and int equivalent of the str values. For example, mixed sort! ([13.1, 2.4] ) returns [1,2·13 ,4J. calling mixed sort1(1) prints AssertionError: qlsolution.mixed sortl: 1 non int/str list b. (2 pts) Define the mixed sort2 function, which returns the list sorted first increasing by the int values and then sorted increasing by the int equivalent of the str values. For example, mixed sort ([3,1, 2,4]) returns [1,4, 2, 3] c. (1 pt) Define the mixed sort3 function, which returns the list sorted first increasing by the int values and then sorted decreasing by the int equivalent of the str values. For example, mixed sort([3,1, 2,4]) returns [1,4, 3, 2. Hint: for the key argument, I used a conditional if in the lambda to choose a different tuple for int and str values, so they compare correctly. d. (1 pt) Define the mixed sort4 function, which returns values in the same order as mixed sort3, but here all the values returned are int. For example, mixed sort([3,1, 2,4]) returns [1,4,3,2]. You may create a temporary list in this function. Hint: I created it using a comprehension.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
"""
File Name : sorting.py
Author : __
Date : 10/10/2017
Description :

"""


def mixed_sort1(input_list):
    """
    This function sort the list increasing order by int value of string
    :param input_list:
    :return:
    """
    assert isinstance(input_list, list), "q1solution.mixed_sort1 : " + str(input_list) + " non int/str list"
    assert all(
        isinstance(item, int) or isinstance(item, str) for item in input_list), "q1solution.mixed_sort1 : " + str(
        input_list) + " non int/str list"
    return sorted(input_list, key=lambda x: int(x))


def mixed_sort2(input_list):
    """
    This function sort the list increasing order by int and then increasing  order by string
    :param input_list:
    :return:
    """

    assert isinstance(input_list, list), "q1solution.mixed_sort1 : " + str(input_list) + " non int/str list"
    assert all(
        isinstance(item, int) or isinstance(item, str) for item in input_list), "q1solution.mixed_sort1 : " + str(
        input_list) + " non int/str list"
    return sorted(input_list, key=lambda x: (isinstance(x, str), x))


def mixed_sort3(input_list):
    """
    This function sort the list increasing order by int and decreasing order by string
    :param input_list:
    :return:
    """
    assert isinstance(input_list, list), "q1solution.mixed_sort1 : " + str(input_list) + " non int/str list"
    assert all(
        isinstance(item, int) or isinstance(item, str) for item in input_list), "q1solution.mixed_sort1 : " + str(
        input_list) + " non int/str list"
    return sorted(input_list, key=lambda x: (False, x) if isinstance(x, int) else (True, -int(x)))


def mixed_sort4(input_list):
    """
    This function sort the list increasing order by int and decreasing order by string and using
    list comprehension convert each element to int type and return
    :param input_list:
    :return:
    """

    assert isinstance(input_list, list), "q1solution.mixed_sort1 : " + str(input_list) + " non int/str list"
    assert all(
        isinstance(item, int) or isinstance(item, str) for item in input_list), "q1solution.mixed_sort1 : " + str(
        input_list) + " non int/str list"
    return [int(x) for x in sorted(input_list, key=lambda x: (False, x) if isinstance(x, int) else (True, -int(x)))]


if __name__ == '__main__':
    print("mixed_sort1:", mixed_sort1(['3', 1, '2', 4]))
    print("mixed_sort2:", mixed_sort2(['3', 1, '2', 4]))
    print("mixed_sort3:", mixed_sort3(['3', 1, '2', 4]))
    print("mixed_sort4:", mixed_sort4(['3', 1, '2', 4]))

mixed sortl: [1, 2, 3, 4] mixed sort2: [1, 4, 2, 3] mixed sort3: [1, 4, 3, 2] mixed sort4: [1, 4, 3, 2] Process fin

Add a comment
Know the answer?
Add Answer to:
Python problem. 3. (6 pts) Define the following four sorting functions: each takes an argument that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In PYTHON! Exercise 3: Lists and Functions In this exercise we will explore the use of...

    In PYTHON! Exercise 3: Lists and Functions In this exercise we will explore the use of lists and functions with multiple inputs and multiple outputs. Your task is to implement the separate_and_sort function. This function takes two input parameters: 1. A list containing strings and integers in any order. 2. An optional integer parameter size which controls how many items in the list the function will process. If the length of the list is smaller than the value of size,...

  • in python A. Define a function called contains_only_integers() that takes a tuple, returns True if all...

    in python A. Define a function called contains_only_integers() that takes a tuple, returns True if all the items in the tuple are integers(2), and returns False otherwise. For example, contains_only_integers (3, 5, 17, 257, 65537) ), contains_only_integers( (-1,) ), and contains_only_integers( ) should all return True, but contains_only_integers (2.0,4.0)) and contains_only_integers (8, 4, "2", 1)) should both return false. Your function should use a while loop to do this calculation. 121 Hint: the is instance() built-in function provides the most...

  • Define a function called get_n_largest(numbers, n) which takes a list of integers and a value n...

    Define a function called get_n_largest(numbers, n) which takes a list of integers and a value n as parameters and returns a NEW list which contains the n largest values in the parameter list. The values in the returned list should be in increasing order. The returned list must always be of length n. If the number of values in the original list is less than n, the value None should be repeated at the end of the returned list to...

  • (10 pts)3-1. Given the following piece of code #define SIZE 10 include <iostream> using namespace std;...

    (10 pts)3-1. Given the following piece of code #define SIZE 10 include <iostream> using namespace std; // sorted array in descending order int list[SIZE] (23, 19, 17, 13, 11, 7, 5, 3, 1, 0); // recursively binary search the array list for key // return the index to list if key is found. else return -1 int recBinarySearch (int key) // Please implement the recursive function.. Please implement the C++ function recBinarySearch that recursively binary searches the value key in...

  • #include <stdio.h> // Define other functions here to process the filled array: average, max, min, sort,...

    #include <stdio.h> // Define other functions here to process the filled array: average, max, min, sort, search // Define computeAvg here // Define findMax here // Define findMin here // Define selectionSort here ( copy from zyBooks 11.6.1 ) // Define binarySearch here int main(void) { // Declare variables FILE* inFile = NULL; // File pointer int singleNum; // Data value read from file int valuesRead; // Number of data values read in by fscanf int counter=0; // Counter of...

  • Create a python add the following functions below to the module. Each section below is a...

    Create a python add the following functions below to the module. Each section below is a function that you must implement, make sure the function's names and parameters match the documentation (Copy-Paste). DO NOT put the functions in an if-name-main block. 1. def productSum(x: int, y: int, z: int) -> int This function should return: The product of x and y, if the product of x and y is less than z. Else it should return the sum of x...

  • Question 2 - Objects You are to implement the following functions: getCharacterFrequency -10pts This function takes...

    Question 2 - Objects You are to implement the following functions: getCharacterFrequency -10pts This function takes a single string (str) argument and returns an object. o The object's properties will be the unique letters present in str The value of each property will be the frequency of each character present in the string. NOTE: Uppercase and Lowercase letters should be grouped in the same count. For example, the word Babble would result in the following object "B3, 11 This count...

  • Python 3 Define a function below, get_subset, which takes two arguments: a dictionary of strings (keys)...

    Python 3 Define a function below, get_subset, which takes two arguments: a dictionary of strings (keys) to integers (values) and a list of strings. All of the strings in the list are keys to the dictionary. Complete the function such that it returns the subset of the dictionary defined by the keys in the list of strings. For example, with the dictionary ("puffin": 5, "corgi": 2, "three": 3) and the list ("three", "corgi"), your function should return {"corgi": 2, "three"...

  • Python 3 Coding Functions: Here is any code required to help code what is below: def...

    Python 3 Coding Functions: Here is any code required to help code what is below: def pokemon_by_types(db, types): new_db = {} for pokemon_type in types: for key in db: # iterate through all the type in types list if db[key][1] == pokemon_type or db[key][2] == pokemon_type: if key not in new_db: new_db[key] = db[key] return new_db I need help coding the functions listed below in the image: Thank you get types(db): Given a database db, this function determines all the...

  • IN PYTHON 3 LANGUAGE, please help with function, USE RECURSION ONLY def im(l: 'an int, str,list,tuple,set,or...

    IN PYTHON 3 LANGUAGE, please help with function, USE RECURSION ONLY def im(l: 'an int, str,list,tuple,set,or dict') -> 'an int, str, tuple, or frozenset'      pass    SAMPLE OUTPUT: The following call (with many mutable data structures) imm(1)   returns 1 imm('a') returns 'a' imm( (1, 2, 3))   returns (1, 2, 3) imm( frozenset([1, 2, 3]))   returns frozenset({1, 2, 3}) imm( [1, 2, 3, 4, 5, 6])   returns (1, 2, 3, 4, 5, 6) imm( [1, 2, [3, [4], 5], 6])  ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT