सामग्री पर जाएँ

लेसन 148 · Practice and Review

Python अभ्यास प्रश्न

स्ट्रिंग, लूप, डिक्शनरी, फ़ंक्शन, फ़ाइलें, क्लास, जनरेटर और एल्गोरिदम पर समाधान सहित 27 क्रमबद्ध Python अभ्यास। उन्हें अपने ब्राउज़र में चलाइए।

कोड के बारे में पढ़ना और कोड लिखना अलग कौशल हैं, और दूसरा कौशल केवल अभ्यास से बनता है। इस पेज पर 27 अभ्यास हैं जो पूरे कोर्स को कवर करते हैं, विषय के हिसाब से समूहित और शुरुआती से उन्नत के क्रम में। हर अभ्यास में एक छोटा टास्क, स्टार्टर कोड वाला एडिटर और एक छिपा हुआ समाधान है।

इनका पूरा फ़ायदा उठाने का तरीका यह है:

  • पहले कोशिश कीजिए, बाद में झाँकिए। समाधान खोलने से पहले हर अभ्यास को ईमानदारी से आज़माइए। कुछ मिनट अटके रहना ही वह जगह है जहाँ सीखना होता है।
  • बार-बार चलाइए। हर स्टार्टर टेस्ट कॉल प्रिंट करता है, ताकि आप देख सकें कि आपका आउटपुट कमेंट में लिखे अपेक्षित नतीजे से कब मेल खाता है।
  • तुलना कीजिए, नकल नहीं। आपका समाधान हमारे से अलग दिख सकता है और फिर भी सही हो सकता है। विचारों के लिए हमारा पढ़िए, फिर अपना बेहतर कीजिए।

हर अभ्यास समूह उस पाठ से जुड़ा है जिसका वह अभ्यास कराता है, और चीट शीट को दूसरे टैब में खुला रखना काम का है। जिन अभ्यासों में input() इस्तेमाल होता है उनके साथ एडिटर के Input बॉक्स में पहले से जवाब दिए होते हैं, जिन्हें आप दूसरे मान आज़माने के लिए बदल सकते हैं।

स्ट्रिंग और बुनियादी बातें

ये वेरिएबल, इनपुट और आउटपुट, स्ट्रिंग, स्ट्रिंग मेथड और स्ट्रिंग फ़ॉर्मैटिंग का अभ्यास कराते हैं।

1. जन्मदिन की शुभकामना (शुरुआती)

input() से नाम और उम्र पढ़िए, फिर Hi Mina! Next year you'll be 28. जैसी लाइन प्रिंट कीजिए। याद रखिए कि input() हमेशा स्ट्रिंग लौटाता है।

Python अभ्यास 1: जन्मदिन की शुभकामना

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
name = input("Name: ")
age = int(input("Age: "))

print(f"Hi {name}! Next year you'll be {age + 1}.")

int() से बदलना ही मुख्य कदम है: स्ट्रिंग "27" में 1 जोड़ने पर TypeError उठता।

2. रूपांतरण तालिका (शुरुआती)

0 से 100 तक 20 के कदम में सेल्सियस तापमान की तालिका उनके फ़ारेनहाइट मानों (F = C * 9 / 5 + 32) के साथ प्रिंट कीजिए। कॉलम सीध में रखिए और फ़ारेनहाइट के लिए एक दशमलव स्थान दिखाइए।

Python अभ्यास 2: रूपांतरण तालिका

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
print("   C        F")
for celsius in range(0, 101, 20):
    fahrenheit = celsius * 9 / 5 + 32
    print(f"{celsius:>4} {fahrenheit:>8.1f}")

range(0, 101, 20) में 100 शामिल है क्योंकि stop मान शामिल नहीं होता (101 है), और फ़ॉर्मैट स्पेक >4 और >8.1f हर कॉलम को दाएँ-अलाइन करते हैं।

3. पैलिंड्रोम जाँचक (शुरुआती)

is_palindrome(text) लिखिए जो True लौटाए अगर टेक्स्ट उलटा पढ़ने पर भी वैसा ही पढ़ा जाता है, अक्षरों के केस, स्पेस और विराम-चिह्न को अनदेखा करके।

Python अभ्यास 3: पैलिंड्रोम

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def is_palindrome(text: str) -> bool:
    letters = [char.lower() for char in text if char.isalnum()]
    return letters == letters[::-1]

