**Prepare Well**
Question 1: How do you create a list and add elements dynamically?
#Create a list and add numbers dynamically
Question 2: How do you merge two dictionaries? If you give same key it will overwrite the values and wont update.
a={'name':'suchi','age':10,'city':'bangalore'}
b={'name1':'baby'}
c={'name2':'baby','mom2':'suchi'}
print("Other way to merge is : ",{**a,**b,**c})
a.update(b)
print(a)
Question 3: How do you iterate through an array and calculate the sum of its elements?
Question 4: How do you assign multiple values to variables at once through input ?
# taking multiple inputs at a time
x, y, z = input("Values: ").split()
print(x)
print(y)
print(z)
Question 5: How do you create a hash table using a dictionary in Python and retrieve a value?
#hash table
hash_table={'name':"Suchitra",'Job':'Engineer'}
print(hash_table.get('Job'))
Question 6: How do you concatenate two strings and find the length of the resulting string?
#Concatenate Stringsa="Hello"
b="World"
print(len(a+b))
Question 7: How do you use list comprehension to create a list of squares of numbers from 1-10?
#List comprehensions to find square of all numbers from 1-10
sq=[x**2 for x in range(1,11)]
print(sq)
Question 8: How do you filter even numbers from a list using a list comprehension?
#Filter even numbers
x=[x for x in range(1,11) if x%2==0]
print(x)
Question 9: How do you use a lambda function to sort a list of tuples based on the second element?
# List of tuples
tuples_list = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
# Sorting the list of tuples based on the second element
sorted_list=sorted(tuples_list,key=lambda x:x[1])
print(sorted_list)Question 10: Exception Handling -
try
,except
,finally
, andraise
statements?def division(a,b):
try:
c=a/b
print(c)
except ZeroDivisionError as e:
print(e)raise #This will show the errror msg as well, if this line is deleted then exception will be hiddenelse:
print("Output is",int(c))
finally:
print("completed")
division(10,0)Question 11: How do you merge two dictionaries in Python?
#merge dict
a={'name':'suni','age':10}
b={'class':'1','love':'no'}
print({**a,**b})Question 12: How do you use the
map()
function to apply a function to all elements in a list?#add -PM to all the elements of a list using map
def addPM(x):
return x+"-PM"
print(addPM("Hello"))
a=["Suchitra","Cutie","Baby","Hello","Welcome","Bye"]
output=list(map(addPM,a))
print(output)Hello-PM ['Suchitra-PM', 'Cutie-PM', 'Baby-PM', 'Hello-PM', 'Welcome-PM', 'Bye-PM'] Process finished with exit code 0Question 13: How do you use a dictionary comprehension to create a dictionary with keys as numbers from 1 to 5 and values as their squares?
#Dictionary Comprehension
x={x:x*x for x in range(1,6)}
print(x)
#List Comprehension- Mind the difference please []/{}
x=[x*x for x in range(1,6)]
print(x){1: 1, 2: 4, 3: 9, 4: 16, 5: 25} [1, 4, 9, 16, 25]Question 14: How do you use the
filter()
function to filter out odd numbers from a list?x=[x for x in range(1,21)]
print(x)
filterout=list(filter(lambda x:x%2!=0,x))
print(filterout)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]Question 15 : How do you use a set to remove duplicates from a list?
numbers = [1, 2, 2, 3, 4, 4, 5]
print(list(set(numbers)))[1, 2, 3, 4, 5]Question 16: How do you use the
zip()
function to combine two lists into a list of tuples?a=[x for x in range(1,10)]
b=[y*y for y in range(1,10)]
print(list(zip(a,b)))[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]Question 17: Function to Find the Maximum and Minimum Numbers in a List
a=[x for x in range(1,10)]
b=[y*y for y in range(1,10)]
print(max(a),min(b))
print(list(zip(a,b)))9 1 [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)] Process finished with exit code 0Question 18 : Creating a Nested List
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(nested_list)
Question 19 : Flattening a Nested List
nested_list=[[1,2,3],[4,5,6]]
print(nested_list)
flatt=[items for sublist in nested_list for items in sublist]
print(flatt)[[1, 2, 3], [4, 5, 6]] [1, 2, 3, 4, 5, 6]Question 20 : Sorting a List in Ascending and Descending Order
nested_list=[[1,2,3],[4,5,6]]
print(nested_list)
flatt=[items for sublist in nested_list for items in sublist]
print(flatt)
print(sorted(flatt,reverse=True),sorted(flatt))[[1, 2, 3], [4, 5, 6]] [1, 2, 3, 4, 5, 6] [6, 5, 4, 3, 2, 1] [1, 2, 3, 4, 5, 6]Question 21: Merging Two Sorted Lists into One Sorted List
nested_list=[[1,2,3],[4,5,6]]
print(nested_list)
flatt=[items for sublist in nested_list for items in sublist]
print(flatt)
a=sorted(flatt,reverse=True)
b=sorted(flatt)
print(sorted(a+b))[[1, 2, 3], [4, 5, 6]] [1, 2, 3, 4, 5, 6] [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]Question 22 : Finding the Intersection of Two Lists
x=[1,2,3,4,5]
y=[90,5,4,89,67]
z=set(x)&set(y)
print(z){4, 5}Question 23 : How do you retrieve a value from a dictionary using a key?a={'name':'Suchi','city':'Bnglr'}
print(a.get('city'))BnglrQuestion 24: How do you iterate through a dictionary and print key-valuepairs?
mydict={'roll':'one','name':'two','3':'three','4':'four'}Key is roll and value is one Key is name and value is two Key is 3 and value is three Key is 4 and value is four
for key,value in mydict.items():
print(f"Key is {key} and value is {value}")Question 25. Write a program to convert dict to list and vice-versa.
#dict to list
a={'name':'lohan','age':10,'city':'Mysore','place':'Karnataka'}
lista=list(a.keys())
listb=list(a.values())
print(lista+listb)
#list to dict
new_dict = {lista[i]: listb[i] for i in range(len(lista))}
print(new_dict)
#or
print(dict(zip(lista,listb)))Question 26. Write a program to count the frequency of elements in a list using a dictionary.
lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4,10,10,10]
freq={}
for i in lst:
if i in freq:
freq[i]+=1
else:
freq[i]=1
print(freq){1: 1, 2: 2, 3: 3, 4: 4, 10: 3}Question 27: How do you remove a key-value pair from a dictionary?
a={'name':'lohan','age':10,'city':'Mysore','place':'Karnataka'}
a.pop("place")
print(a){'name': 'lohan', 'age': 10, 'city': 'Mysore'}Question 28: How do you check if a key exists in a dictionary?
a={'name':'lohan','age':10,'city':'Mysore','place':'Karnataka'}
a.pop("place")
print(a)
print("place" not in a)
print("place" in a){'name': 'lohan', 'age': 10, 'city': 'Mysore'} True FalseQuestion 29 :Write a function to invert keys and values in a dictionary.
a={'name':'lohan','age':10,'city':'Mysore','place':'Karnataka'}
invert={}
for key,value in a.items():
invert[value]=key
print(invert){'lohan': 'name', 10: 'age', 'Mysore': 'city', 'Karnataka': 'place'}Question 30 : How do you get all keys and values from a dictionary?
a={'name':'lohan','age':10,'city':'Mysore','place':'Karnataka'}
invert={}
for key,value in a.items():
key=a.keys()
value=a.values()
print(key,value):: ARRAYS ::In Python, you can create an array using thearray
moduleQuestion 31. How do you create an array in Python?
import array as ar
arr=ar.array('i',[1,2,3,4,5])
print(arr)Question 32. Write a program to reverse an array.
import array as ar
arr=ar.array('i',[1,2,3,4,5])
rev=arr[::-1]
print(rev)Question 33. How do you find the sum of elements in an array?import array as ar
arr=ar.array('i',[1,2,3,4,5])
rev=sum(arr)
print(rev)Question 34. Write a program to find the second largest element in an array.
import array as ar
arr=ar.array('i',[1,2,3,10,5])
sort=sorted(arr)
print(sort[-2])5
Question 35. How do you iterate through an array and calculate the square of each element?
import array as ar
arr=ar.array('i',[1,2,3,10,5])
sq=ar.array('i',(x**2 for x in arr))
print(sq)array('i', [1, 4, 9, 100, 25])
Question 36. How do you find the maximum and minimum elements in an array?
import array as ar
arr=ar.array('i',[1,2,3,10,5])
maxi=max(arr)
mini=min(arr)
print(maxi,mini)10 1
Question 37. Write a program to rotate an array by a given number of positions.
import array as ar
def rotate_array(arr,pos):
return arr[pos:]+arr[:pos]
arr=ar.array('i',[1,2,3,10,5])
rot=rotate_array(arr,2)
print(rot)array('i', [3, 10, 5, 1, 2])Question 38. How do you merge two arrays?
import array as ar
arr=ar.array('i',[1,2,3,10,5])
arr1=ar.array('i',[21,22,23,24,90])
print(arr+arr1)array('i', [1, 2, 3, 10, 5, 21, 22, 23, 24, 90])Question 39. Write a function to check if an array is sorted.
import array as ar
arr=ar.array('i',[1,2,3,10,5])
arr1=ar.array('i',[21,22,23,24,90])
print(arr1 == ar.array('i',sorted(arr1)))
print(arr == ar.array('i',sorted(arr)))True False
Question 40. How do you remove duplicates from an array?
import array as ar
arr = ar.array('i', [1, 2, 2, 3, 3, 3, 10, 5])
unique_arr = ar.array('i', sorted(set(arr), key=arr.index))
print(unique_arr)array('i', [1, 2, 3, 10, 5])
:: HASHES ::
Question 41. What is a hash in Python?
A hash in Python is a fixed-size integer that uniquely identifies data. It is generated by a hash function, which takes input data and returns a hash value. Hashes are commonly used in data structures like hash tables and for data integrity checks.
Question 42. Write a program to hash a string using SHA256.
You can hash a string using the
hashlib
module in Python.import hashlib def hash_string_sha256(s): return hashlib.sha256(s.encode()).hexdigest() # Example usage hashed_string = hash_string_sha256("hello") print(hashed_string)
Explanation:
import hashlib
: Imports thehashlib
module.hashlib.sha256(s.encode()).hexdigest()
: Hashes the strings
using SHA256 and returns the hexadecimal representation.print(hashed_string)
: Prints the hashed string.Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
43. How do you calculate the hash of an integer?
You can calculate the hash of an integer using the built-in
hash()
function.num = 42 hashed_num = hash(num) print(hashed_num)
Explanation:
hash(num)
: Calculates the hash of the integernum
.print(hashed_num)
: Prints the hashed integer.Output:
42
44. How do you create a hash table in Python?
You can create a hash table in Python using a dictionary.
hash_table = {}
Explanation:
{}
: Creates an empty dictionary, which can be used as a hash table.45. Write a program to perform insert, delete, and lookup operations on a hash table.
You can perform these operations using a dictionary.
# Create a hash table hash_table = {} # Insert operation hash_table['name'] = 'Alice' hash_table['age'] = 25 # Lookup operation print("Name:", hash_table.get('name')) print("Age:", hash_table.get('age')) # Delete operation del hash_table['age'] print("Hash table after deletion:", hash_table)
Explanation:
hash_table['name'] = 'Alice'
: Inserts a key-value pair into the hash table.hash_table.get('name')
: Looks up the value associated with the key'name'
.del hash_table['age']
: Deletes the key-value pair with the key'age'
.print(hash_table)
: Prints the hash table.Output:
Name: Alice Age: 25 Hash table after deletion: {'name': 'Alice'}
46. How do you handle collisions in a hash table?
Collisions in a hash table can be handled using various techniques, such as chaining (using linked lists) or open addressing (probing). Here's an example using chaining:
class HashTable: def __init__(self): self.table = [[] for _ in range(10)] def _hash(self, key): return hash(key) % len(self.table) def insert(self, key, value): index = self._hash(key) for kvp in self.table[index]: if kvp[0] == key: kvp[1] = value return self.table[index].append([key, value]) def lookup(self, key): index = self._hash(key) for kvp in self.table[index]: if kvp[0] == key: return kvp[1] return None def delete(self, key): index = self._hash(key) for i, kvp in enumerate(self.table[index]): if kvp[0] == key: del self.table[index][i] return # Example usage ht = HashTable() ht.insert('name', 'Alice') ht.insert('age', 25) print("Name:", ht.lookup('name')) print("Age:", ht.lookup('age')) ht.delete('age') print("Age after deletion:", ht.lookup('age'))
Explanation:
self.table = [[] for _ in range(10)]
: Initializes the hash table with 10 empty lists (buckets)._hash(self, key)
: Computes the hash index for a given key.insert(self, key, value)
: Inserts a key-value pair into the hash table, handling collisions by appending to the list at the computed index.lookup(self, key)
: Looks up the value associated with a key.delete(self, key)
: Deletes a key-value pair from the hash table.Output:
Name: Alice Age: 25 Age after deletion: None
47. Write a program to count the frequency of characters in a string using a hash table.
You can count the frequency of characters using a dictionary.
def count_char_frequency(s): frequency = {} for char in s: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 return frequency # Example usage s = "hello world" print(count_char_frequency(s))
Explanation:
frequency = {}
: Initializes an empty dictionary to store character frequencies.for char in s
: Iterates over each character in the strings
.frequency[char] += 1
: Increments the count if the character is already in the dictionary.frequency[char] = 1
: Adds the character to the dictionary with a count of 1 if it is not already present.print(count_char_frequency(s))
: Prints the character frequencies.Output:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
48. How do you check if two strings are anagrams using hashes?
You can check if two strings are anagrams by comparing their character frequencies.
def are_anagrams(s1, s2): def char_frequency(s): frequency = {} for char in s: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 return frequency return char_frequency(s1) == char_frequency(s2) # Example usage s1 = "listen" s2 = "silent" print(are_anagrams(s1, s2))
Explanation:
char_frequency(s)
: A helper function that returns the character frequency of a string.are_anagrams(s1, s2)
: Compares the character frequencies ofs1
ands2
.print(are_anagrams(s1, s2))
: Prints whether the strings are anagrams.Output:
True
49. Write a program to find the first non-repeating character in a string using a hash.
You can find the first non-repeating character by counting character frequencies and then iterating through the string.
def first_non_repeating_char(s): frequency = {} for char in s: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 for char in s: if frequency[char] == 1: return char return None # Example usage s = "swiss" print(first_non_repeating_char(s))
Explanation:
frequency = {}
: Initializes an empty dictionary to store character frequencies.for char in s
: Iterates over each character in the strings
to count frequencies.for char in s
: Iterates over each character again to find the first non-repeating character.return char
: Returns the first non-repeating character.return None
: ReturnsNone
if no non-repeating character is found.print(first_non_repeating_char(s))
: Prints the first non-repeating character.Output:
w
50. How do you implement a custom hash function?
You can implement a custom hash function by defining a function that takes a key and returns a hash value.
def custom_hash(key): hash_value = 0 for char in key: hash_value += ord(char) return hash_value # Example usage key = "hello" print(custom_hash(key))
Explanation:
hash_value = 0
: Initializes the hash value to 0.for char in key
: Iterates over each character in the key.hash_value += ord(char)
: Adds the ASCII value of the character to the hash value.return hash_value
: Returns the computed hash value.print(custom_hash(key))
: Prints the hash value of the key.Output:
532
:: STRING MANIPULATION ::
51. Reverse a String
a="hello"
print(a[::-1])olleh52. Check if a String is a Palindrome
a="hello"
b="Madam"
c="madam"
print(a==a[::-1], b==b[::-1], c==c[::-1])False False True53. Count Vowels in a String
a="helloO"
vowel=['a','e','i','o','u','A','E','I','O','U'] #you can also use vowel="aeiouAEIOU"
count=0
for i in vowel:
if i in a:
print(i)
count+=1
print(count)e o O 3
54. Replace a Substring in a String
a="I Love you"
print(a.replace("Love","Hate"))I Hate you
55. Split a String by Spaces and Join it Back with Hyphens
a="I Love you"
b=a.split(" ")
print(b)
print("-".join(b))['I', 'Love', 'you'] I-Love-you
56. Find All Substrings of a String
def all_substrings(s): substrings = [s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)] return substrings print(all_substrings("abc")) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']
57. Remove Duplicate Characters from a String
def remove_duplicates(s): return ''.join(sorted(set(s), key=s.index)) print(remove_duplicates("hello")) # Output: "helo"
58. Find the Longest Common Prefix of a List of Strings
def longest_common_prefix(strs): if not strs: return "" prefix = strs[0] for s in strs[1:]: while s[:len(prefix)] != prefix and prefix: prefix = prefix[:len(prefix)-1] return prefix print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"
59. Count the Frequency of Words in a String
from collections import Counter
a="hello world"
print(Counter(a))Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})60. Implement Binary Search on a Sorted List
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
61. Implement Bubble Sort Algorithm
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([64, 34, 25, 12, 22, 11, 90])) # Output: [11, 12, 22, 25, 34, 64, 90]
62. Find the Factorial of a Number Using Recursion
def fact(x):
if x==0:
return 1
else:
return x*fact(x-1)
print(fact(5))#Output: 12063. Find the Fibonacci Sequence Up to a Given Number
def fibonacci(n): fib_sequence = [0, 1] while fib_sequence[-1] + fib_sequence[-2] < n: fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) return fib_sequence print(fibonacci(100)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
64. Check if a Number is Prime
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True print(is_prime(29)) # Output: True print(is_prime(10)) # Output: False
65. Implement a Stack Using a List
class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): if not self.is_empty(): return self.stack.pop() return None def is_empty(self): return len(self.stack) == 0 def peek(self): if not self.is_empty(): return self.stack[-1] return None stack = Stack() stack.push(1) stack.push(2) print(stack.pop()) # Output: 2 print(stack.peek()) # Output: 1
66. Implement a Queue Using a List
class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if not self.is_empty(): return self.queue.pop(0) return None def is_empty(self): return len(self.queue) == 0 def peek(self): if not self.is_empty(): return self.queue[0] return None queue = Queue() queue.enqueue(1) queue.enqueue(2) print(queue.dequeue()) # Output: 1 print(queue.peek()) # Output: 2
67. Find the GCD of Two Numbers Using Recursion
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) print(gcd(48, 18)) # Output: 6
68. Find the LCM of Two Numbers
def lcm(a, b): def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) return abs(a * b) // gcd(a, b) print(lcm(12, 15)) # Output: 60
:: ADVANCED TOPIC ::
69. Implement Quicksort on a List
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print(quicksort([3, 6, 8, 10, 1, 2, 1])) # Output: [1, 1, 2, 3, 6, 8, 10]
70. Implement a Linked List
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def print_list(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") # Example usage ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.print_list() # Output: 1 -> 2 -> 3 -> None
71. Detect a Cycle in a Linked List
def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False # Example usage # Create a linked list with a cycle for testing head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = head.next # Create a cycle print(has_cycle(head)) # Output: True
72. Find the Middle Element of a Linked List
def find_middle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data # Example usage ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.append(4) ll.append(5) print(find_middle(ll.head)) # Output: 3
73. Reverse a Linked List
def reverse_list(head): prev = None current = head while current: next_node = current.next current.next = prev prev = current current = next_node return prev # Example usage ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.head = reverse_list(ll.head) ll.print_list() # Output: 3 -> 2 -> 1 -> None
74. Implement a Binary Tree and Its Traversal
class TreeNode: def __init__(self, data): self.data = data self.left = self.right = None def inorder_traversal(root): if root: inorder_traversal(root.left) print(root.data, end=" ") inorder_traversal(root.right) # Example usage root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) inorder_traversal(root) # Output: 4 2 5 1 3
75. Find the Height of a Binary Tree
def find_height(root): if not root: return 0 left_height = find_height(root.left) right_height = find_height(root.right) return max(left_height, right_height) + 1 # Example usage print(find_height(root)) # Output: 3
76. Find the Maximum Element in a Binary Tree
def find_max(root): if not root: return float('-inf') left_max = find_max(root.left) right_max = find_max(root.right) return max(root.data, left_max, right_max) # Example usage print(find_max(root)) # Output: 5
77. Implement Depth-First Search on a Graph
def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start, end=" ") for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited) # Example usage graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } dfs(graph, 'A') # Output: A B D E F C
78. Implement Breadth-First Search on a Graph
from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start) while queue: vertex = queue.popleft() print(vertex, end=" ") for neighbor in graph[vertex]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) # Example usage bfs(graph, 'A') # Output: A B C D E F
79. Find the Shortest Path in a Weighted Graph Using Dijkstra’s Algorithm
import heapq def dijkstra(graph, start): distances = {vertex: float('infinity') for vertex in graph} distances[start] = 0 priority_queue = [(0, start)] while priority_queue: current_distance, current_vertex = heapq.heappop(priority_queue) if current_distance > distances[current_vertex]: continue for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances # Example usage graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } print(dijkstra(graph, 'A')) # Output: {'A': 0, 'B': 1, 'C': 3, 'D': 4}
Sure! Let's start with number 80 and work our way up with explanations for each.
80. Find the Kth Largest Element in a List
import heapq def kth_largest(nums, k): return heapq.nlargest(k, nums)[-1] # Example usage nums = [3, 2, 1, 5, 6, 4] k = 2 print(kth_largest(nums, k)) # Output: 5
Explanation:
- Import the
heapq
Module:import heapq
The
heapq
module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
- Define the Function:
def kth_largest(nums, k):
This function takes a list
nums
and an integerk
as input.
- Find the K Largest Elements:
return heapq.nlargest(k, nums)[-1]
The
heapq.nlargest(k, nums)
function returns thek
largest elements from the listnums
in descending order. The[-1]
index retrieves the last element from this list, which is thek
th largest element.
- Example Usage:
nums = [3, 2, 1, 5, 6, 4] k = 2 print(kth_largest(nums, k)) # Output: 5
This example finds the 2nd largest element in the list
[3, 2, 1, 5, 6, 4]
, which is5
.81. Find Duplicates in a List
def find_duplicates(nums): seen = set() duplicates = set() for num in nums: if num in seen: duplicates.add(num) else: seen.add(num) return list(duplicates) # Example usage nums = [1, 2, 3, 4, 5, 3, 2] print(find_duplicates(nums)) # Output: [2, 3]
Explanation:
- Define the Function:
def find_duplicates(nums):
This function takes a list
nums
as input.
- Initialize Sets:
seen = set() duplicates = set()
Two sets are initialized:
seen
to keep track of elements that have been encountered, andduplicates
to store duplicate elements.
- Iterate Through the List:
for num in nums: if num in seen: duplicates.add(num) else: seen.add(num)
For each element in the list, check if it is already in the
seen
set. If it is, add it to theduplicates
set. Otherwise, add it to theseen
set.
- Return the Duplicates:
return list(duplicates)
Convert the
duplicates
set to a list and return it.
- Example Usage:
nums = [1, 2, 3, 4, 5, 3, 2] print(find_duplicates(nums)) # Output: [2, 3]
This example finds the duplicate elements in the list
[1, 2, 3, 4, 5, 3, 2]
, which are2
and3
.82. Check if a List is a Subset of Another List
def is_subset(list1, list2): return set(list1).issubset(set(list2)) # Example usage list1 = [1, 2, 3] list2 = [1, 2, 3, 4, 5] print(is_subset(list1, list2)) # Output: True
Explanation:
- Define the Function:
def is_subset(list1, list2):
This function takes two lists
list1
andlist2
as input.
- Check Subset:
return set(list1).issubset(set(list2))
Convert both lists to sets and use the
issubset
method to check iflist1
is a subset oflist2
.
- Example Usage:
list1 = [1, 2, 3] list2 = [1, 2, 3, 4, 5] print(is_subset(list1, list2)) # Output: True
This example checks if
[1, 2, 3]
is a subset of[1, 2, 3, 4, 5]
, which isTrue
.83. Find the Union and Intersection of Two Sets
def union_and_intersection(set1, set2): union = set1.union(set2) intersection = set1.intersection(set2) return union, intersection # Example usage set1 = {1, 2, 3} set2 = {2, 3, 4} union, intersection = union_and_intersection(set1, set2) print("Union:", union) # Output: Union: {1, 2, 3, 4} print("Intersection:", intersection) # Output: Intersection: {2, 3}
Explanation:
- Define the Function:
def union_and_intersection(set1, set2):
This function takes two sets
set1
andset2
as input.
- Find Union:
union = set1.union(set2)
Use the
union
method to find the union ofset1
andset2
.
- Find Intersection:
intersection = set1.intersection(set2)
Use the
intersection
method to find the intersection ofset1
andset2
.
- Return Results:
return union, intersection
Return the union and intersection as a tuple.
- Example Usage:
set1 = {1, 2, 3} set2 = {2, 3, 4} union, intersection = union_and_intersection(set1, set2) print("Union:", union) # Output: Union: {1, 2, 3, 4} print("Intersection:", intersection) # Output: Intersection: {2, 3}
This example finds the union and intersection of
{1, 2, 3}
and{2, 3, 4}
.84. Calculate the Power Set of a List
from itertools import chain, combinations def power_set(lst): return list(chain.from_iterable(combinations(lst, r) for r in range(len(lst) + 1))) # Example usage lst = [1, 2, 3] print(power_set(lst)) # Output: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Explanation:
- Import Modules:
from itertools import chain, combinations
Import the
chain
andcombinations
functions from theitertools
module.
- Define the Function:
def power_set(lst):
This function takes a list
lst
as input.
- Generate Power Set:
return list(chain.from_iterable(combinations(lst, r) for r in range(len(lst) + 1)))
Use a generator expression to create combinations of all lengths (from 0 to the length of the list). Use
chain.from_iterable
to flatten the list of combinations into a single list.
- Example Usage:
lst = [1, 2, 3] print(power_set(lst)) # Output: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
This example generates the power set of
[1, 2, 3]
.85. Shuffle a List Randomly
import random def shuffle_list(lst): random.shuffle(lst) return lst # Example usage lst = [1, 2, 3, 4, 5] print(shuffle_list(lst)) # Output: [3, 1, 5, 2, 4] (example output, will vary)
Explanation:
- Import the
random
Module:import random
The
random
module provides functions for generating random numbers and performing random operations.
- Define the Function:
def shuffle_list(lst):
This function takes a list
lst
as input.
- Shuffle the List:
random.shuffle(lst)
Use the
random.shuffle
Sure, let's continue from where we left off.86. Shuffle a List Randomly (continued)
Use the `random.shuffle(lst)` function to shuffle the elements of the list in place. 4. **Return the Shuffled List**:
python return lst
Return the shuffled list. 5. **Example Usage**:
python lst = [1, 2, 3, 4, 5] print(shuffle_list(lst)) # Output: [3, 1, 5, 2, 4] (example output, will vary)
This example shuffles the list `[1, 2, 3, 4, 5]`. The output will vary each time the function is called. ### 74. Generate All Permutations of a List
python from itertools import permutations
def all_permutations(lst): return list(permutations(lst))
Example usage
lst = [1, 2, 3] print(all_permutations(lst)) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
### Explanation: 1. **Import the `permutations` Function**:
python from itertools import permutations
Import the `permutations` function from the `itertools` module. 2. **Define the Function**:
python def all_permutations(lst):
This function takes a list `lst` as input. 3. **Generate Permutations**:
python return list(permutations(lst))
Use the `permutations` function to generate all possible permutations of the list and convert the result to a list. 4. **Example Usage**:
python lst = [1, 2, 3] print(all_permutations(lst)) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
This example generates all permutations of the list `[1, 2, 3]`. ### 73. Calculate the Sum of Elements in a Nested List
python def sumnestedlist(lst): total = 0 for element in lst: if isinstance(element, list): total += sumnestedlist(element) else: total += element return total
Example usage
nestedlist = [1, [2, 3], [4, [5, 6]], 7] print(sumnestedlist(nestedlist)) # Output: 28
### Explanation: 1. **Define the Function**:
python def sumnestedlist(lst):
This function takes a nested list `lst` as input. 2. **Initialize Total**:
python total = 0
Initialize a variable `total` to keep track of the sum. 3. **Iterate Through the List**:
python for element in lst: if isinstance(element, list): total += sumnestedlist(element) else: total += element
For each element in the list, check if it is a list. If it is, recursively call `sum_nested_list` to sum the elements of the nested list. Otherwise, add the element to `total`. 4. **Return the Total**:
python return total
Return the total sum. 5. **Example Usage**:
python nestedlist = [1, [2, 3], [4, [5, 6]], 7] print(sumnestedlist(nestedlist)) # Output: 28
This example calculates the sum of the elements in the nested list `[1, [2, 3], [4, [5, 6]], 7]`, which is `28`. ### 87. Convert a List of Tuples into a Dictionary
python def listtodict(lst): return dict(lst)
Example usage
lst = [('a', 1), ('b', 2), ('c', 3)] print(listtodict(lst)) # Output: {'a': 1, 'b': 2, 'c': 3}
### Explanation: 1. **Define the Function**:
python def listtodict(lst):
This function takes a list of tuples `lst` as input. 2. **Convert to Dictionary**:
python return dict(lst)
Use the `dict` constructor to convert the list of tuples into a dictionary. 3. **Example Usage**:
python lst = [('a', 1), ('b', 2), ('c', 3)] print(listtodict(lst)) # Output: {'a': 1, 'b': 2, 'c': 3}
This example converts the list of tuples `[('a', 1), ('b', 2), ('c', 3)]` into the dictionary `{'a': 1, 'b': 2, 'c': 3}`. ### 88. Convert a List to a String and Vice Versa
python def listtostring(lst): return ' '.join(map(str, lst))
def stringtolist(s): return s.split()
Example usage
lst = [1, 2, 3, 4, 5] s = "1 2 3 4 5" print(listtostring(lst)) # Output: "1 2 3 4 5" print(stringtolist(s)) # Output: ['1', '2', '3', '4', '5']
### Explanation: 1. **Convert List to String**:
python def listtostring(lst): return ' '.join(map(str, lst))
This function takes a list `lst` as input and converts it to a string. The `map(str, lst)` function converts each element of the list to a string, and `' '.join(...)` joins the elements with spaces. 2. **Convert String to List**:
python def stringtolist(s): return s.split()
This function takes a string `s` as input and converts it to a list. The `split()` method splits the string by spaces and returns a list of substrings. 3. **Example Usage**:
python lst = [1, 2, 3, 4, 5] s = "1 2 3 4 5" print(listtostring(lst)) # Output: "1 2 3 4 5" print(stringtolist(s)) # Output: ['1', '2', '3', '4', '5']
`` This example converts the list
[1, 2, 3, 4, 5]to the string
"1 2 3 4 5"and the string
"1 2 3 4 5"to the list
['1', '2', '3', '4', '5']`.Sure! Let's go through each of these topics with code examples and explanations.
81. How do you write test cases for a function in Python?
You can use the
unittest
module to write test cases for a function in Python.import unittest def add(a, b): return a + b class TestAddFunction(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-1, 1), 0) self.assertEqual(add(0, 0), 0) if __name__ == '__main__': unittest.main()
Output:
... ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
82. Write a program to validate an email address using regex.
import re def validate_email(email): pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
return re.match(pattern, email) is not None # Example usage print(validate_email("test@example.com")) # Output: True print(validate_email("invalid-email")) # Output: False
83. How do you mock a function in Python?
You can use the
unittest.mock
module to mock a function in Python.from unittest.mock import patch def get_data(): return "Real Data" def process_data(): data = get_data() return f"Processed {data}" # Example usage with patch('__main__.get_data', return_value="Mock Data"): print(process_data()) # Output: Processed Mock Data
84. Write a program to test if a list is sorted.
def is_sorted(lst): return lst == sorted(lst) # Example usage print(is_sorted([1, 2, 3, 4, 5])) # Output: True print(is_sorted([5, 3, 1, 2, 4])) # Output: False
85. How do you test the performance of a Python function?
You can use the
timeit
module to test the performance of a Python function.import timeit def example_function(): return sum(range(1000)) # Example usage print(timeit.timeit(example_function, number=1000)) # Output: Time taken to run the function 1000 times
86. Write a program to check the memory usage of a list.
You can use the
sys
module to check the memory usage of a list.import sys def memory_usage(lst): return sys.getsizeof(lst) # Example usage lst = [1, 2, 3, 4, 5] print(memory_usage(lst)) # Output: Memory usage in bytes
87. How do you automate file reading and writing in Python?
def read_file(file_path): with open(file_path, 'r') as file: return file.read() def write_file(file_path, content): with open(file_path, 'w') as file: file.write(content) # Example usage write_file('example.txt', 'Hello, World!') print(read_file('example.txt')) # Output: Hello, World!
88. Write a program to automate sending emails using Python.
You can use the
smtplib
module to send emails.import smtplib from email.mime.text import MIMEText def send_email(subject, body, to_email): from_email = "your_email@example.com" password = "your_password" msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email with smtplib.SMTP_SSL('smtp.example.com', 465) as server: server.login(from_email, password) server.sendmail(from_email, to_email, msg.as_string()) # Example usage send_email("Test Subject", "Test Body", "recipient@example.com")
89. How do you automate web scraping using Python?
You can use the
requests
andBeautifulSoup
modules to scrape web pages.import requests from bs4 import BeautifulSoup def scrape_website(url): response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') return soup.title.string # Example usage print(scrape_website('https://www.example.com')) # Output: Title of the webpage
90. Write a program to test API endpoints using Python.
You can use the
requests
module to test API endpoints.import requests def test_api(url): response = requests.get(url) return response.status_code, response.json() # Example usage url = 'https://api.example.com/data' status_code, data = test_api(url) print(f"Status Code: {status_code}, Data: {data}")
Practical Examples
91. Write a program to find the top N frequent elements in a list.
from collections import Counter def top_n_frequent_elements(lst, n): count = Counter(lst) return [item for item, _ in count.most_common(n)] # Example usage lst = [1, 1, 1, 2, 2, 3] n = 2 print(top_n_frequent_elements(lst, n)) # Output: [1, 2]
92. How do you implement a priority queue in Python?
You can use the
heapq
module to implement a priority queue.import heapq def priority_queue(elements): heapq.heapify(elements) return [heapq.heappop(elements) for _ in range(len(elements))] # Example usage elements = [4, 1, 7, 3, 8, 5] print(priority_queue(elements)) # Output: [1, 3, 4, 5, 7, 8]
93. Write a program to simulate a simple caching mechanism.
class SimpleCache: def __init__(self): self.cache = {} def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value # Example usage cache = SimpleCache() cache.set('a', 1) print(cache.get('a')) # Output: 1
94. How do you find the mode of a list?
from collections import Counter def find_mode(lst): count = Counter(lst) return count.most_common(1)[0][0] # Example usage lst = [1, 2, 2, 3, 3, 3, 4] print(find_mode(lst)) # Output: 3
95. Write a program to group anagrams from a list of strings.
from collections import defaultdict def group_anagrams(words): anagrams = defaultdict(list) for word in words: sorted_word = ''.join(sorted(word)) anagrams[sorted_word].append(word) return list(anagrams.values()) # Example usage words = ["eat", "tea", "tan", "ate", "nat", "bat"] print(group_anagrams(words)) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
96. How do you find the longest increasing subsequence in a list?
def longest_increasing_subsequence(nums): if not nums: return [] dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) max_length = max(dp) lis = [] for i in range(len(nums) - 1, -1, -1): if dp[i] == max_length: lis.append(nums[i]) max_length -= 1 return lis[::-1] # Example usage nums = [10, 9, 2, 5, 3, 7, 101, 18] print(longest_increasing_subsequence(nums)) # Output: [2, 3, 7, 101]
97. Write a program to generate a random password.
import random import string def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for i in range(length)) return password # Example usage print(generate_password(10)) # Output: Random 10-character password
98. How do you implement a heap sort algorithm?
```python def heapify(arr, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2
if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest)
def heap_sort(arr): n = len(arr)
for
Sure, let's continue from where we left off.98. Implement Heap Sort Algorithm (continued)
for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0) # Example usage arr = [12, 11, 13, 5, 6, 7] heap_sort(arr) print(arr) # Output: [5, 6, 7, 11, 12, 13]
Explanation:
- Build the Heap:
for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i)
Build a max heap by calling
heapify
on all non-leaf nodes.
- Extract Elements from the Heap:
for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0)
Extract elements one by one from the heap and call
heapify
to maintain the heap property.
- Example Usage:
arr = [12, 11, 13, 5, 6, 7] heap_sort(arr) print(arr) # Output: [5, 6, 7, 11, 12, 13]
This example sorts the array
[12, 11, 13, 5, 6, 7]
using heap sort.97. Generate a Random Password
import random import string def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for i in range(length)) return password # Example usage print(generate_password(10)) # Output: Random 10-character password
Explanation:
- Import Modules:
import random import string
Import the
random
andstring
modules.
- Define the Function:
def generate_password(length):
This function takes an integer
length
as input.
- Generate Password:
characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for i in range(length))
Create a string
characters
containing all possible characters for the password. Use a list comprehension to generate a random password of the specified length.
- Return the Password:
return password
Return the generated password.
- Example Usage:
print(generate_password(10)) # Output: Random 10-character password
This example generates a random 10-character password.
96. Find the Longest Increasing Subsequence in a List
def longest_increasing_subsequence(nums): if not nums: return [] dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) max_length = max(dp) lis = [] for i in range(len(nums) - 1, -1, -1): if dp[i] == max_length: lis.append(nums[i]) max_length -= 1 return lis[::-1] # Example usage nums = [10, 9, 2, 5, 3, 7, 101, 18] print(longest_increasing_subsequence(nums)) # Output: [2, 3, 7, 101]
Explanation:
- Define the Function:
def longest_increasing_subsequence(nums):
This function takes a list
nums
as input.
- Check for Empty List:
if not nums: return []
If the list is empty, return an empty list.
- Initialize DP Array:
dp = [1] * len(nums)
Initialize a DP array
dp
with all elements set to 1.
- Fill DP Array:
for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1)
Fill the DP array by comparing each element with all previous elements.
- Find the Longest Increasing Subsequence:
max_length = max(dp) lis = [] for i in range(len(nums) - 1, -1, -1): if dp[i] == max_length: lis.append(nums[i]) max_length -= 1
Find the longest increasing subsequence by tracing back from the maximum length.
- Return the Subsequence:
return lis[::-1]
Return the longest increasing subsequence in the correct order.
- Example Usage:
nums = [10, 9, 2, 5, 3, 7, 101, 18] print(longest_increasing_subsequence(nums)) # Output: [2, 3, 7, 101]
This example finds the longest increasing subsequence in the list
[10, 9, 2, 5, 3, 7, 101, 18]
.95. Group Anagrams from a List of Strings
from collections import defaultdict def group_anagrams(words): anagrams = defaultdict(list) for word in words: sorted_word = ''.join(sorted(word)) anagrams[sorted_word].append(word) return list(anagrams.values()) # Example usage words = ["eat", "tea", "tan", "ate", "nat", "bat"] print(group_anagrams(words)) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Explanation:
- Import Module:
from collections import defaultdict
Import the
defaultdict
class from thecollections
module.
- Define the Function:
def group_anagrams(words):
This function takes a list of strings
words
as input.
- Initialize Anagrams Dictionary:
anagrams = defaultdict(list)
Initialize a
defaultdict
to store anagrams.
- Group Anagrams:
for word in words: sorted_word = ''.join(sorted(word)) anagrams[sorted_word].append(word)
For each word, sort the characters and use the sorted word as the key to group anagrams.
- Return the Groups:
return list(anagrams.values())
Return the grouped anagrams as a list of lists.
- Example Usage:
words = ["eat", "tea", "tan", "ate", "nat", "bat"] print(group_anagrams(words)) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
This example groups the anagrams from the list
["eat", "tea", "tan", "ate", "nat", "bat"]
.94. Find the Mode of a List
from collections import Counter def find_mode(lst): count = Counter(lst) return count.most_common(1)[0][0] # Example usage lst = [1, 2, 2, 3, 3, 3, 4] print(find_mode(lst)) # Output: 3
Explanation:
- Import Module:
from collections import Counter
Import the
Counter
class from thecollections
module.
- Define the Function:
def find_mode(lst):
This function takes a list
lst
as input.
- Count Elements:
count = Counter(lst)
Use
Counter
to count the frequency of each element in the list.
- Find the Mode:
return count.most_common(1)[0][0]
Use the
most_common
method to find the most common element (mode).
- Example Usage:
lst = [1, 2, 2, 3, 3, 3, 4] print(find_mode(lst)) # Output: 3
This example finds the mode of the list
[1, 2, 2, 3, 3, 3, 4]
, which is3
.93. Simulate a Simple Caching Mechanism
```python class SimpleCache: def init(self): self.cache = {}
def get(self, key): return Sure, let's continue from where we left off.
93. Simulate a Simple Caching Mechanism (continued)
def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value # Example usage cache = SimpleCache() cache.set('a', 1) print(cache.get('a')) # Output: 1
Explanation:
- Define the Class:
class SimpleCache:
This class simulates a simple caching mechanism.
- Initialize the Cache:
def __init__(self): self.cache = {}
Initialize an empty dictionary to store cached values.
- Get Method:
def get(self, key): return self.cache.get(key)
Retrieve the value associated with the given key from the cache.
- Set Method:
def set(self, key, value): self.cache[key] = value
Store the value associated with the given key in the cache.
- Example Usage:
cache = SimpleCache() cache.set('a', 1) print(cache.get('a')) # Output: 1
This example demonstrates setting and getting a value in the cache.
92. Implement a Priority Queue in Python
You can use the
heapq
module to implement a priority queue.import heapq def priority_queue(elements): heapq.heapify(elements) return [heapq.heappop(elements) for _ in range(len(elements))] # Example usage elements = [4, 1, 7, 3, 8, 5] print(priority_queue(elements)) # Output: [1, 3, 4, 5, 7, 8]
Explanation:
- Import the
heapq
Module:import heapq
The
heapq
module provides an implementation of the heap queue algorithm.
- Define the Function:
def priority_queue(elements):
This function takes a list
elements
as input.
- Heapify the List:
heapq.heapify(elements)
Convert the list into a heap in-place.
- Extract Elements:
return [heapq.heappop(elements) for _ in range(len(elements))]
Extract elements from the heap one by one, resulting in a sorted list.
- Example Usage:
elements = [4, 1, 7, 3, 8, 5] print(priority_queue(elements)) # Output: [1, 3, 4, 5, 7, 8]
This example demonstrates using a priority queue to sort the list
[4, 1, 7, 3, 8, 5]
.91. Find the Top N Frequent Elements in a List
from collections import Counter def top_n_frequent_elements(lst, n): count = Counter(lst) return [item for item, _ in count.most_common(n)] # Example usage lst = [1, 1, 1, 2, 2, 3] n = 2 print(top_n_frequent_elements(lst, n)) # Output: [1, 2]
Explanation:
- Import the
Counter
Class:from collections import Counter
Import the
Counter
class from thecollections
module.
- Define the Function:
def top_n_frequent_elements(lst, n):
This function takes a list
lst
and an integern
as input.
- Count Elements:
count = Counter(lst)
Use
Counter
to count the frequency of each element in the list.
- Find the Top N Elements:
return [item for item, _ in count.most_common(n)]
Use the
most_common
method to find the topn
most frequent elements.
- Example Usage:
lst = [1, 1, 1, 2, 2, 3] n = 2 print(top_n_frequent_elements(lst, n)) # Output: [1, 2]
This example finds the top 2 most frequent elements in the list
[1, 1, 1, 2, 2, 3]
, which are1
and2
.Feel free to ask if you need further explanations or have more questions!
Comments
Post a Comment