Lompat ke konten

Pelajaran 148 ยท Practice and Review

Latihan Python

27 latihan Python bertingkat dengan solusi tentang string, perulangan, dictionary, fungsi, berkas, kelas, generator, dan algoritma. Jalankan langsung di browsermu.

Membaca tentang kode dan menulis kode adalah dua keterampilan yang berbeda, dan hanya latihan yang membangun yang kedua. Halaman ini mengumpulkan 27 latihan yang mencakup seluruh kursus, dikelompokkan menurut topik dan diurutkan dari pemula sampai lanjutan. Setiap latihan punya tugas singkat, editor dengan kode awal, dan solusi yang tersembunyi.

Berikut cara mendapatkan manfaat terbesar darinya:

  • Coba dulu, intip kemudian. Berikan setiap latihan percobaan yang sungguh-sungguh sebelum membuka solusinya. Buntu selama beberapa menit adalah saat belajar terjadi.
  • Sering-seringlah menjalankan. Setiap kode awal mencetak pemanggilan uji, sehingga kamu bisa melihat kapan keluaranmu cocok dengan hasil yang diharapkan di komentar.
  • Bandingkan, jangan salin. Solusimu mungkin tampak berbeda dari solusi kami dan tetap benar. Baca solusi kami untuk mendapat ide, lalu perbaiki solusimu sendiri.

Setiap kelompok latihan menaut ke pelajaran yang dilatihnya, dan contekan berguna untuk dibiarkan terbuka di tab lain. Latihan yang memakai input() disertai jawaban awal di kotak Input editor, yang bisa kamu ubah untuk menguji nilai lain.

String dan dasar-dasar

Latihan ini melatih variabel, input dan output, string, metode string, dan pemformatan string.

1. Ucapan ulang tahun (Pemula)

Baca nama dan usia dengan input(), lalu cetak baris seperti Hi Mina! Next year you'll be 28. Ingat bahwa input() selalu mengembalikan string.

Python Latihan 1: Ucapan ulang tahun

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.

Tampilkan solusi
Python
name = input("Name: ")
age = int(input("Age: "))

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

Mengonversi dengan int() adalah langkah kuncinya: menambahkan 1 ke string "27" akan memunculkan TypeError.

2. Tabel konversi (Pemula)

Cetak tabel suhu Celsius dari 0 sampai 100 dengan kelipatan 20 beserta nilai Fahrenheit-nya (F = C * 9 / 5 + 32). Ratakan kolom-kolomnya dan tampilkan satu angka desimal untuk Fahrenheit.

Python Latihan 2: Tabel konversi

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.

Tampilkan solusi
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) menyertakan 100 karena nilai stop tidak disertakan, dan spesifikasi format >4 dan >8.1f meratakan setiap kolom ke kanan.

3. Pemeriksa palindrom (Pemula)

Tulis is_palindrome(text) yang mengembalikan True jika teks terbaca sama dari belakang, dengan mengabaikan huruf besar-kecil, spasi, dan tanda baca.

Python Latihan 3: Palindrom

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.

Tampilkan solusi
Python
def is_palindrome(text: str) -> bool:
    letters = [char.lower() for char in text if char.isalnum()]
    return letters == letters[::-1]

Hanya menyimpan karakter alfanumerik menghapus spasi dan tanda baca, dan [::-1] memberi salinan terbalik untuk dibandingkan.

4. Penghitung vokal (Pemula)

Tulis count_vowels(text) yang mengembalikan dictionary berisi berapa kali setiap vokal (a, e, i, o, u) muncul, dengan mengabaikan huruf besar-kecil. Sertakan vokal yang muncul nol kali.

Python Latihan 4: Penghitung vokal

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.

Tampilkan solusi
Python
def count_vowels(text: str) -> dict[str, int]:
    lowered = text.lower()
    return {vowel: lowered.count(vowel) for vowel in "aeiou"}

Dict comprehension atas "aeiou" menjamin setiap vokal muncul sebagai kunci, dan str.count() yang melakukan penghitungan.

Alur kendali

Latihan untuk pernyataan if, perulangan for, perulangan while, dan break dan continue.

5. Tick-Tock (Pemula)

Untuk angka 1 sampai 20, cetak Tick untuk kelipatan 3, Tock untuk kelipatan 5, TickTock untuk kelipatan keduanya, dan angka itu sendiri untuk selainnya.

Python Latihan 5: Tick-Tock

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.

Tampilkan solusi
Python
for n in range(1, 21):
    word = ""
    if n % 3 == 0:
        word += "Tick"
    if n % 5 == 0:
        word += "Tock"
    print(word or n)