केवल अक्षर-अंक वाले (alphanumeric) कैरेक्टर रखने से स्पेस और विराम-चिह्न हट जाते हैं, और [::-1] तुलना के लिए उलटी कॉपी देता है।

4. स्वर गिनने वाला (शुरुआती)

count_vowels(text) लिखिए जो डिक्शनरी लौटाए कि हर स्वर (a, e, i, o, u) कितनी बार आया, केस अनदेखा करके। जो स्वर शून्य बार आते हैं उन्हें भी शामिल कीजिए।

Python अभ्यास 4: स्वर गिनने वाला

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def count_vowels(text: str) -> dict[str, int]:
    lowered = text.lower()
    return {vowel: lowered.count(vowel) for vowel in "aeiou"}

"aeiou" पर डिक्शनरी कॉम्प्रिहेंशन गारंटी देता है कि हर स्वर कुंजी के रूप में मौजूद हो, और str.count() गिनती करता है।

कंट्रोल फ़्लो

if स्टेटमेंट, for लूप, while लूप और break तथा continue का अभ्यास।

5. टिक-टॉक (शुरुआती)

1 से 20 तक की संख्याओं के लिए, 3 के गुणजों पर Tick, 5 के गुणजों पर Tock, दोनों के गुणजों पर TickTock, और बाकी पर संख्या खुद प्रिंट कीजिए।

Python अभ्यास 5: टिक-टॉक

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
for n in range(1, 21):
    word = ""
    if n % 3 == 0:
        word += "Tick"
    if n % 5 == 0:
        word += "Tock"
    print(word or n)

दो स्वतंत्र if जाँचों में शब्द बनाना "दोनों" वाली स्थिति अपने-आप संभाल लेता है, और word or n शब्द खाली होने पर संख्या पर लौट आता है।

6. लीप वर्ष (शुरुआती)

कोई साल लीप वर्ष है अगर वह 4 से विभाज्य है, सिवाय उन सालों के जो 100 से विभाज्य हैं, जब तक कि वे 400 से भी विभाज्य न हों। is_leap(year) लिखिए।

Python अभ्यास 6: लीप वर्ष

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def is_leap(year: int) -> bool:
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

कोष्ठक अपवाद और उसके अपवाद को समूह में बाँधते हैं। असली कोड में calendar.isleap(year) यही काम करता है।

7. डिजिटल रूट (मध्यम)

किसी संख्या के अंकों को जोड़िए। अगर नतीजे में एक से ज़्यादा अंक हों, तो तब तक दोहराइए जब तक एक अंक न बचे। 98,765 के लिए: 9+8+7+6+5 = 35, फिर 3+5 = 8।

Python अभ्यास 7: डिजिटल रूट

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def digital_root(number: int) -> int:
    while number >= 10:
        number = sum(int(digit) for digit in str(number))
    return number

while लूप ठीक तब तक दोहराता है जब तक एक से ज़्यादा अंक हैं; अंकों तक पहुँचने का सबसे सरल तरीका स्ट्रिंग में बदलना है।

8. संख्या का अनुमान लगाइए (मध्यम)

गुप्त संख्या 37 है। अनुमान माँगते रहिए, Too low या Too high से जवाब दीजिए, और जब अनुमान सही हो तो प्रिंट कीजिए कि कितने प्रयास लगे। Input बॉक्स में पहले से तीन अनुमान हैं।

Python अभ्यास 8: संख्या का अनुमान लगाइए

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
secret = 37
attempts = 0

while True:
    guess = int(input("Guess: "))
    attempts += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print(f"Correct! You needed {attempts} attempts.")
        break

break के साथ while True उन लूप के लिए ठीक बैठता है जिनकी निकलने की शर्त बीच में मिलती है। संख्या अनुमान प्रोजेक्ट इसका पूरा संस्करण बनाता है।

लिस्ट, डिक्शनरी और सेट

लिस्ट, लिस्ट मेथड, डिक्शनरी, सेट, कॉम्प्रिहेंशन और collections का अभ्यास।

9. दूसरा सबसे बड़ा (शुरुआती)

लिस्ट में दूसरा सबसे बड़ा अलग मान लौटाइए, या अगर नहीं है तो None।

Python अभ्यास 9: दूसरा सबसे बड़ा

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def second_largest(numbers: list[int]) -> int | None:
    unique = sorted(set(numbers), reverse=True)
    return unique[1] if len(unique) >= 2 else None

