Question

ON PYTHON: ''' Design the functions described below. RECALL: With functions that do not return a...

ON PYTHON:

''' Design the functions described below.
RECALL:
With functions that do not return a value and print a result to the console,
to test you must call the function, run it and visually inspect the result for correctness.
With functions that return a value, use the print_test function
to provide feedback of the test results at the command line.
The print_test function is implemented for you at the bottom of this file.
RECALL: floating point arithmetic can lose precision and therefore
we are restricting these functions to work on lists of integers or strings.
This allows us to compare 2 lists using ==.
ie. [1,2] == [1,2] or ['ab','cd'] == ['ab','cd']
'''

def main():
print('call your test functions from here')

'' Q5. Design a function that takes a list of tuples and
an additional integer specifying a position. The function
creates and returns a new list with the element from each tuple
at the specified position.
ie. if original list is [(1,2,3),(4,5,6)] and the specified position is 1
the returned list should be [2,5]
The function should not change the original list.
'''


''' Q6. Design a function that takes a list of tuples, a position (pos)
in the tuple and single value(v) that is the same type as the value
at the given position in the tuple. The function should create and
return a new list of only those tuples from the original list that
contain value v at position pos.
'''

# (str, bool -> None)
# prints test_name followed by 'passed' if expression evaluates to True,
# prints test_name followed by 'failed' if expression evaluates to False
def print_test(test_name, expression):
if(expression):
print(test_name + ': passed')
else:
print(test_name + ': failed')


# The following code will call your main function
if __name__ == '__main__':
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

''' Design the functions described below.
RECALL:
With functions that do not return a value and print a result to the console,
to test you must call the function, run it and visually inspect the result for correctness.
With functions that return a value, use the print_test function
to provide feedback of the test results at the command line.
The print_test function is implemented for you at the bottom of this file.
RECALL: floating point arithmetic can lose precision and therefore
we are restricting these functions to work on lists of integers or strings.
This allows us to compare 2 lists using ==.
ie. [1,2] == [1,2] or ['ab','cd'] == ['ab','cd']
'''

''' Q5. Design a function that takes a list of tuples and
an additional integer specifying a position. The function
creates and returns a new list with the element from each tuple
at the specified position.
ie. if original list is [(1,2,3),(4,5,6)] and the specified position is 1
the returned list should be [2,5]
The function should not change the original list.
'''


def function_Q5(tuples_list, position):
    #creating an empty list
    result = []
    #looping through each tuple in tuples_list
    for tup in tuples_list:
        #if position is a valid index on tup, appending element at position to result
        if position >= 0 and position < len(tup):
            result.append(tup[position])
        #otherwise if the position is invalid on this tuple, appending a None value
        else:
            result.append(None)
    #returning the result
    return result


''' Q6. Design a function that takes a list of tuples, a position (pos)
in the tuple and single value(v) that is the same type as the value
at the given position in the tuple. The function should create and
return a new list of only those tuples from the original list that
contain value v at position pos.
'''


def function_Q6(tuples_list, position, value):
    # creating an empty list
    result = []
    # looping through each tuple in tuples_list
    for tup in tuples_list:
        #checking if position is valid and tup contains value at position
        if position >= 0 and position < len(tup):
            if tup[position] == value:
                #adding current tuple to result list
                result.append(tup)
    return result


def main():
    # testing function_Q5()
    print_test('Q5 method test1', function_Q5([(1, 2, 3), (4, 5, 6)], 1) == [2, 5])
    print_test('Q5 method test2', function_Q5([(1, 2, 3), (4, 5, 6)], 0) == [1, 4])
    print_test('Q5 method test3', function_Q5([(1, 2), (3, 4), (5, 6)], 1) == [2, 4, 6])

    # testing function_Q6()
    # function_Q6([(1, 2, 3), (4, 5, 6)], 1, 2) returns [(1, 2, 3)] because only the first tuple
    # contain the value 2 at position 1
    print_test('\nQ6 method test1', function_Q6([(1, 2, 3), (4, 5, 6)], 1, 2) == [(1, 2, 3)])
    print_test('Q6 method test2', function_Q6([(1, 2, 3), (4, 5, 6)], 2, 6) == [(4, 5, 6)])
    print_test('Q6 method test3', function_Q6([(1, 2, 3), (4, 5, 6)], 2, 99) == [])


# (str, bool -> None)
# prints test_name followed by 'passed' if expression evaluates to True,
# prints test_name followed by 'failed' if expression evaluates to False
def print_test(test_name, expression):
    if (expression):
        print(test_name + ': passed')
    else:
        print(test_name + ': failed')


# The following code will call your main function
if __name__ == '__main__':
    main()

#output

