0% found this document useful (0 votes)
5 views24 pages

Python Notes

The document contains a collection of Python practice problems focused on dictionaries and other data structures. It includes code examples, explanations, and sample outputs for tasks such as merging dictionaries, finding maximum values, sorting, and checking for common elements. Additionally, it covers lambda functions, average calculations, and basic operations on lists.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views24 pages

Python Notes

The document contains a collection of Python practice problems focused on dictionaries and other data structures. It includes code examples, explanations, and sample outputs for tasks such as merging dictionaries, finding maximum values, sorting, and checking for common elements. Additionally, it covers lambda functions, average calculations, and basic operations on lists.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PEACTICE QUESTION BASED ON DICTIONARIES PRACTICE SET 2

Merge Dictionaries (Without Overwriting)


Problem

Merge two dictionaries without overwriting existing keys.

Code
def merge_dicts(d1, d2):
result = [Link]()
for k, v in [Link]():
if k not in result:
result[k] = v
return result

# Example
print(merge_dicts({'a': 1, 'b': 2}, {'b': 3, 'c': 4}))

Explanation

 Keeps values from first dictionary


 Adds only new keys from second

2. Find Key with Maximum Value


Problem

Find the key having the maximum value.

Code
def max_value_key(d):
return max(d, key=[Link])

# Example
print(max_value_key({'a': 10, 'b': 25, 'c': 15}))

Explanation

 [Link] fetches values


 max() returns key with highest value
3. Common Keys in Two Dictionaries
Problem

Find common keys between two dictionaries.

Code
def common_keys(d1, d2):
return [Link]() & [Link]()

# Example
print(common_keys({'a':1,'b':2}, {'b':3,'c':4}))

Explanation

 & performs set intersection

4. Sort Dictionary in Descending Order (by


Value)
Problem

Sort dictionary by values in descending order.

Code
def sort_desc(d):
return dict(sorted([Link](), key=lambda x: x[1], reverse=True))

# Example
print(sort_desc({'a': 2, 'b': 5, 'c': 1}))

Explanation

 sorted() with reverse=True


 Sorts using value (x[1])

5. Remove Duplicate Values


Problem

Remove duplicate values (keep first occurrence).


Code
def remove_duplicates(d):
seen = set()
result = {}

for k, v in [Link]():
if v not in seen:
result[k] = v
[Link](v)

return result

# Example
print(remove_duplicates({'a':1,'b':2,'c':1,'d':3}))

Explanation

 Tracks seen values


 Skips duplicates

6. Top Sales (Highest N Values)


Problem

Find top N highest values from dictionary.

Code
def top_sales(d, n):
return dict(sorted([Link](), key=lambda x: x[1], reverse=True)[:n])

# Example
print(top_sales({'A':100,'B':300,'C':200}, 2))

Explanation

 Sort descending
 Slice top n items

7. Calculate Sum of Values


Problem

Find sum of all values in dictionary.


Code
def calculate_sum(d):
return sum([Link]())

# Example
print(calculate_sum({'a': 10, 'b': 20, 'c': 30}))

Explanation

 .values() gives all values


 sum() adds them

8. Common Key-Value Pairs


Problem

Find common key-value pairs in two dictionaries.

Code
def common_pairs(d1, d2):
return {k: d1[k] for k in d1 if k in d2 and d1[k] == d2[k]}

# Example
print(common_pairs({'a':1,'b':2}, {'b':2,'c':3}))

Explanation

 Checks both key and value equality

9. Create Dictionary from Lists


Problem

Create dictionary from two lists (keys and values).

Code
def create_dict(keys, values):
return dict(zip(keys, values))

# Example
print(create_dict(['a','b','c'], [1,2,3]))
Explanation

 zip() pairs elements


 dict() converts to dictionary

PYTHON PRACTICE SET 3

1. Calculate Average (calculateaverage /


avg)
Problem

Calculate the average of numbers in a list.

Code
def calculate_average(lst):
return sum(lst) / len(lst)

# Example
print(calculate_average([10, 20, 30, 40]))

Explanation

 sum(lst) → total of elements


 len(lst) → count of elements
 Average = Total / Count