सेट डुप्लिकेट 9 हटा देता है, इसलिए सॉर्ट किए नतीजे का दूसरा आइटम ही जवाब है। बहुत बड़ी लिस्ट के लिए, ऐसा एक पास जो शीर्ष दो मान ट्रैक करे, सॉर्टिंग से बचाता है।

10. डुप्लिकेट हटाएँ, क्रम रखें (शुरुआती)

डुप्लिकेट के बिना नई लिस्ट लौटाइए, हर मान की पहली उपस्थिति को उसकी मूल स्थिति में रखते हुए।

Python अभ्यास 10: क्रम में अनोखे

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def unique(items: list) -> list:
    return list(dict.fromkeys(items))

डिक्शनरी इन्सर्शन क्रम रखती है और उनमें डुप्लिकेट कुंजियाँ नहीं हो सकतीं, इसलिए dict.fromkeys() क्रम बचाकर डुप्लिकेट हटाने का एक-लाइन तरीका है। seen सेट वाला लूप भी काम करता है।

11. शीर्ष शब्द (मध्यम)

टेक्स्ट में n सबसे आम शब्द (word, count) जोड़ों के रूप में लौटाइए। केस अनदेखा कीजिए और हर शब्द से विराम-चिह्न .,!? हटाइए।

Python अभ्यास 11: शीर्ष शब्द

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from collections import Counter

def top_words(text: str, n: int) -> list[tuple[str, int]]:
    words = (word.strip(".,!?").lower() for word in text.split())
    return Counter(words).most_common(n)

Counter.most_common() गिनती से सॉर्ट करता है, और बराबरी वाले उसी क्रम में रहते हैं जिसमें शब्द पहली बार दिखे, इसीलिए cat, sat से पहले आता है।

12. मान के आधार पर समूह (मध्यम)

लोगों और उनके शहरों की डिक्शनरी दी गई है; ऐसी डिक्शनरी बनाइए जो हर शहर को लोगों की सॉर्ट की हुई लिस्ट से जोड़े।

Python अभ्यास 12: शहर के आधार पर समूह

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from collections import defaultdict

def by_city(people: dict[str, str]) -> dict[str, list[str]]:
    groups = defaultdict(list)
    for person, city in people.items():
        groups[city].append(person)
    return {city: sorted(names) for city, names in groups.items()}

defaultdict(list) हर लिस्ट पहली बार इस्तेमाल पर बनाता है, और अंतिम कॉम्प्रिहेंशन नामों को सॉर्ट करके सादी डिक्शनरी लौटाता है।

13. मैट्रिक्स का ट्रांसपोज़ (मध्यम)

पंक्तियों को कॉलम में बदलिए: [[1, 2, 3], [4, 5, 6]] बन जाता है [[1, 4], [2, 5], [3, 6]]। पहले कॉम्प्रिहेंशन से आज़माइए, फिर zip() से।

Python अभ्यास 13: ट्रांसपोज़

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def transpose(matrix: list[list[int]]) -> list[list[int]]:
    return [[row[col] for row in matrix] for col in range(len(matrix[0]))]

def transpose_zip(matrix: list[list[int]]) -> list[list[int]]:
    return [list(column) for column in zip(*matrix)]

zip(*matrix) पंक्तियों को अलग आर्ग्युमेंट के रूप में अनपैक करता है, इसलिए zip पहले आइटम को जोड़ी में बाँधता है, फिर दूसरे को, और इसी तरह।

फ़ंक्शन

फ़ंक्शन, आर्ग्युमेंट, रिकर्शन, हाई-ऑर्डर फ़ंक्शन और डेकोरेटर का अभ्यास।

14. लचीला औसत (शुरुआती)

average(*numbers) लिखिए जो कितने भी आर्ग्युमेंट स्वीकार करे और उनका माध्य लौटाए। बिना संख्याओं के बुलाए जाने पर उपयोगी संदेश के साथ ValueError उठाइए।

Python अभ्यास 14: लचीला औसत

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def average(*numbers: float) -> float:
    if not numbers:
        raise ValueError("average() needs at least one number")
    return sum(numbers) / len(numbers)

*numbers आर्ग्युमेंट को ट्यूपल में जमा करता है, और खाली ट्यूपल फ़ॉल्सी है, जिससे जाँच छोटी हो जाती है।

15. गहरा जोड़ (मध्यम)

ऐसी लिस्ट की हर संख्या जोड़िए जिसमें किसी भी गहराई तक नेस्टेड लिस्ट हो सकती हैं।

