Home › Python programs (Hindi)
List में दूसरा सबसे बड़ा Number — code और dry run
Problem statement
List में दूसरा सबसे बड़ा number निकालना। परिभाषा पर ध्यान दें: [12, 45, 45, 2] में अगर duplicates गिनते हैं तो जवाब 45 है, पर "दूसरा अलग (distinct)" माँगा जाए तो 12। दोनों को जान-बूझकर handle करें।Approach 1: simple loop
Remove the maximum, then take the maximum of what remains — the two-step version that reads exactly like the problem statement.
nums = [12, 45, 2, 41] copy = nums[:] # keep the original untouched copy.remove(max(copy)) # drop ONE occurrence of the largest print(max(copy)) # Output: 41
remove() deletes only the first matching occurrence, so duplicates of the maximum survive — which is what the "duplicates count" reading wants. Work on a copy so the original list is intact for later use.
Approach 2: reusable function
For the distinct reading, collapse duplicates with a set first, sort, and pick the second from the end — the version most exams and interviews mean.
nums = [12, 45, 45, 2] unique = sorted(set(nums)) print(unique[-2]) # Output: 12
Build it defensively and the edge cases say their names: a list with fewer than two distinct values has no second largest at all.
def second_largest(nums):
unique = sorted(set(nums))
if len(unique) < 2:
return None # explicitly: there is no answer
return unique[-2]Approach 3: Pythonic alternative
One pass, two variables: walk the list once, tracking the largest and second largest seen so far. This is the version that scales — it also works streaming over data you cannot sort.
nums = [12, 45, 2, 41]
first = second = float("-inf")
for n in nums:
if n > first:
second = first # old champion demoted
first = n
elif first > n > second:
second = n
print(second)
# Output: 41Starting both at negative infinity means any real number beats them — even a list of all-negative numbers works. Note the chained comparison first > n > second, which skips duplicates of the champion.
Dry run
One-pass version को[12, 45, 2, 41] पर चलाएँ। शुरुआत: first = second = -inf। n=12: 12 > -inf → first = 12। n=45: 45 > 12 → second = 12, first = 45। n=2: 45 से छोटा, और 12 से भी नहीं टकराया — skip। n=41: 45 से छोटा पर 12 से बड़ा → second = 41। जवाब: 41। हर number से ठीक एक comparison हुआ — यही one pass का मतलब है।Common errors
- Original list को ही sort कर देना — copy बनाकर या
sorted()से करो। - Duplicates पर
[-2]उठा लेना — पहले तय करो कि duplicates गिनने हैं या distinct। - Second को 0 से शुरू करना — सब negative list पर गलत;
float("-inf")लो। - छोटी list का case — [7] या [7, 7] में दूसरा distinct है ही नहीं; None return करो।
- Purana champion खो देना —
second = firstपहले,first = nबाद में।
Practice on PyDebug
Concept समझने के बाद इन free problems को browser में solve करें: