Python Exam Questions

0.0(0)
Studied by 4 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/11

flashcard set

Earn XP

Description and Tags

Pyfn

Last updated 7:33 PM on 10/27/23
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

12 Terms

1
New cards

Here is the Python code for the stringexpand function:

def stringexpand(name):
    expanded_string = ' '.join(name)
    return expanded_string

When you call the function stringexpand("Adam"), it will return the expanded string "A d a m".

Define a Python function stringexpand(name) which, given a string name, returns the expanded string such that white space is added after each character of the input string. For example, stringexpand(“Adam”) returns “A d a m”.

2
New cards

Here is the Python function palindrome(word) that checks whether the input string is a palindrome or not, regardless of the case of the alphabets, and returns a boolean result accordingly:

def palindrome(word):
    word = word.lower()
    return word == word[::-1]

For example, palindrome("Racecar") will return True, and palindrome("dude") will return False.

Define a Python function palindrome(word), which checks whether the input string is palindrome or not (irrespective of whether the alphabets are upper or lower case) and then returns boolean result accordingly. Palindrome string is the string which is same both backwards and forwards. For example, palindrome("Racecar") will return True. Similarly, palindrome("dude") will return False.

3
New cards

To define the Python function sortdict(dict), you can use the sorted() function with a lambda function as the key parameter to sort the dictionary items by the student WAM in descending order. Here's an example implementation:

def sort_dict_by_values_descending(input_dict):
    sorted_items = sorted(input_dict.items(), 
        key = lambda item : item[1], reverse=True)
    return sorted_items

This function takes a dictionary dict as input and returns a list of tuples sorted by the student WAM in descending order. Each tuple contains the student ID as the first element and the WAM as the second element.

Define a Python function sortdict(dict) which, given a dictionary dict of student IDs and students WAM as keys and values respectively, returns the list of tuples sorted by student WAM in descending order. For example, sortdict({212222:35,2222222:85,2232222:55}) returns [(2222222, 85), (2232222, 55), (212222, 35)] Hint: Think about using sort() function with lists.

4
New cards

To define a Python function sumdigits(n) that returns the sum of the digits of a positive integer n, you can use recursion. Here's an example implementation:

def sumdigits(n):
    if n < 10:
        return n
    else:
        return n % 10 + sumdigits(n // 10)

This function uses the modulo operator % to get the last digit of n and the integer division operator // to remove the last digit. It recursively calls itself with the updated value of n until n becomes less than 10, at which point it returns n.

[Userecursiontosolvethisproblem] Define a Python function sumdigits(n) which, given a positive integer, returns the sum of the digits of input n. For example, sumdigits(1234) returns 10 (obtained by summing all the digits of input: 1+2+3+4=10).

5
New cards

def multiply_lists(lst):
    if len(lst) == 0:
        return 1

    total = 1
    for item in lst:
        if type(item) == type(10) or type(item) == type(10.01):
            total *= item
        else:
            total *= multiply_lists(item)
    return total

Write a Python function multiply_lists(lst) which can return the product of the numerical data in the input list lst. However, it is possible that the input list, lst, possibly contain other lists (which can be empty or further contain more lists). You can assume that the lists only contain numerical data and lists. For example, multiply_lists([1,2,[],3.5,4]) returns 28.0;

Similarly multiply_lists([1,[2],[3.5,[4]]]) also returns 28.0.

6
New cards

def team_maker(pool1, pool2, pool3):
    teams = []
    for i in range(len(pool1)):
        for j in range(len(pool2)):
            for k in range(len(pool3)):
                teams.append(pool1[i] + " " + pool2[j] + " " + pool3[k])
    return teams

Claremontcricketclubhavemanyplayersandneedtomakecombinationofthreeplayers for the practice sessions. There are three type of players: Batsmen, bowler and wicket- keeper. All of them are in different pools and the club need to select one player from each pool and make a combination. All players in each pool need to have practice session with all players of other pool.

Write a python function team_maker(pool1,pool2,pool3) for the above situation which, given three lists of pools of players (pool1,pool2,pool3) returns a list containing all different combinations for the practice sessions. Each item of the output list has the names of players combined as a string with a white space “ “

For example,

team_maker(['Smith','Finch'],['Cummins','Lyon'],['Adam','Payne']) returns ['Smith Cummins Adam', 'Smith Cummins Payne', 'Smith Lyon Adam', 'Smith Lyon Payne', 'Finch Cummins Adam', 'Finch Cummins Payne', 'Finch Lyon Adam', 'Finch Lyon Payne']

7
New cards
def splitEmailAddress(Address):
    result = []
    
    for component in Address.split('@'):
        for element in component.split('.'):
            result.append(element)
        
    return result

Write a Python function splitEmailAddress(Address), which, given an email address, e.g. Michael.Wise@uwa.edu.au, returns a list of the component strings, e.g. [‘Michael’, ‘Wise’, ‘uwa’, ‘edu’, ‘au’]. [5 Marks]

8
New cards
  1. Using string splitting:

def basename(P):
    # Split the path by '/' and get the last part
    filename = P.split('/')[-1]
    # Split the filename by '.' and get the first part
    result = filename.split('.')[0]
    return result
  1. Using rfind and slicing:

def basename(P):
    # Find the last '/' character in the path
    i = P.rfind('/')
    # Extract the substring starting from the character after the last '/'
    filename = P[i + 1:]
    # Split the filename by '.' and get the first part
    result = filename.split('.')[0]
    return result

WriteaPythondefinitionforthefunctionbasename(P)which,givena pathname to a file (a string), returns a string with the file name without the preceding directories and without any suffix, if one exists. For example basename(‘/Users/michaelw/CITS1401/exam.doc’) will return the string ‘exam’. (There is a function called basename in the os.path library, but please ignore it and instead use string processing functions.) [5 Marks]

9
New cards

You can calculate the Manhattan distance between two N-dimensional points by iterating through the corresponding coordinates of the two points and summing the absolute differences. Here's a Python definition for the manhat function:

def manhat(x, y):
    # Initialize the Manhattan distance
    distance = 0

    # Check if the two input lists have the same length
    if len(x) != len(y):
        raise ValueError("Input lists must have the same length")

    # Iterate through the coordinates and calculate the Manhattan distance
    for i in range(len(x)):
        distance += abs(x[i] - y[i])

    return distance

This manhat function takes two lists, x and y, representing N-dimensional points. It checks if the lists have the same length, and then it iterates through the coordinates, calculating the absolute difference for each pair of corresponding coordinates and summing them to get the Manhattan distance. The result is returned as a floating-point value.

The Manhattan distance between two points (x1, x2) and (y1, y2) – the distance a car needs to travel between two points in a city on a grid – is (in 2 dimensions):

m a n h a t = ( y 1 x 1 ) + ( y 2 x 12 )

Write a definition for manhat(x, y), where x and y are points in N- dimensional space, each represented as a list of floating point values, e.g. manhat([1, 3, 5, 7], [1, 9, 25, 42]) returns 41. You can assume that the lists are the same length, though not necessarily length 4. (|..| stands for the absolute value function.) [10 Marks]

10
New cards
def read_non_blank_lines(f):
    # Check if the file at path 'f' exists
    if os.path.exists(f):
        # Open the file for reading
        infile = open(f, 'r')
        
        # Initialize a list to store non-blank lines
        non_blanks = []

        # Iterate through each line in the file
        for line in infile:
            # Remove leading and trailing whitespace (including newline characters)
            line = line.strip() # line = line[:-1] also fine
            
            # Check if the line is not empty
            if line != "":
                # Append the non-blank line to the list
                non_blanks.append(line)

        # Close the file
        infile.close()

        # Return the list of non-blank lines
        return non_blanks

    # If the file does not exist, return an empty list
    return []

  • Tests whether file f exists

  • Opens the file for reading

  • Reads the file

  • Splits the resulting string into lines (ie split on \n)

  • Returns a those lines that are not blank

Considerthefollowingratherimpenetrable(butcorrect)Pythoncode,taken from a function:

if os.path.exists(f):
return [c for c in open(f,'r').read().split('\n') if c != ""]

a. Whatdoesthecodedo?[3marks]
b. Rewritethecodesothatitiseasiertounderstand[7Marks].

11
New cards
def merge(list1, list2):
    # Initialize an empty list to store the merged result
    merged_list = []

    # Initialize pointers for the two lists
    i, j = 0, 0

    # Continue while there are elements in both lists
    while i < len(list1) and j < len(list2):
        # Compare the elements at the current pointers
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1

    # Append any remaining elements from list1, if any
    while i < len(list1):
        merged_list.append(list1[i])
        i += 1

    # Append any remaining elements from list2, if any
    while j < len(list2):
        merged_list.append(list2[j])
        j += 1

    return merged_list

This merge function takes two sorted lists, list1 and list2, and combines them into a single sorted list merged_list. It uses two pointers, i and j, to iterate through the elements of list1 and list2, respectively, comparing and merging them into merged_list. Any remaining elements in either list are appended to the result.

Write a definition for the function merge(list1, list2), that, given two lists: list1 and list2, which are sorted in ascending order, returns a list that combines the two lists in ascending order, e.g. merge([1,3,5,11,12], [2,4,6,8])returns[1,2,3,4,5,6,8,11,12]. (Hint: Forstarters,youwill need a while loop that compares the smallest item in each list.) [30 Marks]

12
New cards
def marksdistribution(D):
    # Initialize a dictionary to count grades
    marks_dict = {'N': 0, 'P': 0, 'Cr': 0, 'D': 0, 'HD': 0}

    # Iterate through the marks in the input dictionary
    for mark in D.values():
        # Check the mark against grade boundaries
        if mark < 50:
            marks_dict['N'] += 1
        elif mark < 60 and mark >= 50:
            marks_dict['P'] += 1
        elif mark < 70 and mark >= 60:
            marks_dict['Cr'] += 1
        elif mark < 80 and mark >= 70:
            marks_dict['D'] += 1
        elif mark <= 100 and mark >= 80:
            marks_dict['HD'] += 1

    # Create a new dictionary containing only grades with counts greater than 0
    final_dict = {key: value for key, value in marks_dict.items() if value > 0}

    return final_dict

The function marksdistribution(D) takes as input a dictionary that maps student names to their marks in the range from 0 to 100. It returns a dictionary that maps the marks ranges used at UWA to the counts of students from the input dictionary (D) who fall into these respective mark ranges. The definitions for the mark ranges are as follows:

  • N: Marks less than 50

  • P: Marks from 50 (inclusive) to less than 60

  • Cr: Marks from 60 (inclusive) to less than 70

  • D: Marks from 70 (inclusive) to less than 80

  • HD: Marks of 80 or higher

For example, if the input dictionary D is given as {"Fred": 55, "James": 67, "Jemima": 71}, the function marksdistribution(D) will return a dictionary that looks like this: {"P": 1, "Cr": 1, "D": 1}.