2. Check Prime Number (isprime / prime)


Problem

Check whether a number is prime.

Code
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Example
print(is_prime(7))
Explanation

 Checks divisibility up to √n
 Optimized approach reduces time complexity

3. Guess Random Number Game


(guessrandom / random)
Problem

Generate a random number and let user guess it.

Code
import random

def guess_game():
num = [Link](1, 10)

while True:
guess = int(input("Enter your guess (1-10): "))

if guess == num:
print("Correct!")
break
elif guess < num:
print("Too low")
else:
print("Too high")

# guess_game()

Explanation

 [Link]() generates number


 Loop continues until correct guess

4. Palindrome Check (ispalindrome /


palindrome)
Problem

Check whether a string is a palindrome.


Code
def is_palindrome(s):
return s == s[::-1]

# Example
print(is_palindrome("madam"))

Explanation

 [::-1]reverses string
 Compare original with reversed

5. Find Maximum and Minimum


(findmaxmin / max)
Problem

Find maximum and minimum element in a list.

Code
def find_max_min(lst):
return max(lst), min(lst)

# Example
print(find_max_min([5, 2, 9, 1]))

Explanation

 max() returns largest value


 min() returns smallest value

6. Factorial (factorial / fact)


Problem

Calculate factorial of a number.

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

# Example
print(factorial(5))

Explanation

 Recursive approach
 n! = n × (n-1)!

7. Find Common Elements (common)


Problem

Find common elements between two lists.

Code
def common_elements(lst1, lst2):
return list(set(lst1) & set(lst2))

# Example
print(common_elements([1,2,3], [2,3,4]))

Explanation

 Converts lists to sets


 Uses intersection &

8. Find Treasures (findtreasures / hidden)


Problem

Find hidden treasures marked as "T" in a grid.

Code
def find_treasures(grid):
treasures = []

for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 'T':
[Link]((i, j))

return treasures
# Example
grid = [
['X', 'T', 'X'],
['T', 'X', 'X'],
['X', 'X', 'T']
]

print(find_treasures(grid))

Explanation

 Traverse 2D list using nested loops


 Store positions where treasure found

9. Average Using Loop (Manual avg)


Problem

Calculate average without using sum().

Code
def avg(lst):
total = 0
for num in lst:
total += num
return total / len(lst)

# Example
print(avg([10, 20, 30]))

Explanation

 Manually accumulates sum


 Useful for understanding logic

10. Iterative Factorial (fact)


Problem

Find factorial using loop.

Code
def fact(n):
result = 1
for i in range(1, n+1):
result *= i
return result

# Example
print(fact(5))

Explanation

 Iterative approach avoids recursion

11. Find Maximum Without Built-in (max)


Problem

Find maximum without using max().

Code
def find_max(lst):
maximum = lst[0]
for num in lst:
if num > maximum:
maximum = num
return maximum

# Example
print(find_max([3, 7, 2, 9]))

Explanation

 Compares each element


 Updates maximum value

12. Hidden Word Palindrome (hidden +


palindrome)
Problem

Check palindrome ignoring spaces and case.

Code
def hidden_palindrome(s):
s = [Link](" ", "").lower()
return s == s[::-1]

# Example
print(hidden_palindrome("A man a plan a canal Panama"))

Explanation

 Removes spaces
 Converts to lowercase
 Then checks palindrome

PYTHON ASSIGNMENT 2

1. Lambda Sort (Ascending by Value)


Problem

Sort a list of tuples based on the second element using a lambda function.

Code
data = [('a', 3), ('b', 1), ('c', 2)]

sorted_data = sorted(data, key=lambda x: x[1])

print(sorted_data)

Explanation

 lambda x: x[1] → extracts second element


 sorted() uses this as sorting key
 Output: [('b', 1), ('c', 2), ('a', 3)]

2. Lambda Sort (Descending Dictionary by


Value)
Problem

Sort a dictionary by values in descending order using lambda.

Code
d = {'a': 10, 'b': 5, 'c': 20}
result = dict(sorted([Link](), key=lambda x: x[1], reverse=True))