Menyusun kata dalam dua pemeriksaan if yang independen menangani "keduanya" secara otomatis, dan word or n kembali ke angka ketika kata kosong.

6. Tahun kabisat (Pemula)

Sebuah tahun adalah tahun kabisat jika habis dibagi 4, kecuali tahun yang habis dibagi 100, kecuali jika juga habis dibagi 400. Tulis is_leap(year).

Python Latihan 6: Tahun kabisat

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.

Tampilkan solusi
Python
def is_leap(year: int) -> bool:
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Tanda kurung mengelompokkan pengecualian dan pengecualian dari pengecualiannya. Dalam kode nyata, calendar.isleap(year) melakukan pekerjaan yang sama.

7. Akar digital (Menengah)

Jumlahkan digit-digit sebuah angka. Jika hasilnya lebih dari satu digit, ulangi sampai tersisa satu digit. Untuk 98.765: 9+8+7+6+5 = 35, lalu 3+5 = 8.

Python Latihan 7: Akar digital

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.

Tampilkan solusi
Python
def digital_root(number: int) -> int:
    while number >= 10:
        number = sum(int(digit) for digit in str(number))
    return number

Perulangan while berulang persis selama ada lebih dari satu digit; mengonversi ke string adalah cara paling sederhana untuk mengunjungi digit-digitnya.

8. Tebak angka (Menengah)

Angka rahasianya 37. Terus minta tebakan, jawab Too low atau Too high, dan saat tebakan benar, cetak berapa kali percobaan yang dibutuhkan. Kotak Input sudah berisi tiga tebakan.

Python Latihan 8: Tebak angka

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.

Tampilkan solusi
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

while True dengan break cocok untuk perulangan yang kondisi keluarnya ditemukan di tengah. Proyek tebak angka membangun versi lengkapnya.

List, dictionary, dan set

Latihan untuk list, metode list, dictionary, set, comprehension, dan collections.

9. Terbesar kedua (Pemula)

Kembalikan nilai terbesar kedua yang berbeda dalam sebuah list, atau None jika tidak ada.

Python Latihan 9: Terbesar kedua

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.

Tampilkan solusi
Python
def second_largest(numbers: list[int]) -> int | None:
    unique = sorted(set(numbers), reverse=True)
    return unique[1] if len(unique) >= 2 else None

Set menghapus angka 9 yang ganda, sehingga item kedua dari hasil terurut adalah jawabannya. Untuk list yang sangat besar, satu lintasan yang melacak dua nilai teratas menghindari pengurutan.

10. Hapus duplikat, pertahankan urutan (Pemula)

Kembalikan list baru tanpa duplikat, dengan mempertahankan kemunculan pertama setiap nilai di posisi aslinya.

Python Latihan 10: Unik sesuai urutan

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.

Tampilkan solusi
Python
def unique(items: list) -> list:
    return list(dict.fromkeys(items))

Dictionary menjaga urutan penyisipan dan tidak bisa punya kunci duplikat, jadi dict.fromkeys() adalah cara satu baris untuk menghapus duplikat sambil mempertahankan urutan. Perulangan dengan set seen juga bisa.

11. Kata teratas (Menengah)

Kembalikan n kata paling umum dalam sebuah teks sebagai pasangan (word, count). Abaikan huruf besar-kecil dan buang tanda baca .,!? dari setiap kata.

Python Latihan 11: Kata teratas

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.

Tampilkan solusi
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() mengurutkan berdasarkan jumlah, dan seri mempertahankan urutan kata pertama kali terlihat, itulah sebabnya cat muncul sebelum sat.

12. Kelompokkan berdasarkan nilai (Menengah)

Diberi dictionary berisi orang dan kotanya, bangun dictionary yang memetakan setiap kota ke list terurut berisi orang-orangnya.

Python Latihan 12: Kelompokkan per kota

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.

Tampilkan solusi
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) membuat setiap list saat pertama dipakai, dan comprehension terakhir mengurutkan nama-namanya lalu mengembalikan dictionary biasa.

13. Transpos matriks (Menengah)

Ubah baris menjadi kolom: [[1, 2, 3], [4, 5, 6]] menjadi [[1, 4], [2, 5], [3, 6]]. Coba dengan comprehension, lalu dengan zip().

Python Latihan 13: Transpos

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.

Tampilkan solusi
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) membongkar baris-baris sebagai argumen terpisah, sehingga zip memasangkan item pertama, lalu item kedua, dan seterusnya.