Python अभ्यास 15: गहरा जोड़

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def deep_sum(items: list) -> int:
    total = 0
    for item in items:
        if isinstance(item, list):
            total += deep_sum(item)
        else:
            total += item
    return total

फ़ंक्शन हर नेस्टेड लिस्ट के लिए खुद को बुलाता है, और बेस केस बस सादी संख्या है। यह रिकर्सिव हल का क्लासिक आकार है।

16. सीढ़ी चढ़ने वाला (उन्नत)

आप सीढ़ी पर एक बार में 1 या 2 कदम चढ़ सकते हैं। ways(n) लिखिए जो लौटाए कि सीढ़ी n तक पहुँचने के कितने अलग तरीके हैं। इसे n = 90 के लिए काफ़ी तेज़ बनाइए।

Python अभ्यास 16: सीढ़ी चढ़ने वाला

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from functools import cache

@cache
def ways(n: int) -> int:
    if n <= 1:
        return 1
    return ways(n - 1) + ways(n - 2)

आख़िरी चाल या तो 1 कदम है या 2, इसलिए जवाब दो छोटी समस्याओं का जोड़ है। @cache के बिना वही मान अरबों बार दोबारा निकाले जाते।

17. कॉल गिनने वाला डेकोरेटर (उन्नत)

एक डेकोरेटर counted लिखिए जो गिने कि फ़ंक्शन कितनी बार बुलाया गया और संख्या को रैपर के calls एट्रिब्यूट में रखे।

Python अभ्यास 17: कॉल काउंटर

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from functools import wraps

def counted(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

फ़ंक्शन ऑब्जेक्ट हैं, इसलिए रैपर अपना एट्रिब्यूट रख सकता है। @wraps मूल नाम और डॉकस्ट्रिंग को रैपर पर कॉपी करता है।

एरर और फ़ाइलें

एक्सेप्शन, एक्सेप्शन उठाना, फ़ाइलें और CSV फ़ाइलें का अभ्यास।

18. सुरक्षित कन्वर्ज़न (शुरुआती)

to_int(text, default=0) लिखिए जो टेक्स्ट को इंटीजर में बदले, या टेक्स्ट वैध संख्या न होने पर डिफ़ॉल्ट लौटाए।

Python अभ्यास 18: सुरक्षित कन्वर्ज़न

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def to_int(text: str, default: int = 0) -> int:
    try:
        return int(text)
    except ValueError:
        return default

केवल ValueError पकड़िए, जो int() गलत टेक्स्ट पर उठाता है, ताकि None पास करने जैसे असली बग फिर भी दिखें।

19. मान्य होने तक पूछते रहिए (मध्यम)

धनात्मक पूर्ण संख्या माँगते रहिए। जो टेक्स्ट संख्या नहीं है उसके लिए Not a number प्रिंट कीजिए; शून्य या ऋणात्मक के लिए Must be positive। अंत में स्वीकार किया गया मान प्रिंट कीजिए।

Python अभ्यास 19: मान्य होने तक पूछिए

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
while True:
    text = input("Positive number: ")
    try:
        value = int(text)
    except ValueError:
        print("Not a number")
        continue
    if value <= 0:
        print("Must be positive")
        continue
    break

print("Accepted:", value)

हर समस्या को अपना संदेश और continue मिलता है; केवल मान्य इनपुट break तक पहुँचता है। इसे फ़ंक्शन में लपेटने से यह दोबारा इस्तेमाल करने योग्य बन जाता है।

20. CSV औसत (मध्यम)

दी गई पंक्तियों को scores.csv में लिखिए, फिर फ़ाइल को वापस पढ़िए और हर छात्र का औसत एक दशमलव स्थान के साथ प्रिंट कीजिए।

Python अभ्यास 20: CSV औसत

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
import csv

rows = [
    ["name", "quiz1", "quiz2", "quiz3"],
    ["Ana", "8", "9", "10"],
    ["Ben", "6", "7", "5"],
]

with open("scores.csv", "w", newline="", encoding="utf-8") as file:
    csv.writer(file).writerows(rows)

with open("scores.csv", newline="", encoding="utf-8") as file:
    for row in csv.DictReader(file):
        marks = [int(value) for key, value in row.items() if key != "name"]
        print(f"{row['name']}: {sum(marks) / len(marks):.1f}")

CSV मान हमेशा स्ट्रिंग होते हैं, इसलिए गणित से पहले उन्हें बदलिए, और CSV फ़ाइलें newline="" के साथ खोलिए।

क्लास और ऑब्जेक्ट

क्लास, स्पेशल मेथड, कस्टम एक्सेप्शन और डेटा क्लास का अभ्यास।

21. बैंक खाता (मध्यम)

deposit() और withdraw() वाली BankAccount क्लास बनाइए। दोनों ऐसी राशियाँ ठुकराती हैं जो धनात्मक नहीं हैं, ValueError के साथ, और withdraw() बैलेंस कम होने पर InsufficientFunds एक्सेप्शन उठाता है। balance को केवल-पढ़ने वाली प्रॉपर्टी के रूप में दीजिए।

Python अभ्यास 21: बैंक खाता

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
class InsufficientFunds(Exception):
    pass

class BankAccount:
    def __init__(self, owner: str, balance: float = 0) -> None:
        self.owner = owner
        self._balance = balance

    @property
    def balance(self) -> float:
        return self._balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

    def withdraw(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("withdrawal must be positive")
        if amount > self._balance:
            raise InsufficientFunds(f"balance is only {self._balance}")
        self._balance -= amount

प्रॉपर्टी में कोई सेटर नहीं है, इसलिए account.balance = 1_000_000 से AttributeError उठता है; बैलेंस बदलने का एकमात्र तरीका वैलिडेट करने वाली मेथड हैं।

22. Vector टाइप (मध्यम)

2-D वेक्टर के लिए Vector क्लास लिखिए जो +, किसी संख्या के साथ *, ==, abs() (लंबाई) और पढ़ने योग्य repr सपोर्ट करे।

Python अभ्यास 22: Vector

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
import math

class Vector:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

    def __add__(self, other: "Vector") -> "Vector":
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, factor: float) -> "Vector":
        return Vector(self.x * factor, self.y * factor)

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Vector) and (self.x, self.y) == (other.x, other.y)

    def __abs__(self) -> float:
        return math.hypot(self.x, self.y)

    def __repr__(self) -> str:
        return f"Vector({self.x}, {self.y})"