print(result)

Explanation

 [Link]() → key-value pairs


 Lambda picks value (x[1])
 reverse=True → descending order

3. Lambda Fibonacci Series


Problem

Generate Fibonacci series using lambda function.

Code
fib = lambda n: n if n <= 1 else fib(n-1) + fib(n-2)

series = [fib(i) for i in range(10)]


print(series)

Explanation

 Recursive lambda function


 Base case: n <= 1
 Builds Fibonacci sequence

4. Optimized Fibonacci using Lambda +


Map
Problem

Generate Fibonacci using map() and lambda.

Code
def fib(n):
a, b = 0, 1
result = []

for _ in range(n):
[Link](a)
a, b = b, a + b

return result

print(list(map(lambda x: x, fib(10))))

Explanation

 Lambda used with map()


 Iterative Fibonacci is efficient

5. Perfect Student Score (Filter High


Scorers)
Problem

Filter students who scored above 75 using lambda.

Code
students = {'A': 80, 'B': 65, 'C': 90, 'D': 70}

top_students = dict(filter(lambda x: x[1] > 75, [Link]()))

print(top_students)

Explanation

 filter() applies lambda condition


 Keeps only scores > 75

6. Student Score Sorting (Ranking System)


Problem

Sort students by score using lambda.

Code
students = {'A': 80, 'B': 65, 'C': 90}

ranking = sorted([Link](), key=lambda x: x[1], reverse=True)

print(ranking)
Explanation

 Sorts by value
 Useful for ranking systems

7. Find Index of Element using Lambda


Problem

Find index of elements greater than 50.

Code
lst = [10, 60, 30, 80, 40]

indexes = list(filter(lambda i: lst[i] > 50, range(len(lst))))

print(indexes)

Explanation

 Iterate over indexes


 Filter based on condition

8. Student Index with Max Score


Problem

Find index of student with maximum score.

Code
scores = [45, 88, 76, 90, 67]

max_index = max(range(len(scores)), key=lambda i: scores[i])

print(max_index)

Explanation

 range(len(scores)) → indexes
 Lambda compares values using index
9. Perfect Score Students (Score = 100)
Problem

Find students who scored exactly 100.

Code
students = {'A': 100, 'B': 98, 'C': 100}

perfect = list(filter(lambda x: x[1] == 100, [Link]()))

print(perfect)

Explanation

 Filters exact match condition

10. Lambda Sort Multiple Conditions


Problem

Sort students by score, then by name.

Code
students = [('A', 90), ('C', 90), ('B', 85)]

sorted_students = sorted(students, key=lambda x: (-x[1], x[0]))

print(sorted_students)

Explanation

 -x[1] → descending score


 x[0] → ascending name

11. Lambda for Even Fibonacci Numbers


Problem

Filter even Fibonacci numbers.

Code
fib = [0, 1, 1, 2, 3, 5, 8, 13]

even_fib = list(filter(lambda x: x % 2 == 0, fib))

print(even_fib)

Explanation

 Filters even numbers using lambda

12. Average Student Score using Lambda


Problem

Calculate average using lambda.

Code
scores = [80, 90, 70, 60]

average = (lambda lst: sum(lst) / len(lst))(scores)

print(average)

Explanation

 Lambda used as inline function


 Immediately invoked

1. Create a Dictionary
Problem

Create a dictionary with keys as names and values as marks.

Code
def create_dict():
d = {'Alice': 85, 'Bob': 90, 'Charlie': 78}
return d

print(create_dict())

Explanation

 Dictionary stores key-value pairs


 Keys must be unique
2. Access Dictionary Elements
Problem

Access the value of a given key safely.

Code
def access_value(d, key):
return [Link](key, "Key not found")

print(access_value({'a': 1, 'b': 2}, 'a'))

Explanation

 .get() avoids errors if key is missing

3. Update Dictionary Value


Problem

Update value of a specific key.

Code
def update_value(d, key, value):
d[key] = value
return d

print(update_value({'a': 1}, 'a', 10))

Explanation

 Direct assignment updates value

4. Delete a Key
Problem