Add a comment
Know the answer?
Add Answer to:
ON PYTHON: ''' Design the functions described below. RECALL: With functions that do not return a...
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
  • use python 2a. Union (1 points) Make a union function which takes in 2 lists as...

    use python 2a. Union (1 points) Make a union function which takes in 2 lists as parameters and returns a list. It should return a list that contain all elements that are in either list. Your results list should contain no duplicates. For example, if the two lists are [1,5,6,5, 2] and [3,5, 1,9] then the result list is (1,5,6,2,3,9). Note that the list sizes don't have to be equal. Note that the input lists could have duplicates, but your...

  • Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for...

    Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for the dictionary are strings and the values are lists of numbers. The function should create a new dictionary where the keys are the same strings as the original dictionary and the values are tuples. The first entry in each tuple should be the weighted average of the non-negative values in the list (where the weight was the number in the 0 position of the...

  • Designing functions Reminder: When designing functions, follow the given steps to reinforce good software development p...

    Designing functions Reminder: When designing functions, follow the given steps to reinforce good software development practices and problem solving strategies: a) Start by writing the documentation for the function. Use docstrings shown in lecture and lab. b) Write test calls to the function in your main function for the different cases of input the function will encounter. This will help you understand the behavior of the function and later behave as tests for your function. c) Define the function d)...

  • Define the get_list_of_lists() function which is passed a list of strings as a parameter. An example...

    Define the get_list_of_lists() function which is passed a list of strings as a parameter. An example parameter list is: ["4 3 1 12 2 12 3 12 4 3", "4 3 1 12 2 12 3 12 4 3", "4 3 1 12 2 6"] The function returns a list of lists of tuples. For each element of the parameter list, e.g., "4 3 1 12 2 12" the function creates a list of tuples, e.g., [("4", 3), ("1", 12),...

  • PYTHON. Write the following functions without using any predefined functions unless specified. def min (dataList) :      ...

    PYTHON. Write the following functions without using any predefined functions unless specified. def min (dataList) :       #returns the smallest value of the data values in dataList def max (dataList):        #returns the largest value def getRange (dataList) def mean (dataList) :     #returns the average of data values def median (dataList):    #returns the middle value of an ordered list #note: to sort the list first, may use the predefined sort function Then write a test1 function to test the above functions using...

  • 1. In Python, 'mutable' objects such as lists are passed to functions 'by reference'. This means:...

    1. In Python, 'mutable' objects such as lists are passed to functions 'by reference'. This means: a.) Changes made to the object within the function persist after the function completes b.) The function receives a copy of the object c.) Python keeps a history of where then object was used d.) Statements in the function can refer to the object by nickname 2. Which of the following is NOT a requirement for a Python function: a.) The function must have...

  • In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...

    In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains, insert, and normal_list methods. You may use default arguments and/or helper functions. The file must be named: LinkedList.py Here is what I have for my code so far. The methods I need the recursive implementations for will be bolded: class Node: """ Represents a node in a linked list (parent class) """ def __init__(self, data): self.data = data self.next = None class LinkedList: """...

  • PYTHON Given three unsorted lists, a name list (e.g. nameLst = [“Betty”, “Andrew”, “Zach”, “Cathy”, …]),...

    PYTHON Given three unsorted lists, a name list (e.g. nameLst = [“Betty”, “Andrew”, “Zach”, “Cathy”, …]), an Exam1 score list (e.g. score1 = [50, 45, 48, 48, …]), and an Exam 2 score list (e.g. score2=[35, 48, 50, 37, …]) Write the following functions: def makeLst (aNameLst, e1ScoreLst, e2ScoreLst) : #the function will return a list of tuples as in the following form #[(“Betty”, (50,35)), (“Andrew”, (45,48)), (“Zach”, (48,50)), (“Cathy”, (48,37)), …] def personalAverage(aList) : #takes a class list in...

  • The problem is this Design a function that accepts a list as an argument and returns...

    The problem is this Design a function that accepts a list as an argument and returns the largest value in the list. The function should use recursion to find the largest item. My coding so far is this def main(): # Prints the largest value in list user_input = input('Enter a list of numbers seperated by a space: ') user_list = user_input.split() print('Largest number is ', max_Number(user_list), '.') # Recursion function that finds the maximum number in a sequence of...

  • PROJECT 6    Functions You are to write a PYTHON program which: *Defines the following 4  functions: whoamI()...

    PROJECT 6    Functions You are to write a PYTHON program which: *Defines the following 4  functions: whoamI() This function prints out your name and lists any programming course you have taken prior to this course. isEven(number) This function accepts one parameter, a number, and prints out a message indicating if the number is even or odd. Keep in mind that a number is even if there is no remainder when the number is divided by two. printEven(number) This function accepts one...

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