Skip to content
English

Examples

Every program on this page is complete: copy it into a file ending in .alg and run it with algorizm. The output shown under each program was produced by running it.

Fibonacci numbers

The same sequence computed in two ways: by a function that calls itself, and by a loop that is fast enough for large numbers.

funksiya fib(n):
    agar n < 2:
        qaytar n
    qaytar fib(n - 1) + fib(n - 2)

funksiya fib_tez(n):
    a, b = 0, 1
    har i ichida oraliq(n):
        a, b = b, a + b
    qaytar a

sonlar = qo'lla(fib, oraliq(15))
chiqar("Dastlabki 15 ta son:", sonlar.birlashtir(", "))
chiqar("fib(80) =", fib_tez(80))
Output
Dastlabki 15 ta son: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
fib(80) = 23416728348467685

Prime numbers

The sieve of Eratosthenes: cross out the multiples of every prime, and what is left are the primes.

funksiya tub_sonlar(n):
    tubmi = [rost] * (n + 1)
    tubmi[0] = yolg'on
    tubmi[1] = yolg'on
    i = 2
    toki i * i <= n:
        agar tubmi[i]:
            j = i * i
            toki j <= n:
                tubmi[j] = yolg'on
                j += i
        i += 1
    qaytar filtrla(funksiya(k): tubmi[k], oraliq(n + 1))

tublar = tub_sonlar(100)
chiqar(f"100 gacha {uzunlik(tublar)} ta tub son bor:")
chiqar(tublar.birlashtir(", "))
Output
100 gacha 25 ta tub son bor:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

Counting words

A dictionary counts how often each word occurs, and the result is sorted by the count.

gap = "olma anor olma uzum anor olma behi"

sanoq = {}
har soz ichida gap.ajrat():
    sanoq[soz] = sanoq.ol(soz, 0) + 1

har soz, marta ichida saralangan(sanoq.juftlar(), funksiya(j): -j[1]):
    chiqar(f"{formatla(soz, '6')} {'#' * marta} {marta}")
Output
olma   ### 3
anor   ## 2
uzum   # 1
behi   # 1

Multiplication table

formatla pads every number to the same width, so the columns line up.

har i ichida oraliq(1, 6):
    qator = []
    har j ichida oraliq(1, 6):
        qator.qo'sh(formatla(i * j, "4"))
    chiqar(qator.birlashtir(""))
Output
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

A small library

Two classes, a dictionary of objects, and errors that are raised with tashla and caught with urin / ushla.

sinf Kitob:
    funksiya yarat(nom, muallif, yil):
        bu.nom = nom
        bu.muallif = muallif
        bu.yil = yil
        bu.band = yolg'on

    funksiya tavsif():
        holat = "bo'sh"
        agar bu.band:
            holat = "band"
        qaytar f"\"{bu.nom}\", {bu.muallif}, {bu.yil} ({holat})"

sinf Kutubxona:
    funksiya yarat():
        bu.kitoblar = {}

    funksiya qo'sh(kitob):
        bu.kitoblar[kitob.nom] = kitob

    funksiya ber(nom):
        agar nom emas ichida bu.kitoblar:
            tashla f"\"{nom}\" kitobi kutubxonada yo'q"
        kitob = bu.kitoblar[nom]
        agar kitob.band:
            tashla f"\"{nom}\" kitobi hozir band"
        kitob.band = rost
        qaytar kitob

    funksiya royxat():
        har nom ichida bu.kitoblar:
            chiqar(" -", bu.kitoblar[nom].tavsif())

k = Kutubxona()
k.qo'sh(Kitob("O'tkan kunlar", "Abdulla Qodiriy", 1926))
k.qo'sh(Kitob("Kecha va kunduz", "Cho'lpon", 1936))
k.qo'sh(Kitob("Yulduzli tunlar", "Pirimqul Qodirov", 1978))

har nom ichida ["O'tkan kunlar", "O'tkan kunlar", "Sarob"]:
    urin:
        kitob = k.ber(nom)
        chiqar("Berildi:", kitob.nom)
    ushla xato:
        chiqar("Bo'lmadi:", xato)

chiqar("Kutubxonadagi kitoblar:")
k.royxat()
Output
Berildi: O'tkan kunlar
Bo'lmadi: "O'tkan kunlar" kitobi hozir band
Bo'lmadi: "Sarob" kitobi kutubxonada yo'q
Kutubxonadagi kitoblar:
 - "O'tkan kunlar", Abdulla Qodiriy, 1926 (band)
 - "Kecha va kunduz", Cho'lpon, 1936 (bo'sh)
 - "Yulduzli tunlar", Pirimqul Qodirov, 1978 (bo'sh)

Marks in a JSON file

The program writes a list of dictionaries to a JSON file, reads it back, and prints the students sorted by their average mark.

import json
import fayl

talabalar = [
    {"ism": "Ali", "baholar": [5, 4, 5]},
    {"ism": "Guli", "baholar": [5, 5, 5]},
    {"ism": "Vali", "baholar": [3, 4, 4]}
]

fayl.yoz("talabalar.json", json.matn(talabalar, 2))
oqilgan = json.tahlil(fayl.o'qi("talabalar.json"))
fayl.o'chir("talabalar.json")

har t ichida saralangan(oqilgan, funksiya(t): -yig'indi(t["baholar"])):
    ortacha = yig'indi(t["baholar"]) / uzunlik(t["baholar"])
    chiqar(f"{formatla(t['ism'], '5')} {formatla(ortacha, '.2f')}")
Output
Guli  5.00
Ali   4.67
Vali  3.67

Guess the number

An interactive game: the program thinks of a number, and you guess it. It reads your answers with kirit, so it has no fixed output.

import tasodif

sir = tasodif.butun(1, 100)
urinishlar = 0

chiqar("Men 1 dan 100 gacha son o'yladim. Toping!")
toki rost:
    javob = kirit("Taxminingiz: ")
    agar javob == bo'sh:
        to'xta
    agar emas javob.raqammi():
        chiqar("Iltimos, son kiriting")
        davom
    urinishlar += 1
    taxmin = butun(javob)
    agar taxmin < sir:
        chiqar("Kattaroq")
    yoki agar taxmin > sir:
        chiqar("Kichikroq")
    aks holda:
        chiqar(f"Topdingiz! Urinishlar soni: {urinishlar}")
        to'xta