Blog

Python Practice Questions & Solutions Day 7 of Learning Python for Data Science

Test your understanding of Python Data Structure, which we learned in our previous lesson of Day 7 of Learning Python for Data Science, with these targeted practice questions.

Welcome back to Day 7 of Learning Python for Data Science journey! In the last article, we explored:

Tuples
dictionaries
Comprehensions

Now, it’s time to solve the practice questions given in the previous article.
Each question is followed by a detailed explanation and output.

Tuples

Create a tuple with numbers and find the maximum and minimum values.

tuple1 = (243, 34, 235, 25, 252, 253, 567 ,5685, 8678)

print('Max : ', max(tuple1))
print('Min : ', min(tuple1))

Output:

Max :  8678
Min :  25

Write a program to count occurrences of an element in a tuple.

tuple1 = (243, 34, 235, 25, 25, 252, 253, 567 ,5685, 8678)

tuple1.count(25)

Output:

2

Convert a tuple of strings to a single concatenated string.

tuple_str = ('Mango', 'Banana', 'Grapes')

''.join(tuple_str)

Output:

'MangoBananaGrapes'

Check if an element exists in a tuple.

tuple_str = ('Mango', 'Banana', 'Grapes')

'Mango' in tuple_str

Output:

True

Swap two tuples without using a temporary variable.

tuple_str = ('Mango', 'Banana', 'Grapes') #creating
tuple1 = (243, 34, 235, 25, 25, 252, 253, 567 ,5685, 8678) #creating

tuple_str, tuple1 = tuple1, tuple_str # swaping

print(tuple_str)
print(tuple1)

Output:

tuple_str:  (243, 34, 235, 25, 25, 252, 253, 567, 5685, 8678)
tuple1: ('Mango', 'Banana', 'Grapes')

Reverse a tuple

tuple_str = ('Mango', 'Banana', 'Grapes') 

tuple_str[::-1]

Output:

('Grapes', 'Banana', 'Mango')

Write a program to find common elements between two tuples.

tuple_str1 = ('Mango', 'Banana', 'Grapes') 
tuple_str2 = ('Mango', 'Guvava', 'Peach')

set(tuple_str1).intersection(set(tuple_str2))

Output:

{'Mango'}

Convert a tuple of numbers into a tuple of their squares.

tuple_n = (5, 4, 6, 7, 8, 9, 2)

tuple_square = tuple(i**2 for i in tuple_n)

print(tuple_square)

Output:

(25, 16, 36, 49, 64, 81, 4)

Merge two tuples and remove duplicates.

tuple_n = (5, 4, 6, 7, 8, 9, 2)
tuple_d = (5, 4, 34, 45, 56, 67, 8)

set(tuple_n).union(set(tuple_d)) #method 1

set(tuple_n) | set(tuple_d) #method 2

Output:

{2, 4, 5, 6, 7, 8, 9, 34, 45, 56, 67}

Write a function to return the first and last element of a tuple.

tuple_n = (5, 4, 6, 7, 8, 9, 2)

def tup_func(tuple):
    return tuple[0], tuple[-1]

tup_func(tuple_n)

Output:

(5, 2)

Dictionaries

Create a dictionary from two lists (keys and values).

keys = ['name', 'age']
values = [['John', 'Mark'], [28, 30]]

# Creating the dictionary
people_dict = dict(zip(keys, values))

print(people_dict)

Output:

{'name': ['John', 'Mark'], 'age': [28, 30]}

Write a function that returns keys with the highest values in a dictionary.

def get_max_keys(dictionary):
    if not dictionary:
        return None  # Handle empty dictionary case
    
    max_value = max(dictionary.values())  # Find the highest value
    max_keys = [key for key, value in dictionary.items() if value == max_value]  # Get all keys with max value
    
    return max_keys, max_value

# Example dictionary
num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 4  # Added a duplicate max value for testing
}

print(get_max_keys(num))

Output:

(['four', 'five'], 4)

Merge two dictionaries and sort by key.

num1 = {
    'one': 1,
    'two': 2,
}

num2 = {
    'three': 3,
    'four': 4
}

# Merging dictionaries
num1.update(num2)

# Sorting by keys
sorted_num1 = dict(sorted(num1.items()))

print(sorted_num1)

Output:

{'four': 4, 'one': 1, 'three': 3, 'two': 2}

Count occurrences of characters in a string using a dictionary.

string = 'banana'
count = {}

# iterating through string to create a dictionary
for i in string:
    if i in count.keys():
        count[i] += 1
    else:
        count[i] = 1

print(count)

Output:

{'b': 1, 'a': 3, 'n': 2}

Find the sum of all values in a dictionary.

num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4
}

# Finding the sum of all values
sum_values = sum(num.values())

print("Sum of all values:", sum_values)

Output:

Sum of all values: 10

Remove a key from a dictionary safely.

num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4
}

# Safely removing a key
removed_value = num.pop('two', None)  # Removes 'two', returns None if not found

print("Updated Dictionary:", num)
print("Removed Value:", removed_value)

Output:

Updated Dictionary: {'one': 1, 'three': 3, 'four': 4}
Removed Value: 2

Sort a dictionary by its values in ascending order.

