Question

Define the functions in Python 3.8

1. Write a function most frequent n that takes a list of strings and an integer n, and that returns a dictionary where the ke

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

def most_frequent_n(text, n):
    # sorting the dictionary and store into sorted_text
    sorted_text = sorted(text.items(), key=operator.itemgetter(1), reverse=True)

    new_text = {}
    i=1
    # iterate over the sorted_text
    for k, v in sorted_text:
        # store key, value pair to the new_text dictionary
        new_text[k] = v

        # if i == n break the for loop
        # because we need only n values
        if i == n:
            break

        i = i + 1

    return new_text

    
def average_scores(gradebook):
    avg_grade = {}
    
    # iterate over gradebook
    for k, v in gradebook.items():

        # calculate average of marks and 
        # store name and average to the dictionary, avg_grade
        avg_grade[k] = statistics.mean(v)

    # returning avg_grade dictionary
    return avg_grade


def num_name(num):
    # dictionary for ones digit
    ones = {0: "zero",1:"one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"}

    # dictionary for tens digit
    tens = { 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"}

    # dictionary for special numbers from 10-19
    special = {10: "ten", 11:"eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 
                15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen"}

    # check if num<10 then return value from ones dictionary
    if num<10:
        return ones[num]

    # check if num < 10 then return value from special dictionary
    elif num < 20:
        return special[num]
    else:
        # extract ones digit
        ones_digit = int(str(num)[1])

        # extract tens digit
        tens_digit = int(str(num)[0])

        # return the number in words 
        return tens[tens_digit] + " " + ones[ones_digit]


text = {"is":2, "the":3, "of":2, "am":1, "a":1}

# calling most_frequent_n method
print(most_frequent_n(text, 3))
print(most_frequent_n(text, 2))
print()

gradebook = {"thomas": [83, 73, 82, 93],
            "Maria": [78, 82, 85, 89],
            "Philip": [65, 72, 78, 71],
            "Sally": [96, 93, 99, 86]}

# calling average_scores method
print(average_scores(gradebook))
print()

# calling num_name method
print(num_name(7))
print(num_name(58))
print(num_name(12))
        

Screenshots of running code and output:
File Edit Selection View Go Run Terminal Help python_ex.py - HomeworkLib - Visual Studio Code - Х D python_ex.py X A www. go A & py File Edit Selection View Go Run Terminal Help python_ex.py - HomeworkLib - Visual Studio Code - Х D python_ex.py X e python_ex.py )File Edit Selection View Go Run Terminal Help python_ex.py - HomeworkLib - Visual Studio Code - Х D python_ex.py X Q CH ge python_eFile Edit Selection View Go Run Terminal Help python_ex.py - HomeworkLib - Visual Studio Code - Х python_ex.py X & python_ex.py > S

Add a comment
Know the answer?
Add Answer to:
Define the functions in Python 3.8 1. Write a function most frequent n that takes 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
  • Python 3.7.3 ''' Problem 3 Write a function called names, which takes a list of strings...

    Python 3.7.3 ''' Problem 3 Write a function called names, which takes a list of strings as a parameter. The strings are intended to represent a person's first and last name (with a blank in between). Assume the last names are unique. The function should return a dictionary (dict) whose keys are the people's last names, and whose values are their first names. For example: >>> dictionary = names([ 'Ljubomir Perkovic', \ 'Amber Settle', 'Steve Jost']) >>> dictionary['Settle'] 'Amber' >>>...

  • 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: Write a function removeRand() that takes a dictionary d and an integer n as...

    PYTHON 3: Write a function removeRand() that takes a dictionary d and an integer n as parameters. The function randomly chooses n key-value pairs and removes them from the dictionary d. If n is greater than the number of elements in the dictionary, the function prints a message but does not make any changes to d. If n is equal to the number of elements in d, the function clears the dictionary. Otherwise the function goes through n rounds in...

  • IN PYTHON: Write a function that takes, as an argument, a positive integer n, and returns...

    IN PYTHON: Write a function that takes, as an argument, a positive integer n, and returns a LIST consisting of all of the digits of n (as integers) in the same order. Name this function intToList(n). For example, intToList(123) should return the list [1,2,3].

  • Write a Python function makeDict() that takes a filename as a parameter. The file contains DNA...

    Write a Python function makeDict() that takes a filename as a parameter. The file contains DNA sequences in Fasta format, for example: >human ATACA >mouse AAAAAACT The function returns a dictionary of key:value pairs, where the key is the taxon name and the valus is the total number of 'A' and 'T' occurrences. For example, for if the file contains the data from the example above the function should return: {'human':4,'mouse':7}

  • Python 3 Write a function named starCounter that takes three parameters: 1. a dictionary named starDictionary....

    Python 3 Write a function named starCounter that takes three parameters: 1. a dictionary named starDictionary. Each key in starDictionary is the name of a star (a string). Its value is a dictionary with two keys: the string 'distance' and the string 'type'. The value associated with key 'distance' is the distance from our solar system in light years. The value associated with key 'type' is a classification such as 'supergiant' or 'dwarf'. 2. a number, maxDistance 3. a string,...

  • using python Write a function that takes a dictionary and a list of keys as 2...

    using python Write a function that takes a dictionary and a list of keys as 2 parameters. It removes the entries associated with the keys from the given dictionary Your function should not print or return anything. The given dictionary should be modified after the function is called Note: it means that you can't create another dictionary in your function. Since dictionaries are mutable, you can modify them directly def remove_keys (dict, key_list) "" "Remove the key, value pair from...

  • write a function firstLetterWords(words) that takes as a parameter a list of strings named words and...

    write a function firstLetterWords(words) that takes as a parameter a list of strings named words and returns a dictionary with lower case letters as keys. But now associate with each key the list of the words in words that begin with that letter. For example, if the list is ['ant', 'bee', 'armadillo', 'dog', 'cat'], then your function should return the dictionary {'a': ['ant', 'armadillo'], 'b': ['bee'], 'c': ['cat'], 'd': ['dog']}.

  • Python 3 Write a function named inverse that takes a single parameter, a dictionary. In this...

    Python 3 Write a function named inverse that takes a single parameter, a dictionary. In this dictionary each key is a student, represented by a string. The value of each key is a list of courses, each represented by a string, in which the student is enrolled. The function inverse should compute and return a dictionary in which each key is a course and the associated value is a list of students enrolled in that course. For example, the following...

  • write the following code in python 3.2+. Recursive function prefered. Thank you! Define a function named...

    write the following code in python 3.2+. Recursive function prefered. Thank you! Define a function named q3() that accepts a List of characters as a parameter and returns a Dictionary. The Dictionary values will be determined by counting the unique 3 letter combinations created by combining the values at index 0, 1, 2 in the List, then the values at index 1, 2, 3 and so on. The q3() function should continue analyzing each sequential 3 letter combination and using...

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