Day21-Day30 python One-Liner questions
Index: Click to Navigate:
Day21
Day22
Day23
Day24
Day25
Day26
Day27
Day28
Day29
Question21-1:
Find the Largest Word in a Sentence
Solution:
sentence = "Python makes fun"
print(max(sentence.split(), key=len))
Explanation:
1️⃣ Splitting the Sentence
sentence.split()
🔹 split()
breaks the sentence into words using spaces as separators:
["Python", "makes", "fun"]
2️⃣ Finding the Longest Word
max(["Python", "makes", "fun"], key=len)
🔹 max()
is used to find the word with the maximum length.
🔹 key=len
tells max()
to compare words based on their length instead of alphabetical order.
3️⃣ Comparing Word Lengths
"Python"
→ 6 characters"makes"
→ 5 characters"fun"
→ 3 characters
✅ "Python" is the longest word, so it is returned.
Question21-2:
Find Second Largest Element in a List
Solution:
nums = [10, 20, 4, 45, 99]
print(sorted(set(nums))[-2])
set(nums)
)
set(nums)
🔹 The set()
function removes duplicates (if any) and returns a set:
{10, 20, 4, 45, 99}
(Note: The set does not maintain order.)
set(nums)
🔹 The set()
function removes duplicates (if any) and returns a set:
{10, 20, 4, 45, 99}
(Note: The set does not maintain order.)
2️⃣ Sort the Set (sorted(set(nums))
)
sorted(set(nums))
🔹 sorted()
sorts the set in ascending order, returning a list:
[4, 10, 20, 45, 99]
sorted(set(nums))
🔹 sorted()
sorts the set in ascending order, returning a list:
[4, 10, 20, 45, 99]
3️⃣ Get the Second Largest Number ([-2]
)
sorted(set(nums))[-2]
sorted(set(nums))[-2]
🔹 [-2]
gets the second last element, which is the second largest number in the sorted list.
🔹 In this case, 45
is the second largest number.
Day - 22
Question22-1:
Print Fibonacci Series in One LineSolution:
fib = lambda n, a=0, b=1: [a] if n == 0 else [a] + fib(n-1, b, a+b)
print(fib(10))
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]Explanation:
Day - 22
Question22-1:
Print Fibonacci Series in One LineSolution:
fib = lambda n, a=0, b=1: [a] if n == 0 else [a] + fib(n-1, b, a+b)
print(fib(10))
Explanation:
1️⃣ Understanding the Lambda Function
fib = lambda n, a=0, b=1: [a] if n == 0 else [a] + fib(n-1, b, a+b)
- This is a recursive lambda function that generates the first
n
Fibonacci numbers.
- It takes three arguments:
n
→ number of Fibonacci numbers to generate.
a
→ first number in the Fibonacci sequence (default = 0
).
b
→ second number in the Fibonacci sequence (default = 1
).
- Base Case:
- If
n == 0
, return [a]
(stop recursion).
- Recursive Case:
- Return
[a]
concatenated with fib(n-1, b, a+b)
.
- This shifts the Fibonacci sequence forward (
b
becomes the next a
, and a+b
becomes the next b
).
fib = lambda n, a=0, b=1: [a] if n == 0 else [a] + fib(n-1, b, a+b)
n
Fibonacci numbers.n
→ number of Fibonacci numbers to generate.a
→ first number in the Fibonacci sequence (default =0
).b
→ second number in the Fibonacci sequence (default =1
).
- If
n == 0
, return[a]
(stop recursion).
- Return
[a]
concatenated withfib(n-1, b, a+b)
. - This shifts the Fibonacci sequence forward (
b
becomes the nexta
, anda+b
becomes the nextb
).
2️⃣ Running fib(10)
print(fib(10))
print(fib(10))
🔹 Let's see how the recursion unfolds:
Step | n | a | b | Returned List |
---|---|---|---|---|
1 | 10 | 0 | 1 | [0] + fib(9, 1, 1) |
2 | 9 | 1 | 1 | [1] + fib(8, 1, 2) |
3 | 8 | 1 | 2 | [1] + fib(7, 2, 3) |
4 | 7 | 2 | 3 | [2] + fib(6, 3, 5) |
5 | 6 | 3 | 5 | [3] + fib(5, 5, 8) |
6 | 5 | 5 | 8 | [5] + fib(4, 8, 13) |
7 | 4 | 8 | 13 | [8] + fib(3, 13, 21) |
8 | 3 | 13 | 21 | [13] + fib(2, 21, 34) |
9 | 2 | 21 | 34 | [21] + fib(1, 34, 55) |
10 | 1 | 34 | 55 | [34] + fib(0, 55, 89) |
11 | 0 | 55 | 89 | [55] (Base case reached) |
Question22-2:
Find All Even Numbers in a ListSolution:
print([x for x in range(10) if x % 2 == 0])
Output:
[0, 2, 4, 6, 8]Explanation:
range(10)
: Generates numbers from 0 to 9 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9
).if x % 2 == 0
: Filters only even numbers (numbers divisible by 2).[x for x in ...]
: Creates a list with the filtered values.print(...)
: Prints the final list.
range(10)
: Generates numbers from 0 to 9 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9
).if x % 2 == 0
: Filters only even numbers (numbers divisible by 2).[x for x in ...]
: Creates a list with the filtered values.print(...)
: Prints the final list.
Day - 23
Question23-1:
Find All Vowels in a StringSolution:
print([ch for ch in "Hello PythonBuzz" if ch in "aeiouAEIOU"])
Output:
['e', 'o', 'o', 'u']Explanation:
Step 1: Understanding List Comprehension
Day - 23
Question23-1:
Find All Vowels in a StringSolution:
print([ch for ch in "Hello PythonBuzz" if ch in "aeiouAEIOU"])
Explanation:
Step 1: Understanding List Comprehension
The syntax of list comprehension is:
[expression for item in iterable if condition]
- Expression →
ch
(each character from the string) - Iterable →
"Hello PythonBuzz"
(looping through each character in the string) - Condition →
if ch in "aeiouAEIOU"
(checks if the character is a vowel)
Step 2: Iterating Over the String
The given string is "Hello PythonBuzz"
, and Python will loop through each character one by one.
Character | Condition ch in "aeiouAEIOU" |
Included in List? |
---|---|---|
H | ❌ (Not a vowel) | No |
e | ✅ (Vowel) | Yes |
l | ❌ (Not a vowel) | No |
l | ❌ (Not a vowel) | No |
o | ✅ (Vowel) | Yes |
(space) | ❌ (Not a vowel) | No |
P | ❌ (Not a vowel) | No |
y | ❌ (Not a vowel) | No |
t | ❌ (Not a vowel) | No |
h | ❌ (Not a vowel) | No |
o | ✅ (Vowel) | Yes |
n | ❌ (Not a vowel) | No |
B | ❌ (Not a vowel) | No |
u | ✅ (Vowel) | Yes |
z | ❌ (Not a vowel) | No |
z | ❌ (Not a vowel) | No |
Step 3: Building the Final List
The characters that satisfy the condition (ch in "aeiouAEIOU"
) are:
['e', 'o', 'o', 'u']
Question23-2:
Check if a string is a palindrome.
Solution:
print((lambda s: s == s[::-1])("madam"))
Explanation:
Step 1: Understanding the Lambda Function
A lambda function is an anonymous function in Python that has a simple one-line expression.
The lambda function here is:
lambda s: s == s[::-1]
s
→ Input strings[::-1]
→ Reverses the string using Python slicings == s[::-1]
→ Compares the original and reversed string to check if they are the same
Step 2: Checking for a Palindrome
How does string reversal work?
s[::-1]
- The slicing
[::-1]
means:
-1
→ Step size (moves in reverse order)
- No start or end indices → Reverses the entire string
s[::-1]
[::-1]
means:
-1
→ Step size (moves in reverse order)- No start or end indices → Reverses the entire string
🔹 Example:
"madam"[::-1] # "madam" (same as original, so it's a palindrome)
"hello"[::-1] # "olleh" (different from original, so not a palindrome)
Step 3: Executing the Function
The function is immediately called with "madam"
as an argument:
print((lambda s: s == s[::-1])("madam"))
"madam" == "madam"
→ ✅ True (Palindrome)
Day - 24
Question24-1:
Day - 24
Question24-1:
Find the Most Frequent Element in a List
Solution:
nums = [1, 3, 2, 3, 4, 3, 5, 2, 2, 2]
print(max(nums, key=nums.count))
Output:
nums.count(x)
Finds the Frequency
nums.count(x)
returns how many times x
appears in nums
.
-
max(iterable, key=function)
Finds the Element with Maximum Frequency
max(nums, key=nums.count)
means:
- For each number in
nums
, count(x)
is calculated.
- The number with the highest count is returned.
nums.count(x)
Finds the Frequency
nums.count(x)
returns how many timesx
appears innums
.
max(iterable, key=function)
Finds the Element with Maximum Frequency
max(nums, key=nums.count)
means:- For each number in
nums
,count(x)
is calculated. - The number with the highest count is returned.
- For each number in
Iteration Breakdown:
Number | Count (nums.count(x) ) |
---|---|
1 |
1 |
3 |
3 |
2 |
4 |
4 |
1 |
5 |
1 |
✅ Since 2
appears 4 times, it is the most frequent number, so the output is:
2
More Optimized Version (Using Counter
):
For large lists, use collections.Counter
, which runs in O(n):
from collections import Counter
print(Counter(nums).most_common(1)[0][0])
Question24-2:
Find Common Elements in Two Lists
Solution:
print(list(set([1, 2, 3, 4]) & set([3, 4, 5, 6])))
Output:
Explanation:
Convert Lists to Sets
set1 = set([1, 2, 3, 4]) # {1, 2, 3, 4}
set2 = set([3, 4, 5, 6]) # {3, 4, 5, 6}
- Converting to sets removes duplicates (if any) and allows efficient operations.
-
Find Common Elements (Intersection &
)
common_elements = set1 & set2 # {3, 4}
- The
&
operator finds elements that exist in both sets.
-
Convert Set to List
result = list(common_elements) # [3, 4]
- Since sets are unordered, the final list may appear in any order.
Convert Lists to Sets
set1 = set([1, 2, 3, 4]) # {1, 2, 3, 4}
set2 = set([3, 4, 5, 6]) # {3, 4, 5, 6}
- Converting to sets removes duplicates (if any) and allows efficient operations.
Find Common Elements (Intersection &
)
common_elements = set1 & set2 # {3, 4}
- The
&
operator finds elements that exist in both sets.
Convert Set to List
result = list(common_elements) # [3, 4]
- Since sets are unordered, the final list may appear in any order.
Day - 25
Question25-1:
Day - 25
Question25-1:
Reverse Words in a Sentence
Solution:
print(" ".join("Python is fun".split()[::-1]))
Output:
1️⃣ Splitting the String into a List of Words
"Python is fun".split()
"Python is fun".split()
🔹 The .split()
method splits the string into a list of words based on spaces.
Output: ["Python", "is", "fun"]
2️⃣ Reversing the List
["Python", "is", "fun"][::-1]
🔹 The slicing notation [::-1]
reverses the list.
Output: ["fun", "is", "Python"]
3️⃣ Joining the Reversed List into a String
" ".join(["fun", "is", "Python"])
🔹 The " ".join()
method joins the words in the list into a single string, with spaces in between.
Output: "fun is Python"
Question25-2:
Check if Two Strings Are Anagrams
Solution:
print(sorted("listen") == sorted("silent"))
Output:
sorted("listen")
sorted("silent")
🔹 The sorted()
function sorts the characters of a string in alphabetical order.
"listen"
becomes ['e', 'i', 'l', 'n', 's', 't']
"silent"
becomes ['e', 'i', 'l', 'n', 's', 't']
2️⃣ Comparing the Sorted Lists
sorted("listen") == sorted("silent")
🔹 Since both sorted lists are identical, the comparison returns True
.
sorted("listen")
sorted("silent")
sorted()
function sorts the characters of a string in alphabetical order."listen"
becomes ['e', 'i', 'l', 'n', 's', 't']
"silent"
becomes ['e', 'i', 'l', 'n', 's', 't']
sorted("listen") == sorted("silent")
True
.Final Output:
True
True
What Does This Do?
This one-liner checks if two words are anagrams.
🔹 An anagram is a word formed by rearranging the letters of another word.
✔ "listen"
and "silent"
are anagrams because they have the same letters in a different order.
🔹 An anagram is a word formed by rearranging the letters of another word.
✔
"listen"
and "silent"
are anagrams because they have the same letters in a different order.More Examples
print(sorted("hello") == sorted("world")) # False
print(sorted("race") == sorted("care")) # True
print(sorted("python") == sorted("java")) # False
print(sorted("hello") == sorted("world")) # False
print(sorted("race") == sorted("care")) # True
print(sorted("python") == sorted("java")) # False
Optimized Approach
A more efficient way to check anagrams (without sorting) is using collections.Counter
:
from collections import Counter
print(Counter("listen") == Counter("silent")) # True
🔹 Counter
counts the occurrences of each letter, making it faster for large strings.
Day - 26Question26-1:
Find all divisors of a number.
Solution:
n = 30
print([x for x in range(1, n) if n % x == 0])
Output:
[1, 2, 3, 5, 6, 10, 15]
Explanation:
collections.Counter
:from collections import Counter
print(Counter("listen") == Counter("silent")) # True
Counter
counts the occurrences of each letter, making it faster for large strings.range(1, n)
:
- This generates a sequence of numbers from
1
to n-1
(i.e., 1, 2, 3, ..., n-1
).
- The reason for excluding
n
is that we're interested in divisors less than n
(excluding n
itself).
-
n % x == 0
:
- This checks if
x
is a divisor of n
.
- If the result of
n % x
is 0
, then x
divides n
without a remainder, meaning x
is a divisor.
-
List Comprehension:
- The list comprehension collects all numbers
x
in the range [1, n)
where n % x == 0
(i.e., all divisors of n
).
- It produces a list of these divisors.
range(1, n)
:
- This generates a sequence of numbers from
1
ton-1
(i.e.,1, 2, 3, ..., n-1
). - The reason for excluding
n
is that we're interested in divisors less thann
(excludingn
itself).
n % x == 0
:
- This checks if
x
is a divisor ofn
. - If the result of
n % x
is0
, thenx
dividesn
without a remainder, meaningx
is a divisor.
List Comprehension:
- The list comprehension collects all numbers
x
in the range[1, n)
wheren % x == 0
(i.e., all divisors ofn
). - It produces a list of these divisors.
Output:
[1, 2, 3, 5, 6, 10, 15]
[1, 2, 3, 5, 6, 10, 15]
These are all the divisors of 30, excluding 30 itself.
Question26-2:
Remove duplicates from a list while maintain order.
Solution:
print(list(dict.fromkeys([1,4,3,4,5,6,8,6])))
Output:
[1, 4, 3, 5, 6, 8]
Explanation:
dict.fromkeys()
:
- This method is used to create a dictionary where the list elements become keys.
- In a dictionary, keys must be unique, so duplicates are automatically removed.
- The values for each key are set to
None
by default, but we don't care about the values in this case. We only care about the keys (unique elements from the list).
-
list()
:
- After removing the duplicates using
dict.fromkeys()
, we convert the dictionary keys back into a list.
- This gives us the list of unique elements while preserving the order of their first occurrence.
dict.fromkeys()
:- This method is used to create a dictionary where the list elements become keys.
- In a dictionary, keys must be unique, so duplicates are automatically removed.
- The values for each key are set to
None
by default, but we don't care about the values in this case. We only care about the keys (unique elements from the list).
-
list()
:- After removing the duplicates using
dict.fromkeys()
, we convert the dictionary keys back into a list. - This gives us the list of unique elements while preserving the order of their first occurrence.
- After removing the duplicates using
Step-by-step:
- The input list is
[1, 4, 3, 4, 5, 6, 8, 6]
.
- After applying
dict.fromkeys()
, the duplicates are removed, and the dictionary becomes:
{1: None, 4: None, 3: None, 5: None, 6: None, 8: None}
.
- Finally,
list()
converts this dictionary back into a list of keys, resulting in: [1, 4, 3, 5, 6, 8]
.
- The input list is
[1, 4, 3, 4, 5, 6, 8, 6]
. - After applying
dict.fromkeys()
, the duplicates are removed, and the dictionary becomes:
{1: None, 4: None, 3: None, 5: None, 6: None, 8: None}
. - Finally,
list()
converts this dictionary back into a list of keys, resulting in:[1, 4, 3, 5, 6, 8]
.
Output:
[1, 4, 3, 5, 6, 8]
This is the original list with duplicates removed, and the order of first occurrence is maintained.
[1, 4, 3, 5, 6, 8]
This is the original list with duplicates removed, and the order of first occurrence is maintained.
Day - 27
Question27-1:
Compute the Dot Product of Two Lists
Solution:
print(sum(x*y for x,y in zip([1,2,3],[4,5,6])))
Explanation:
zip([1, 2, 3], [4, 5, 6])
- The
zip()
function pairs up corresponding elements from both lists:
(1,4), (2,5), (3,6)
-
x * y for x, y in zip(...)
- We iterate over the pairs and multiply them element-wise:
1 * 4 = 4
2 * 5 = 10
3 * 6 = 18
-
sum(...)
- The
sum()
function adds up all the multiplied values:
4 + 10 + 18 = 32
zip([1, 2, 3], [4, 5, 6])
- The
zip()
function pairs up corresponding elements from both lists:(1,4), (2,5), (3,6)
x * y for x, y in zip(...)
- We iterate over the pairs and multiply them element-wise:
1 * 4 = 4 2 * 5 = 10 3 * 6 = 18
sum(...)
- The
sum()
function adds up all the multiplied values:4 + 10 + 18 = 32
Question27-2:
Sort a List of Tuples Based on the Second Element
Solution:
print(sorted([(1,3),(2,2),(4,1)],key= lambda x:x[1]))
Output:
Explanation:
1. Given List of Tuples:
[(1,3), (2,2), (4,1)]
[(1,3), (2,2), (4,1)]
Each tuple has two values:
(1,3)
→ First element =1
, Second element =3
(2,2)
→ First element =2
, Second element =2
(4,1)
→ First element =4
, Second element =1
2. Sorting Criteria:
key=lambda x: x[1]
→ This tells Python to sort using the second element of each tuple.
key=lambda x: x[1]
→ This tells Python to sort using the second element of each tuple.3. Sorting Process:
(4,1)
→ 1 (smallest)
(2,2)
→ 2
(1,3)
→ 3 (largest)
(4,1)
→ 1 (smallest)(2,2)
→ 2(1,3)
→ 3 (largest)4. Sorted List Output:
[(4,1), (2,2), (1,3)]
[(4,1), (2,2), (1,3)]
Day - 28
Question28-1:
Merge two dictionaries.
Solution:
You can merge two dictionaries in one line using different methods:
Method 1: Using |
(Python 3.9+)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
print(dict1 | dict2)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
print(dict1 | dict2)
Explanation: The |
operator merges dictionaries, keeping the values from dict2
for duplicate keys.
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 2: Using {**d1, **d2}
(Works in older Python versions)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
print({**dict1, **dict2})
print({**dict1, **dict2})
🔹 Explanation: Unpacks both dictionaries, with dict2
values overriding dict1
for common keys.
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 3: Using update()
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
dict1.update(dict2)
print(dict1)
🔹 Explanation: update()
modifies dict1
in place.
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 4: Using collections.ChainMap
(Keeps original values)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
from collections import ChainMap
merged = dict(ChainMap(dict2, dict1))
print(merged)
from collections import ChainMap
merged = dict(ChainMap(dict2, dict1))
print(merged)
Output:
{'a': 1, 'b': 3, 'c': 4}
Question28-2:
Count occurrences of each character in a string
Solution:
Method 1: Using collections.Counter
(Most Efficient)
from collections import Counter
print(Counter("buzz"))
Output:
Counter({'z': 2, 'b': 1, 'u': 1})
from collections import Counter
print(Counter("buzz"))
Output:
Counter({'z': 2, 'b': 1, 'u': 1})
Explanation:
Counter("buzz")
creates a dictionary-like object that counts occurrences of each character in"buzz"
.- The result is:
This means:Counter({'z': 2, 'b': 1, 'u': 1})
'z'
appears 2 times.'b'
appears 1 time.'u'
appears 1 time.
Why use this?
✅ Fastest method
✅ Handles large strings efficiently
Method 2: Using Dictionary Comprehension
print({ch: "buzz".count(ch) for ch in set("buzz")})
print({ch: "buzz".count(ch) for ch in set("buzz")})
Explanation:
set("buzz")
→{'b', 'u', 'z'}
(removes duplicates).- For each unique character, we apply
"buzz".count(ch)
, which counts occurrences.
Why use this?
✅ Simple to understand
❌ Less efficient (O(n²) complexity) because .count()
scans the string multiple times
Method 3: Using Counter.most_common()
(Sorted by Frequency)
print(Counter("buzz").most_common())
print(Counter("buzz").most_common())
Explanation:
Counter("buzz")
counts characters..most_common()
returns a list of tuples, sorted in descending order of frequency.
✅ Sorted output (useful when finding most frequent characters)
✅ More readable in some cases
Day - 29
Question29-1:
is_power_of_two = lambda n: n > 0 and (n & (n - 1)) == 0
Explanation:
The lambda function checks if a number n
is a power of two using a bitwise trick.
Breaking it Down:
n > 0
→ Ensures n
is positive (since powers of two are always positive).
n & (n - 1) == 0
→ This checks if n
has only one bit set in its binary form.
- If
n
is a power of two, it has exactly one 1
bit in its binary representation.
- Subtracting
1
from it flips all the bits after the rightmost 1 and turns the rightmost 1
into 0
.
- Doing a bitwise AND (
&
) operation between n
and n - 1
results in 0
only for powers of two.
n > 0
→ Ensures n
is positive (since powers of two are always positive).n & (n - 1) == 0
→ This checks if n
has only one bit set in its binary form.
- If
n
is a power of two, it has exactly one1
bit in its binary representation. - Subtracting
1
from it flips all the bits after the rightmost 1 and turns the rightmost1
into0
. - Doing a bitwise AND (
&
) operation betweenn
andn - 1
results in0
only for powers of two.
Question29-2:
lst, n = [1,2,3,4,5], 2
print(lst[-n:] + lst[:-n])
Explanation:
What Does This Code Do?
This rotates the list to the right by n
positions.
Breaking it Down Step by Step:
lst[-n:]
→ Slices the last n
elements of the list.
lst[:-n]
→ Slices the list excluding the last n
elements.
lst[-n:] + lst[:-n]
→ Concatenates both slices, effectively rotating the list.
lst[-n:]
→ Slices the last n
elements of the list.lst[:-n]
→ Slices the list excluding the last n
elements.lst[-n:] + lst[:-n]
→ Concatenates both slices, effectively rotating the list.Example Execution:
lst = [1, 2, 3, 4, 5]
n = 2
lst[-2:]
→ lst[-2:] = [4, 5]
(Last 2 elements)
lst[:-2]
→ lst[:-2] = [1, 2, 3]
(Remaining elements)
lst = [1, 2, 3, 4, 5]
n = 2
lst[-2:]
→ lst[-2:] = [4, 5]
(Last 2 elements)lst[:-2]
→ lst[:-2] = [1, 2, 3]
(Remaining elements)Final Output:
[4, 5, 1, 2, 3]
[4, 5, 1, 2, 3]
This shifts the list to the right by 2
places.
For n = 3
:
lst = [1, 2, 3, 4, 5]
n = 3
print(lst[-3:] + lst[:-3])
lst[-3:] = [3, 4, 5]
lst[:-3] = [1, 2]
- Final result →
[3, 4, 5, 1, 2]
Day - 30
Question30-1:
Merge Two Dictionaries with Summed Values for DuplicatesSolution:
from collections import Counter
print(dict(Counter({'a': 2, 'b': 3}) + Counter({'b': 4, 'c': 5})))
-
Creating Two Counter
Objects
Counter({'a': 2, 'b': 3}) # First Counter
Counter({'b': 4, 'c': 5}) # Second Counter
These represent dictionaries where the keys are characters, and values are their counts.
-
Adding Two Counter
Objects (+
Operator)
Counter
supports element-wise addition:
Counter({'a': 2, 'b': 3}) + Counter({'b': 4, 'c': 5})
- For keys present in both Counters, their values are added together.
- For unique keys, the values remain as they are.
Calculation:
'a'
: 2 (only in the first counter)
'b'
: 3 (from first) + 4 (from second) = 7
'c'
: 5 (only in the second counter)
Resulting Counter:
Counter({'b': 7, 'a': 2, 'c': 5})
-
Converting Counter
to dict
dict(Counter({'b': 7, 'a': 2, 'c': 5}))
Converts it back to a regular dictionary:
{'a': 2, 'b': 7, 'c': 5}
-
Creating Two
Counter
ObjectsCounter({'a': 2, 'b': 3}) # First Counter Counter({'b': 4, 'c': 5}) # Second Counter
These represent dictionaries where the keys are characters, and values are their counts.
-
Adding Two
Counter
Objects (+
Operator)Counter
supports element-wise addition:
Counter({'a': 2, 'b': 3}) + Counter({'b': 4, 'c': 5})
- For keys present in both Counters, their values are added together.
- For unique keys, the values remain as they are.
Calculation:
'a'
: 2 (only in the first counter)'b'
: 3 (from first) + 4 (from second) = 7'c'
: 5 (only in the second counter)
Resulting Counter:
Counter({'b': 7, 'a': 2, 'c': 5})
-
Converting
Counter
todict
dict(Counter({'b': 7, 'a': 2, 'c': 5}))
Converts it back to a regular dictionary:
{'a': 2, 'b': 7, 'c': 5}
Question30-2:
Find the Most Frequent Word in a Sentence
Solution:
print(max(set(words := "Follow python buzz for more python content ".split()), key=words.count))
Using the Walrus Operator (:=
)
words := "Follow python buzz for more python content ".split()
- This assigns the split words of the string to
words
:
words = ['Follow', 'python', 'buzz', 'for', 'more', 'python',
'content']
-
Converting List to a Set (set(words)
)
- This removes duplicate words and keeps only unique ones:
{'Follow', 'python', 'buzz', 'for', 'more', 'content'}
-
Finding the Most Frequent Word using max()
max(set(words), key=words.count)
words.count(x)
returns how many times x
appears in words
.
max()
picks the word with the highest count.
Using the Walrus Operator (:=
)
words := "Follow python buzz for more python content ".split()
words
:
words = ['Follow', 'python', 'buzz', 'for', 'more', 'python',
'content']
Converting List to a Set (set(words)
)
- This removes duplicate words and keeps only unique ones:
{'Follow', 'python', 'buzz', 'for', 'more', 'content'}
Finding the Most Frequent Word using max()
max(set(words), key=words.count)
words.count(x)
returns how many timesx
appears inwords
.max()
picks the word with the highest count.
Execution Example:
words = ['Follow', 'python', 'buzz', 'for', 'more', 'python', 'content']
# Unique words:
unique_words = {'Follow', 'python', 'buzz', 'for', 'more', 'content'}
# Count occurrences:
'Follow' -> 1
'python' -> 2
'buzz' -> 1
'for' -> 1
'more' -> 1
'content' -> 1
# The most frequent word is 'python' (appears twice).
words = ['Follow', 'python', 'buzz', 'for', 'more', 'python', 'content']
# Unique words:
unique_words = {'Follow', 'python', 'buzz', 'for', 'more', 'content'}
# Count occurrences:
'Follow' -> 1
'python' -> 2
'buzz' -> 1
'for' -> 1
'more' -> 1
'content' -> 1
# The most frequent word is 'python' (appears twice).
Comments
Post a Comment