Fungsi

Latihan untuk fungsi, argumen, rekursi, fungsi tingkat tinggi, dan dekorator.

14. Rata-rata fleksibel (Pemula)

Tulis average(*numbers) yang menerima sejumlah argumen dan mengembalikan rata-ratanya. Munculkan ValueError dengan pesan yang membantu bila dipanggil tanpa angka.

Python Latihan 14: Rata-rata fleksibel

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.

Tampilkan solusi
Python
def average(*numbers: float) -> float:
    if not numbers:
        raise ValueError("average() needs at least one number")
    return sum(numbers) / len(numbers)

*numbers mengumpulkan argumen ke dalam tuple, dan tuple kosong bernilai falsy, yang membuat pemeriksaannya singkat.

15. Jumlah dalam (Menengah)

Jumlahkan setiap angka dalam list yang bisa berisi list bersarang pada kedalaman berapa pun.

Python Latihan 15: Jumlah dalam

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.

Tampilkan solusi
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

Fungsi memanggil dirinya sendiri untuk setiap list bersarang, dan kasus dasarnya hanyalah angka biasa. Inilah bentuk klasik solusi rekursif.

16. Pendaki tangga (Lanjutan)

Kamu bisa menaiki tangga 1 atau 2 anak tangga sekaligus. Tulis ways(n) yang mengembalikan berapa banyak cara berbeda untuk mencapai anak tangga ke-n. Buat cukup cepat untuk n = 90.

Python Latihan 16: Pendaki tangga

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.

Tampilkan solusi
Python
from functools import cache

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

Langkah terakhir adalah 1 atau 2 anak tangga, jadi jawabannya adalah jumlah dari dua masalah yang lebih kecil. Tanpa @cache, nilai yang sama akan dihitung ulang miliaran kali.

17. Dekorator penghitung panggilan (Lanjutan)

Tulis dekorator counted yang menghitung berapa kali sebuah fungsi dipanggil dan menyimpan angkanya dalam atribut calls pada wrapper.

Python Latihan 17: Penghitung panggilan

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.

Tampilkan solusi
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

Fungsi adalah objek, sehingga wrapper bisa membawa atributnya sendiri. @wraps menyalin nama dan docstring asli ke wrapper.

Galat dan berkas

Latihan untuk exception, memunculkan exception, berkas, dan berkas CSV.

18. Konversi aman (Pemula)

Tulis to_int(text, default=0) yang mengonversi teks menjadi bilangan bulat, atau mengembalikan nilai default bila teks bukan angka yang valid.

Python Latihan 18: Konversi aman

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.

Tampilkan solusi
Python
def to_int(text: str, default: int = 0) -> int:
    try:
        return int(text)
    except ValueError:
        return default

Tangkap hanya ValueError, galat yang dimunculkan int() untuk teks yang buruk, sehingga bug sungguhan seperti meneruskan None tetap muncul.

19. Tanya sampai valid (Menengah)

Terus minta bilangan bulat positif. Untuk teks yang bukan angka, cetak Not a number; untuk nol atau negatif, cetak Must be positive. Cetak nilai yang diterima di akhir.

Python Latihan 19: Tanya sampai valid

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.

Tampilkan solusi
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)

Setiap masalah mendapat pesan dan continue-nya sendiri; hanya input yang valid yang mencapai break. Membungkus ini dalam fungsi membuatnya bisa dipakai ulang.

20. Rata-rata dari CSV (Menengah)

Tulis baris yang diberikan ke scores.csv, lalu baca kembali berkasnya dan cetak rata-rata setiap siswa dengan satu angka desimal.

Python Latihan 20: Rata-rata dari 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.

Tampilkan solusi
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}")

Nilai CSV selalu berupa string, jadi konversi sebelum menghitung, dan buka berkas CSV dengan newline="".

Kelas dan objek

Latihan untuk kelas, metode khusus, exception kustom, dan data class.

21. Rekening bank (Menengah)

Buat kelas BankAccount dengan deposit() dan withdraw(). Keduanya menolak jumlah yang tidak positif dengan ValueError, dan withdraw() memunculkan exception InsufficientFunds saat saldo terlalu rendah. Ekspos balance sebagai properti hanya-baca.

Python Latihan 21: Rekening bank

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.

Tampilkan solusi
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

Properti tidak punya setter, jadi account.balance = 1_000_000 memunculkan AttributeError; satu-satunya cara mengubah saldo adalah lewat metode yang tervalidasi.

22. Tipe Vector (Menengah)