Remove a key from dictionary.


Code
def delete_key(d, key):
[Link](key, None)
return d

print(delete_key({'a':1,'b':2}, 'b'))

Explanation

 .pop() removes key safely

5. Check Key Existence


Problem

Check if key exists in dictionary.

Code
def check_key(d, key):
return key in d

print(check_key({'a':1,'b':2}, 'a'))

Explanation

 in operator checks existence

6. Iterate Through Dictionary


Problem

Print all key-value pairs.

Code
def iterate_dict(d):
for k, v in [Link]():
print(k, v)

iterate_dict({'a':1,'b':2})

Explanation
 .items() returns pairs

7. Count Frequency of Elements


Problem

Count frequency of elements in a list using dictionary.

Code
def frequency(lst):
freq = {}
for item in lst:
freq[item] = [Link](item, 0) + 1
return freq

print(frequency([1,2,2,3,1,1]))

Explanation

 .get() handles missing keys

8. Merge Two Dictionaries


Problem

Merge two dictionaries.

Code
def merge_dict(d1, d2):
return {**d1, **d2}

print(merge_dict({'a':1}, {'b':2}))

Explanation

 ** unpacks dictionaries

9. Find Maximum Value Key


Problem
Find key with highest value.

Code
def max_key(d):
return max(d, key=[Link])

print(max_key({'a':5,'b':10,'c':7}))

Explanation

 [Link] used for comparison

10. Sort Dictionary by Value


Problem

Sort dictionary based on values.

Code
def sort_dict(d):
return dict(sorted([Link](), key=lambda x: x[1]))

print(sort_dict({'a':3,'b':1,'c':2}))

Explanation

 Lambda extracts values

11. Remove Duplicate Values


Problem

Remove duplicate values.

Code
def remove_duplicates(d):
seen = set()
result = {}
for k, v in [Link]():
if v not in seen:
result[k] = v
[Link](v)
return result
print(remove_duplicates({'a':1,'b':2,'c':1}))

Explanation

 Uses set to track duplicates

12. Dictionary from Two Lists


Problem

Create dictionary using two lists.

Code
def create_from_lists(keys, values):
return dict(zip(keys, values))

print(create_from_lists(['a','b'], [1,2]))

Explanation

 zip() pairs elements

13. Nested Dictionary Access


Problem

Access nested dictionary value.

Code
def nested_access(d):
return d['student']['marks']

data = {'student': {'marks': 90}}


print(nested_access(data))

Explanation

 Access step-by-step
14. Sum of Values
Problem

Find sum of all values.

Code
def sum_values(d):
return sum([Link]())

print(sum_values({'a':10,'b':20}))

Explanation

 .values() gives all values

15. Invert Dictionary


Problem

Swap keys and values.

Code
def invert_dict(d):
return {v: k for k, v in [Link]()}

print(invert_dict({'a':1,'b':2}))

Explanation

 Dictionary comprehension

16. Filter Dictionary


Problem

Filter values greater than 10.

Code
def filter_dict(d):
return {k:v for k,v in [Link]() if v > 10}
print(filter_dict({'a':5,'b':15,'c':20}))

Explanation

 Conditional comprehension

17. Count Keys


Problem

Find number of keys.

Code
def count_keys(d):
return len(d)

print(count_keys({'a':1,'b':2}))

Explanation

 len() returns number of keys

18. Common Keys Between Dictionaries


Problem

Find common keys.

Code
def common_keys(d1, d2):
return [Link]() & [Link]()

print(common_keys({'a':1,'b':2}, {'b':3,'c':4}))

Explanation

 Set intersection

19. Default Value Handling


Problem

Assign default value if key missing.

Code
def default_dict(d, key):
return [Link](key, 0)

data = {'a':1}
print(default_dict(data, 'b'))
print(data)

Explanation

 setdefault() inserts if missing

20. Group Values by Key Pattern


Problem

Group words by first letter.

Code
def group_words(words):
result = {}
for word in words:
key = word[0]
[Link](key, []).append(word)
return result

print(group_words(['apple','banana','apricot']))

Explanation

 Groups based on first character

You might also like