हर ऑपरेटर एक स्पेशल मेथड से जुड़ा है। अगर आप 2 * a भी चलाना चाहें तो __rmul__ = __mul__ जोड़िए।

23. इन्वेंटरी रिपोर्ट (मध्यम)

name, price और quantity वाली डेटा क्लास Item इस्तेमाल कीजिए, साथ में value प्रॉपर्टी (कीमत गुणा मात्रा)। आइटम को सबसे ज़्यादा से सबसे कम मूल्य के स्टॉक के क्रम में प्रिंट कीजिए।

Python अभ्यास 23: इन्वेंटरी रिपोर्ट

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    price: float
    quantity: int

    @property
    def value(self) -> float:
        return self.price * self.quantity

stock = [Item("Lamp", 24.5, 10), Item("Desk", 240.0, 2), Item("Pen", 1.2, 300)]
for item in sorted(stock, key=lambda i: i.value, reverse=True):
    print(f"{item.name:<6}{item.value:>8.2f}")

डेटा क्लास आपके लिए __init__ और __repr__ लिखती है; प्रॉपर्टी value को हमेशा कीमत और मात्रा के साथ तालमेल में रखती है।

उन्नत चुनौतियाँ

जनरेटर, डेटा स्ट्रक्चर और एल्गोरिदम का अभ्यास।

24. फ़िबोनाची जनरेटर (मध्यम)

जनरेटर fibonacci() लिखिए जो फ़िबोनाची संख्याएँ हमेशा के लिए yield करे (0, 1, 1, 2, 3, 5, ...)। पहले 12 प्रिंट करने के लिए itertools.islice इस्तेमाल कीजिए।

Python अभ्यास 24: फ़िबोनाची जनरेटर

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
from itertools import islice

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(islice(fibonacci(), 12)))

अनंत जनरेटर ठीक है क्योंकि मान एक-एक करके, केवल माँगे जाने पर बनते हैं। islice 12 के बाद रुक जाता है।

25. रन-लेंथ एनकोडिंग (उन्नत)

दोहराए अक्षरों को संपीड़ित कीजिए: "aaabccdddd" बन जाता है "3a1b2c4d"। फिर उसे उलटने के लिए decode() लिखिए (गिनती में कई अंक हो सकते हैं)।

Python अभ्यास 25: रन-लेंथ एनकोडिंग

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
import re
from itertools import groupby

def encode(text: str) -> str:
    return "".join(f"{len(list(group))}{char}" for char, group in groupby(text))