Tulis kelas Vector untuk vektor 2-D yang mendukung +, * dengan angka, ==, abs() (panjangnya), dan repr yang mudah dibaca.

Python Latihan 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.

Tampilkan solusi
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})"

Setiap operator dipetakan ke metode khusus. Tambahkan __rmul__ = __mul__ jika kamu juga ingin 2 * a berfungsi.

23. Laporan inventaris (Menengah)

Pakai data class Item dengan name, price, dan quantity, ditambah properti value (harga dikali jumlah). Cetak item dari stok yang paling bernilai sampai yang paling tidak bernilai.

Python Latihan 23: Laporan inventaris

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.

Tampilkan solusi
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}")

Data class menuliskan __init__ dan __repr__ untukmu; properti menjaga value selalu sinkron dengan harga dan jumlah.

Tantangan lanjutan

Latihan untuk generator, struktur data, dan algoritma.

24. Generator Fibonacci (Menengah)

Tulis generator fibonacci() yang menghasilkan bilangan Fibonacci tanpa henti (0, 1, 1, 2, 3, 5, ...). Pakai itertools.islice untuk mencetak 12 yang pertama.

Python Latihan 24: Generator Fibonacci

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.

Tampilkan solusi
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)))

Generator tak terhingga tidak masalah karena nilai dihasilkan satu per satu, hanya saat diminta. islice berhenti setelah 12.

25. Run-length encoding (Lanjutan)

Kompres karakter yang berulang: "aaabccdddd" menjadi "3a1b2c4d". Lalu tulis decode() untuk membaliknya (hitungan bisa terdiri dari beberapa digit).

Python Latihan 25: Run-length encoding

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.

Tampilkan solusi
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 mengelompokkan karakter berurutan yang sama, dan ekspresi reguler memecah kode menjadi pasangan (hitungan, karakter).

26. Pencarian biner dengan posisi sisip (Lanjutan)

Tulis search(items, target) untuk list terurut. Kembalikan indeks target jika ada; jika tidak, kembalikan indeks tempat ia harus disisipkan agar list tetap terurut. Jangan pakai bisect; buat O(log n).

Python Latihan 26: Cari atau sisipkan

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.

Tampilkan solusi
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

Versi "setengah terbuka" ini (high = len(items) dan low < high) selalu berakhir di posisi pertama yang nilainya setidaknya target, yang persis dikembalikan bisect_left.

27. Kalkulator postfix (Lanjutan)

Evaluasi ekspresi dalam notasi postfix, di mana operator datang setelah operandnya: "3 4 + 2 *" berarti (3 + 4) * 2. Pakai stack. Munculkan ValueError untuk input yang salah bentuk.

Python Latihan 27: Kalkulator postfix

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.

Tampilkan solusi
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]

Angka di-push; setiap operator mem-pop dua nilai (operand kanan keluar lebih dulu) dan mem-push hasilnya. Dictionary fungsi dari operator menggantikan rantai if/elif yang panjang.

Periksa pemahamanmu

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Pada latihan 10, mengapa list(dict.fromkeys(items)) mempertahankan urutan aslinya?

    Sejak Python 3.7, dict mempertahankan urutan penyisipan, sehingga kemunculan pertama setiap nilai menentukan posisinya.
  2. 2. Apa yang membuat solusi tangga pada latihan 16 cukup cepat untuk n = 90?

    Tanpa caching, submasalah yang sama dihitung ulang sebanyak eksponensial kali.
  3. 3. Dalam kalkulator postfix, mengapa nilai pertama yang di-pop dipakai sebagai operand kanan?

    Untuk "10 4 /", angka 4 di-push setelah 10, sehingga ia keluar lebih dulu dan harus menjadi pembaginya.

Ringkasan

  • Kamu telah melatih 27 soal tentang string, alur kendali, koleksi, fungsi, galat, berkas, kelas, dan algoritma.
  • Kunjungi kembali kelompok mana pun yang latihannya terasa sulit, dan baca ulang pelajaran yang ditautkan sebelum mencoba lagi.
  • Cobalah menulis solusi kedua yang berbeda untuk latihan yang sudah kamu selesaikan: perulangan sebagai ganti comprehension, atau sebaliknya.

Selanjutnya: Pertanyaan Wawancara Python, pertanyaan umum dengan jawaban ringkas untuk menguji seberapa baik kamu bisa menjelaskan apa yang kamu ketahui.

Pantau kemajuanmu

Buat akun gratis untuk menandai pelajaran yang selesai dan melanjutkan dari tempat terakhirmu di perangkat mana pun.