Tutorial Python untuk bukan pengatur cara/Contoh Fungsi Lanjutan: Perbezaan antara semakan

Daripada Wikibooks
Kandungan dihapus Kandungan ditambah
Algazel (bincang | sumb.)
→‎Contoh: terjemah contoh
Algazel (bincang | sumb.)
kembang
Baris 30: Baris 30:
return 0
return 0
baki = mult(a, b - 1)
baki = mult(a, b - 1)
value = a + baki
nilai = a + baki
return value
return nilai
</source>
</source>
}}
}}
Baris 47: Baris 47:
----
----


'''RUN 2'''
'''PELAKSANAAN 2'''
; Apa yang berlaku kemudiannya?
; What happens next?
: The variable <code>a</code> gets the value 3 assigned to it and the variable <code>b</code> gets the value 2 assigned to it.
: Pemboleh ubah <code>a</code> menerima nilai 3 yang diumpukkan kepadanya dan pemboleh ubah <code>b</code> menerima nilai 2.
----
----
; And then?
; Kemudian?
: The line <code>if b == 0:</code> is run. Since <code>b</code> has the value 2 this is false so the line <code>return 0</code> is skipped.
: Baris <code>if b == 0:</code> dilaksanakan. Oleh sebab <code>b</code> mempunyai nilai 2, ini bermaksud Palsu, jadi baris <code>return 0</code> dilangkau.
----
----
; And what then?
; Dan kemudian?
: The line <code>rest = mult(a, b - 1)</code> is run. This line sets the local variable <code>rest</code> to the value of <code>mult(a, b - 1)</code>. The value of <code> a</code> is 3 and the value of <code> b</code> is 2 so the function call is <code>mult(3,1)</code>
: Baris <code>baki = mult(a, b - 1)</code> dilaksanakan. Baris ini menetapkan pemboleh ubah lokal <code>baki</code> kepada nilai <code>mult(a, b - 1)</code>. Nilai <code> a</code> adalah 3 dan nilai <code> b</code> adalah 2 jadi panggilan fungsi adalah <code>mult(3,1)</code>
----
----
; So what is the value of <code>mult(3, 1)</code> ?
; Jadi apa pula nilai <code>mult(3, 1)</code> ?
: We will need to run the function <code> mult</code> with the parameters 3 and 1.
: Kita perlu melaksanakan fungsi <code> mult</code> dengan parameter 3 dan 1.
{{Penyelesaian|tajuk=PELAKSANAAN 2|teks=
{{Solution|title=RUN 2|text=
<source lang="python">
<source lang="python">
def mult(3, 2):
def mult(3, 2):
if b == 0:
if b == 0:
return 0
return 0
rest = mult(3, 2 - 1)
baki = mult(3, 2 - 1)
rest = mult(3, 1)
baki = mult(3, 1)
value = 3 + rest
nilai = 3 + baki
return value
return nilai
</source>
</source>
}}
}}


----
----
'''RUN 3'''
'''PELAKSANAAN 3'''
; Apa yang berlaku seterusnya?
; So what happens next?
: The local variables in the '' new'' run of the function are set so that <code>a</code> has the value 3 and <code> b</code> has the value 1. Since these are local values these do not affect the previous values of <code>a</code> and <code>b</code>.
: Pemboleh ubah lokal dalam pelaksanaan ''baru'' fungsi ditetapkan agar <code>a</code> memiliki nilai 3 dan <code> b</code> memiliki nilai 1. Memandangkan bahawa ini adalah nilai-nilai lokal, nilai-nilai ini tidak menjejaskan nilai-nilai <code>a</code> dan <code>b</code> sebelum ini.
----
----
; And then?
; Kemudian?
: Since <code> b</code> has the value 1 the if statement is false, so the next line becomes <code>rest = mult(a, b - 1)</code>.
: Oleh sebab <code> b</code> memiliki nilai 1, kenyataan <code>if</code> menjadi Palsu, jadi baris berikutnya menjadi <code>baki = mult(a, b - 1)</code>.
----
----
; What does this line do?
; Apa yang dilakukan baris ini?
: This line will assign the value of <code>mult(3, 0)</code> to rest.
: Baris ini akan mengumpukkan nilai <code>mult(3, 0)</code> kepada baki.
----
----
; Apakah nilai itu?
; So what is that value?
: We will have to run the function one more time to find that out. This time <code>a</code> has the value 3 and <code>b</code> has the value 0.
: Kita perlu melaksanakan kod sekali lagi bagi mendapatkan jawapannya. Kali ini nilai <code>a</code> adalah 3 dan nilai <code>b</code> adalah 0.
----
----
; So what happens next?
; So what happens next?

Semakan pada 01:49, 20 Julai 2013


Ada pembaca yang mendapati bahagian ini berguna dan sebilangan pula akan mendapatinya mengelirukan. Jika anda mendapatinya mengelirukan, tinggalkan (ataupun lihat contoh-contohnya) dahulu. sekarang kita akan membincangkan program berikut satu persatu:

def mult(a, b):
    if b == 0:
        return 0
    baki = mult(a, b - 1)
    nilai = a + baki
    return nilai
print "3 * 2 = ", mult(3, 2)
Output
3 * 2 =  6


Secara amnya program ini mewujudkan satu fungsi darab integer positif (yang lebih perlahan daripada fungsi darab bina dalam) dan kemudian menunjukkan fungsi ini melalui penggunaannya. Atur cara ini menunjukkan penggunaan rekursi, sebuah bentuk lelaran (ulangan) yang menyebabakan fungsi ini memanggil dirinya sendiri sehinggalah sebuah syarat tamat dilunaskan. Ia mengguna tambahan berulang bagi memulangkan keputusan yang sama dengan darab: contoh, 3 + 3 (tambah) memberikan keputusan yang sama dengan 3 * 2 (darab)

PELAKSANAAN 1

Soalan: Apakah perkara pertama yang dilakukan atur cara?
Jawapan: Perkara pertama yang dilakukan adalah fungsi "mult" diberi definisi dengan semua baris melainkan baris yang terakhir.
definisi fungsi mult
def mult(a, b):
    if b == 0:
        return 0
    baki = mult(a, b - 1)
    nilai = a + baki
    return nilai
Ini mewujudkan sebuah fungsi yang mengambil dua parameter dan memulangkan nilai apabila ia selesai. Fungsi ini dapat dilaksanakan kemudian.

Apa yang jadi kemudian?
Baris selepas fungsi, print "3 * 2 = ", mult(3, 2) dilaksanakan.

Dan apa yang dilakukannya?
Ia mencetak 3 * 2 = dan memulangkan nilai mult(3, 2)

Dan apa yang dipulangkan mult(3, 2) ?
Kita perlu melihat fungsi mult satu persatu jika kita ingin tahu.

PELAKSANAAN 2

Apa yang berlaku kemudiannya?
Pemboleh ubah a menerima nilai 3 yang diumpukkan kepadanya dan pemboleh ubah b menerima nilai 2.

Kemudian?
Baris if b == 0: dilaksanakan. Oleh sebab b mempunyai nilai 2, ini bermaksud Palsu, jadi baris return 0 dilangkau.

Dan kemudian?
Baris baki = mult(a, b - 1) dilaksanakan. Baris ini menetapkan pemboleh ubah lokal baki kepada nilai mult(a, b - 1). Nilai a adalah 3 dan nilai b adalah 2 jadi panggilan fungsi adalah mult(3,1)

Jadi apa pula nilai mult(3, 1) ?
Kita perlu melaksanakan fungsi mult dengan parameter 3 dan 1.
PELAKSANAAN 2
def mult(3, 2):
    if b == 0:
        return 0
    baki = mult(3, 2 - 1)
    baki = mult(3, 1)
    nilai = 3 + baki
    return nilai



PELAKSANAAN 3

Apa yang berlaku seterusnya?
Pemboleh ubah lokal dalam pelaksanaan baru fungsi ditetapkan agar a memiliki nilai 3 dan b memiliki nilai 1. Memandangkan bahawa ini adalah nilai-nilai lokal, nilai-nilai ini tidak menjejaskan nilai-nilai a dan b sebelum ini.

Kemudian?
Oleh sebab b memiliki nilai 1, kenyataan if menjadi Palsu, jadi baris berikutnya menjadi baki = mult(a, b - 1).

Apa yang dilakukan baris ini?
Baris ini akan mengumpukkan nilai mult(3, 0) kepada baki.

Apakah nilai itu?
Kita perlu melaksanakan kod sekali lagi bagi mendapatkan jawapannya. Kali ini nilai a adalah 3 dan nilai b adalah 0.

So what happens next?
The first line in the function to run is if b == 0:. b has the value 0 so the next line to run is return 0

And what does the line return 0 do?
This line returns the value 0 out of the function.

So?
So now we know that mult(3, 0) has the value 0. Now we know what the line rest = mult(a, b - 1) did since we have run the function mult with the parameters 3 and 0. We have finished running mult(3, 0) and are now back to running mult(3, 1). The variable rest gets assigned the value 0.

What line is run next?
The line value = a + rest is run next. In this run of the function, a = 3 and rest = 0 so now value = 3.

What happens next?
The line return value is run. This returns 3 from the function. This also exits from the run of the function mult(3, 1). After return is called, we go back to running mult(3, 2).

Where were we in mult(3, 2)?
We had the variables a = 3 and b = 2 and were examining the line rest = mult(a, b - 1).

So what happens now?
The variable rest get 3 assigned to it. The next line value = a + rest sets value to 3 + 3 or 6.

So now what happens?
The next line runs, this returns 6 from the function. We are now back to running the line print "3 * 2 = ", mult(3, 2) which can now print out the 6.

What is happening overall?
Basically we used two facts to calculate the multiple of the two numbers. The first is that any number times 0 is 0 (x * 0 = 0). The second is that a number times another number is equal to the first number plus the first number times one less than the second number (x * y = x + x * (y - 1)). So what happens is 3 * 2 is first converted into 3 + 3 * 1. Then 3 * 1 is converted into 3 + 3 * 0. Then we know that any number times 0 is 0 so 3 * 0 is 0. Then we can calculate that 3 + 3 * 0 is 3 + 0 which is 3. Now we know what 3 * 1 is so we can calculate that 3 + 3 * 1 is 3 + 3 which is 6.

This is how the whole thing works:

3 * 2
3 + 3 * 1
3 + 3 + 3 * 0
3 + 3 + 0
3 + 3
6

Should you still have problems with this example, look at the process backwards. What is the last step that happens? We can easily make out that the result of mult(3, 0) is 0. Since b is 0, the function mult(3, 0) will return 0 and stop.

So what does the previous step do? mult(3, 1) does not return 0 because b is not 0. So the next lines are executed: rest = mult (a, b - 1), which is rest = mult (3, 0), which is 0 as we just worked out. So now the variable rest is set to 0.

The next line adds the value of rest to a, and since a is 3 and rest is 0, the result is 3.

Now we know that the function mult(3, 1) returns 3. But we want to know the result of mult(3,2). Therefore, we need to jump back to the start of the program and execute it one more round: mult(3, 2) sets rest to the result of mult(3, 1). We know from the last round that this result is 3. Then value calculates as a + rest, i. e. 3 + 3. Then the result of 3 * 2 is printed as 6.

The point of this example is that the function mult(a, b) starts itself inside itself. It does this until b reaches 0 and then calculates the result as explained above.

Recursion

Programming constructs of this kind are called recursive and probably the most intuitive definition of recursion is:


Recursion
If you still don't get it, see recursion.

These last two sections were recently written. If you have any comments, found any errors or think I need more/clearer explanations please email. I have been known in the past to make simple things incomprehensible. If the rest of the tutorial has made sense, but this section didn't, it is probably my fault and I would like to know. Thanks.

Contoh

faktorial.py

# mentakrif fungsi yang mengira faktorial

def faktorial(n):
    if n <= 1:
        return 1
    return n * faktorial(n - 1)

print "2! =", faktorial(2)
print "3! =", faktorial(3)
print "4! =", faktorial(4)
print "5! =", faktorial(5)

Output:

2! = 2
3! = 6
4! = 24
5! = 120

kira_detik.py

def kira_detik(n):
    print n
    if n > 0:
        return kira_detik(n-1)

kira_detik(5)

Output:

5
4
3
2
1
0

Ulasan fungsi_menarik.py

# Ulasan di bawah diberi nombor tingkat agar 
# penjelasan kod lebih terang. Sila baca mengikut tingakatan.
# (tingkat 1, contohnya, ada di bawah)


def mult(a, b): # (2.) Fungsi ini akan berulang kerana ...
    if b == 0:
        return 0
    baki = mult(a, b - 1) # (3.)...Apabila sampai ke SINI, jujukan bermula kembali dari atas! 
    value = a + baki
    return value # (4.) justeru, "return value" tidak akan berlaku
                 # sehingga tingkat 3 dilewati program.
print "3 * 2 = ", mult(3, 2) # (1.) Fungsi "mult" berasal di sini
                             

# Peristiwa "return value" di penghujung hanya boleh berlaku
# sebaik sahaja b sama dengan sifar (b mengurang dengan bilangan 1 setiap kali tingkat 3 berlaku).
# Dan hanya pada masa itu baharu perintah "print" dipaparkan.

# Lihatnya sebagai kesan "lompatan". Amnya apa yang anda perlu faham 
# adalah fungsi dimulakan semual 
# DALAM DIRINYA pada tingkat 3. Justeru, jujukan "melompat" 
# ke atas.

Ulasan faktorial.py

# Satu lagi contoh fungsi "lompatan":

def faktorial(n): # (2.) Fungsi ini akan MENGULANGI dirinya...
    if n <= 1:
        return 1
    return n * faktorial(n - 1) # (3.) Kerana ia MENGASAL semula di sini,
                                # dan pulang ke atas.
 
print "2! =", faktorial(2) # (1.) Fungsi "faktorial" berasal dengan baris ini
print "3! =", faktorial(3)
print "4! =", faktorial(4)
print "5! =", faktorial(5)

Ulasan kira_detik.py

# Satu lagi "lompatan", mudah dan ringkas:


def kira_detik(n): # (2.) Jujukan ini mengulangi dirinya...
    print n
    if n > 0:
        return kira_detik(n-1) # (3.) Kerana ia bermula SEMULA di sini, dan pergi ke atas

kira_detik(5) # (1.) Fungsi "kira_detik" berasal di sini