def decode(code: str) -> str:
    return "".join(char * int(count) for count, char in re.findall(r"(\d+)(\D)", code))

itertools.groupby लगातार बराबर अक्षरों को समूह में बाँधता है, और रेगुलर एक्सप्रेशन कोड को (गिनती, अक्षर) जोड़ों में बाँटता है।

26. इन्सर्ट स्थिति के साथ बाइनरी सर्च (उन्नत)

सॉर्ट की हुई लिस्ट के लिए search(items, target) लिखिए। अगर target मौजूद है तो उसका इंडेक्स लौटाइए; वरना वह इंडेक्स लौटाइए जहाँ लिस्ट को सॉर्ट रखने के लिए उसे डाला जाना चाहिए। bisect इस्तेमाल मत कीजिए; इसे O(log n) बनाइए।

Python अभ्यास 26: खोजें या डालें

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
def search(items: list[int], target: int) -> int:
    low, high = 0, len(items)
    while low < high:
        middle = (low + high) // 2
        if items[middle] < target:
            low = middle + 1
        else:
            high = middle
    return low

यह "अर्ध-खुला" संस्करण (high = len(items) और low < high) हमेशा उस पहली स्थिति पर ख़त्म होता है जिसका मान कम से कम target है, जो ठीक वही है जो bisect_left लौटाता है।

27. पोस्टफ़िक्स कैलकुलेटर (उन्नत)

पोस्टफ़िक्स नोटेशन के एक्सप्रेशन का मान निकालिए, जिसमें ऑपरेटर अपने ऑपरेंड के बाद आते हैं: "3 4 + 2 *" का मतलब है (3 + 4) * 2। स्टैक इस्तेमाल कीजिए। गलत बने इनपुट के लिए ValueError उठाइए।

Python अभ्यास 27: पोस्टफ़िक्स कैलकुलेटर

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

समाधान दिखाएँ
Python
import operator

OPERATORS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

def evaluate(expression: str) -> float:
    stack: list[float] = []
    for token in expression.split():
        if token in OPERATORS:
            if len(stack) < 2:
                raise ValueError(f"not enough operands for {token!r}")
            right = stack.pop()
            left = stack.pop()
            stack.append(OPERATORS[token](left, right))
        else:
            stack.append(float(token))
    if len(stack) != 1:
        raise ValueError("expression must leave exactly one value")
    return stack[0]

संख्याएँ पुश होती हैं; हर ऑपरेटर दो मान पॉप करता है (दायाँ ऑपरेंड पहले निकलता है) और नतीजा पुश करता है। operator के फ़ंक्शन की डिक्शनरी लंबी if/elif शृंखला की जगह लेती है।

अपनी समझ जाँचें

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. अभ्यास 10 में list(dict.fromkeys(items)) मूल क्रम क्यों बनाए रखता है?

    Python 3.7 से डिक्शनरी इन्सर्शन क्रम सुरक्षित रखती हैं, इसलिए हर मान की पहली उपस्थिति उसकी स्थिति तय करती है।
  2. 2. अभ्यास 16 का सीढ़ी वाला समाधान n = 90 के लिए इतना तेज़ क्यों है?

    कैशिंग के बिना वही उप-समस्याएँ घातांकीय बार दोबारा निकाली जातीं।
  3. 3. पोस्टफ़िक्स कैलकुलेटर में पहला पॉप किया मान दायाँ ऑपरेंड क्यों है?

    10 4 /" के लिए 4, 10 के बाद पुश होता है, इसलिए वह पहले निकलता है और भाजक होना चाहिए।

सारांश

  • आपने स्ट्रिंग, कंट्रोल फ़्लो, संग्रह, फ़ंक्शन, एरर, फ़ाइलों, क्लास और एल्गोरिदम में 27 समस्याओं का अभ्यास किया।
  • जिस समूह के अभ्यास कठिन लगे उसे दोबारा देखिए, और दोबारा कोशिश से पहले जुड़ा पाठ फिर पढ़िए।
  • जो अभ्यास आपने हल किए उनके लिए दूसरा, अलग समाधान लिखने की कोशिश कीजिए: कॉम्प्रिहेंशन की जगह लूप, या उलटा।

अगला: Python इंटरव्यू प्रश्न, आम सवाल संक्षिप्त जवाबों के साथ, यह परखने के लिए कि आप जो जानते हैं उसे कितनी अच्छी तरह समझा सकते हैं।

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।