Question 5 - Word Frequency

Write a Python program that takes a sentence and creates a dictionary containing each word and the number of times it occurs.

The counting should be case-insensitive.

Example

Input:
Python is easy and Python is useful

Output:
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'useful': 1}
import numpy as np

sentence = "Python is easy and Python is useful"
words = np.array(sentence.lower().split())

unique_words, counts = np.unique(words, return_counts=True)
frequency = dict(zip(unique_words.tolist(), counts.tolist()))

print(frequency)
{'and': 1, 'easy': 1, 'is': 2, 'python': 2, 'useful': 1}
sentence = "Python is easy and Python is useful"
words = sentence.lower().split()
frequency = {}
for word in words:
    if word in frequency:
        frequency[word] += 1
    else:
        frequency[word] = 1
print(frequency)
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'useful': 1}

Question 6

The marks of students are stored in a dictionary:

marks = {
    "Asha": 78,
    "Ravi": 92,
    "Kiran": 65,
    "Meena": 92,
    "Arun": 48
}

Write a program to:

  1. find the highest mark,
  2. print the name(s) of the student(s) obtaining the highest mark,
  3. calculate the average mark,
  4. print the names of students whose marks are above the average.
marks = {"Asha": 78,"Ravi": 92,"Kiran": 65,"Meena": 92,"Arun": 48}

names = np.array(list(marks.keys()))
scores = np.array(list(marks.values()))
highest = np.max(scores)
average = np.mean(scores)
print(highest, names[scores == highest],
      average, names[scores > average], sep="\n")
92
['Ravi' 'Meena']
75.0
['Asha' 'Ravi' 'Meena']
highest = max(marks.values())
average = sum(marks.values()) / len(marks)
print(highest)
for name, mark in marks.items():
    if mark == highest:
        print(name)
print(average)
for name, mark in marks.items():
    if mark > average:
        print(name)
92
Ravi
Meena
75.0
Asha
Ravi
Meena

Question 7

Write a function

prime_numbers(numbers)

that accepts a list of integers and returns a new list containing only the prime numbers.

Example

Input:
[4, 7, 10, 13, 18, 23, 1]

Output:
[7, 13, 23]
def is_prime(n):
    if n < 2:
        return False
    divisors = np.arange(2, int(np.sqrt(n)) + 1)
    return divisors.size == 0 or np.all(n % divisors != 0)

def prime_numbers(numbers):
    numbers = np.asarray(numbers)
    prime_mask = np.vectorize(is_prime, otypes=[bool])(numbers)
    return numbers[prime_mask].tolist()

numbers = [4, 7, 10, 13, 18, 23, 1]
print(prime_numbers(numbers))
[7, 13, 23]
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def prime_numbers(numbers):
    result = []
    for num in numbers:
        if is_prime(num):
            result.append(num)
    return result
numbers = [4, 7, 10, 13, 18, 23, 1]
print(prime_numbers(numbers))
[7, 13, 23]