num = {
    'four': 4,
    'three': 3,
    'two': 2,
    'one': 1  
}

# Sorting dictionary by values in ascending order
sorted_dict = dict(sorted(num.items(), key=lambda item: item[1]))

print(sorted_dict)

Output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

Write a program to invert keys and values in a dictionary.

num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4
}

new_num = {}

# interting the dictionary
for keys, value in num.items():
    new_num[value] = keys

print(new_num)

Output:

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

Create a dictionary with keys as numbers and values as their cubes.

cubes = {i : i**3 for i in range(1,5)}
print(cubes)

Output:

{1: 1, 2: 8, 3: 27, 4: 64}

Convert a dictionary to a list of tuples.

num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4
}

num_tuple = tuple(num.items()) # converting to a tuple

print(num_tuple)

Output:

(('one', 1), ('two', 2), ('three', 3), ('four', 4))

Comprehensions

Generate a list of squares of even numbers from 1 to 20.

squares = [i**2 for i in range(1,21) if i % 2 == 0]
print(squares)

Output:

[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Create a set of unique characters from a given string using comprehension.

string = 'banana'

unique_char = {i for i in string} #creating a set

print(unique_char)

Output:

{'a', 'n', 'b'}

Write a dictionary comprehension to filter out keys that have even values.

num = {
    'one' : 1,
    'two' : 2,
    'three' : 3,
    'four' : 4
}

eve_num = {key: value for key, value in num.items() if value % 2 == 0} # filtering the key value pairs having even value

print(eve_num)

Output:

{'two': 2, 'four': 4}

Generate a list of words that have more than 3 letters from a sentence.

sentence = 'histroy is written by winners.'

letter = [i for i in sentence.split() if len(i)>3]

print(letter)

Output:

['histroy', 'written', 'winners.']

Create a dictionary where keys are numbers from 1 to 10, and values are their factorials.

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

factorials = {num: factorial(num) for num in range(1, 11)}

print(factorials)

Output:

{1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880, 10: 3628800}

Extract unique words from a paragraph using set comprehension.

para = "The cat chased the mouse. The mouse ran fast, but the cat was faster. The cat jumped, and the mouse hid. The cat looked, but the mouse was gone."

unique_words = {word for word in para.split()} # extracting unique words

print(unique_words)

Output:

{'the', 'gone.', 'jumped,', 'cat', 'but', 'faster.', 'chased', 'The', 'fast,', 'ran', 'mouse.', 'mouse', 'looked,', 'hid.', 'and', 'was'}

Convert a list of tuples into a dictionary using comprehension.

lis = [('one', 1), ('two', 2), ('three', 3), ('four', 4)]

tup = {i[0]:i[1] for i in lis} # creating dictionary

print(tup)

Output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

Generate a list of numbers that are multiples of both 3 and 5 from 1 to 100.

multiples_of_3_and_5 = [i for i in range(1, 101) if i % 3 == 0 and i % 5 == 0]

print(multiples_of_3_and_5)

Output:

[15, 30, 45, 60, 75, 90]

Create a dictionary with student names as keys and their grades as values, filtering only students with grades above 80.

students_grades = {
    'Alice': 85,
    'Bob': 78,
    'Charlie': 92,
    'David': 88,
    'Emma': 95}

filtered_students = {key : value for key, value in students_grades.items() if value >80}

print(filtered_students)

Output:

{'Alice': 85, 'Charlie': 92, 'David': 88, 'Emma': 95}

Generate a set of squares of odd numbers from 1 to 30.

squares_of_odd = {i**2 for i in range(1,31) if i % 2 != 0}

print(squares_of_odd)

Output:

{1, 121, 225, 289, 9, 169, 361, 441, 841, 81, 49, 529, 625, 729, 25}

We hope this article was helpful for you and you learned a lot about data analyst interview from it. If you have friends or family members who would find it helpful, please share it to them or on social media.

Join our social media for more.

Python for Data Science Python for Data Science Python for Data Science Python for Data Science Python for Data Science Python for Data Science Python for Data Science Python for Data Science

Spread the love

Recent Posts

Mastering Pivot Table in Python: A Comprehensive Guide

Pivot tables are a powerful tool for summarizing and analyzing data, and Python’s Pandas library…

2 weeks ago

Data Science Interview Questions Section 3: SQL, Data Warehousing, and General Analytics Concepts

Welcome to Section 3 of our Data Science Interview Questions series! In this part, we…

2 weeks ago

Data Science Interview Questions Section 2: 25 Questions Designed To Deepen Your Understanding

Welcome back to our Data Science Interview Questions series! In the first section, we explored…

2 weeks ago

Data Science Questions Section 1: Data Visualization & BI Tools (Power BI, Tableau, etc.)

Data Science Questions in Section 1 focus on the essential concepts of Data Visualization and…

2 weeks ago

Optum Interview Questions: 30 Multiple Choice Questions (MCQs) with Answers

In this article, we’ve compiled 30 carefully selected multiple choice questions (MCQs) with answers to…

3 weeks ago

Day 15 of Learning Python for Data Science: Exploring Matplotlib Visualizations and EDA

Welcome to Day 15 of our Python for Data Science journey!On Day 15, we dived…

3 weeks ago