Sumber utama: https://ggc-discrete-math.github.io/functions.html#_injective_surjective_bijective_and_inverse_functions
# Python
# 1. Himpunan
## 1.1 Mendefinisikan Himpunan
Untuk mendefinisikan himpunan dalam Python, kita menuliskan elemen-elemen himpunan dalam tanda kurung kurawal dan memisahkan setiap elemen dengan tanda koma. Sebagai contoh, untuk menuliskan himpunan:
$$ A = \{1, 2, 3, 4, 5\} $$
pada kode Python, kita menuliskan:
```python
A = {1, 2, 3, 4, 5}
```
atau
```python
A = set([1, 2, 3, 4, 5])
```
Untuk mengetahui keanggotaan suatu himpunan kita dapat membentuk sebuah ekspresi menggunakan operator `in`. Sebagai contoh, misalkan kita ingin mengetahui apakah 8 adalah anggota himpunan $A$, atau $8 \in A$ kita menuliskan:
```
8 in A
```
Ekspresi di atas akan menghasilkan nilai Boolean `False`, karena 8 bukanlah elemen dari himpunan $A$.
#### Contoh 1. Mengetahui Keanggotaan Himpunan Menggunakan Python
Kode Python berikut memeriksa apakah 5 dan 0 adalah elemen dari himpunan $A = \{-2, 0, 1, 4\}$.
```python
A = {-2, 0, 1, 4}
print(5 in A)
print(0 in A)
```
Karena $5 \notin A$ dan $0 \in A$, maka kode di atas akan memberikan output:
```
False
True
```
#### Contoh 2. Menampilkan Semua Elemen-elemen dalam Sebuah Himpunan
Kode berikut menampilkan semua elemen-elemen dalam himpunan $A = \{-2, 0, 1, 4\}$.
```python
A = {-2, 0, 1, 4}
for x in A:
print(x, "adalah elemen dari himpunan.")
```
Output dari kode di atas:
```
0 adalah elemen dari himpunan.
1 adalah elemen dari himpunan.
4 adalah elemen dari himpunan.
-2 adalah elemen dari himpunan.
```
#### Contoh 3. Menuliskan Notasi Set Builder dalam Python
Kode berikut mendefinisikan himpunan $B = \{x^2 \ | \ x \in \{1, 2, 3, 4, 5\}\}$ menggunakan set builder dan menampilkan semua elemen dari himpunan tersebut.
```python
B = {x**2 for x in {1, 2, 3, 4, 5}}
for y in B:
print(y, "adalah elemen dari himpunan.")
```
## 1.2 Operasi pada Himpunan
#### Contoh 1. Union
Kita dapat menuliskan operasi union dalam Python dengan dua cara. Misalkan, operasi $A \cup B$, dapat dituliskan dengan dua cara berikut:
```python
A.union(B)
```
atau
```python
A | B
```
Kode berikut mencontohkan operasi union pada himpunan $A$ dan $B$:
```python
A = {-3, -1, 2, 5}
B = {-1, 0, 2}
print(A.union(B))
print(A | B)
```
Kode di atas akan memberikan output:
```
{0, 2, 5, -3, -1}
{0, 2, 5, -3, -1}
```
#### Contoh 2. Intersection (Irisan)
Intersection dari himpunan $A$ dan $B$ dinotasikan dengan $A \cap B$ dalam Python dituliskan dengan dua cara:
```python
A.intersection(B)
```
atau
```python
A & B
```
Kode berikut mencontohkan operasi irisan pada himpunan $A$ dan $B$:
```python
A = {-3, -1, 2, 5}
B = {-1, 0, 2}
print(A.intersection(B))
print(A & B)
```
Kode di atas akan memberikan output:
```
{2, -1}
{2, -1}
```
#### Contoh 3. Selisih
Selisih dari himpunan $A$ dan $B$, dinotasikan dengan $A - B$ dalam Python dituliskan dengan dua cara:
```python
A.difference(B)
```
atau
```python
A - B
```
Kode berikut mencontohkan operasi selisih pada himpunan $A$ dan $B$:
```python
A = {-3, -1, 2, 5}
B = {-1, 0, 2}
print(A.difference(B))
print(B - A)
```
Kode di atas akan memberikan output:
```
{-3, 5}
{0}
```
#### Contoh 4. Komplemen
Komplemen dari suatu himpunan dalam Python dapat dicari dengan mencari selisih himpunan semesta dengan himpunan tersebut. Misalkan $S = \{1, 2, 3, 4, 5, 6, 7, 8, 9\}$ dan $A = \{1, 3, 7, 9\}$, kode berikut mencari $A^c$:
```python
S = {1, 2, 3, 4, 5, 6, 7, 8, 9}
A = {1, 3, 7, 9}
print(S - A)
```
Output dari kode di atas:
```python
{2, 4, 5, 6, 8}
```
:::info
**Operasi himpunan**
```python
def main():
# Inisialisasi variabel
Alist = []
Blist = []
# Input banyaknya elemen himpunan A
ulangA = int(input("Masukkan banyaknya Elemen A: "))
for i in range(ulangA): #bentuk for menggenarasi integer mulai dari 0
#karena list indexnya mulai dari 0 maka variabel ulang akan mengalami pertambahan 1 agar index pada list yang ada bertambah 1
A = int(input(f"Elemen ke -{i+1}: "))
if A != 0:
Alist.append(A)
else:
break
set_A = set(Alist) #merubah tipe data list menjadi set
print("Himpunan A = ",set_A)
print()
# Input banyaknya elemen himpunan B
ulangB = int(input("Masukkan banyaknya Elemen B: "))
for j in range(ulangB): #bentuk for menggenarasi integer mulai dari 0
#karena list indexnya mulai dari 0 maka variabel ulang akan mengalami pertambahan 1 agar index pada list yang ada bertambah 1
B = int(input(f"Elemen ke -{j+1}: "))
if B != 0:
Blist.append(B)
else:
break
set_B = set(Blist)
print("Himpunan B = ",set_B)
# Gabungan (Union)
print()
gabungan = set_A | set_B
if gabungan == set():
print("Operasi gabungan A | B = {}")
else:
print("Operasi gabungan A | B = ",gabungan)
# Irisan (Intersection)
irisan = set_A & set_B
if irisan == set():
print("Operasi irisan A & B = {}")
else:
print("Operasi irisan A & B = ",irisan)
# Operasi Selisih (difference)
selisih = set_A - set_B
if selisih == set():
print("Operasi selisih A - B = {}")
else:
print("Operasi selisih A - B = ",selisih)
main()
````
Output
```
Masukkan banyaknya Elemen A: 2
Elemen ke -1: 1
Elemen ke -2: 2
Himpunan A = {1, 2}
Masukkan banyaknya Elemen B: 4
Elemen ke -1: 1
Elemen ke -2: 2
Elemen ke -3: 4
Elemen ke -4: 5
Himpunan B = {1, 2, 4, 5}
Operasi gabungan A | B = {1, 2, 4, 5}
Operasi irisan A & B = {1, 2}
Operasi selisih A - B = {}
```
**Kartesian Product**
Kode dibawah ini digunakan untuk mencari produk kartesius dari himpunan P = {1, 3, 5} dan Q = {2, 4, 6}
```python
# Python program to get Cartesian
# product of huge dataset
# Import the library Pandas
import pandas as pd
# Obtaining the dataset 1
data1 = pd.DataFrame({'P': [1,3,5]})
# Obtaining the dataset 2
data2 = pd.DataFrame({'Q': [2,4,6]})
# Doing cartesian product of datasets 1 and 2
data3 = pd.merge(data1.assign(key=1), data2.assign(key=1),
on='key').drop('key', axis=1)
# Printing the cartesian product of both datasets
print(data3)
```
OUTPUT
```
P Q
0 1 2
1 1 4
2 1 6
3 3 2
4 3 4
5 3 6
6 5 2
7 5 4
8 5 6
```
sumber: https://www.geeksforgeeks.org/how-to-get-a-cartesian-product-of-a-huge-dataset-using-pandas-in-python/
:::
# Relasi
Kode Python berikut adalah module (disimpan dalam file bernama sifat_relasi.py) yang berisikan fungsi-fungsi untuk menguji sifat-sifat relasi.
***sifat_relasi.py***
```python
"""
Sifat-sifat Relasi
"""
def is_reflexive(R, A):
"""Mengembalikan True jika relasi R pada himpunan A adalah reflektif, False sebaliknya."""
for a in A:
if (a, a) not in R:
return False
return True
def is_symmetric(R, A):
"""Mengembalikan True jika relasi R pada himpunan A adalah simetris, False sebaliknya."""
for a, b in R:
if (b, a) not in R:
return False
return True
def is_transitive(R, A):
"""Mengembalikan True jika relasi R pada himpunan A adalah transitif, False sebaliknya."""
for a in A:
for b in A:
if (a, b) in R:
for c in A:
if (b, c) in R and (a, c) not in R:
return False
return True
```
Misalkan untuk
```
if __name__ == "__main__":
# see Example 7 on Page 576
A = set([1, 2, 3, 4])
R1 = [(1, 1), (1, 2), (2, 1), (2, 2), (3, 4), (4, 1), (4, 4)]
R2 = [(1, 1), (1, 2), (2, 1)]
R3 = [(1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (3, 3), (4, 1), (4, 4)]
R4 = [(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
R5 = [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
R6 = [(3, 4)]
for R in [R1, R2, R3, R4, R5, R6]:
print R
print " reflexive: ", reflexive(R, A)
print " symmetric: ", symmetric(R, A)
print " transitive:", transitive(R, A)
```
:::info
Akan menghasilkan output
```
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 4), (4, 1), (4, 4)]
reflexive: False
symmetric: False
transitive: False
[(1, 1), (1, 2), (2, 1)]
reflexive: False
symmetric: True
transitive: False
[(1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (3, 3), (4, 1), (4, 4)]
reflexive: True
symmetric: True
transitive: False
[(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
reflexive: False
symmetric: False
transitive: True
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
reflexive: True
symmetric: False
transitive: True
[(3, 4)]
reflexive: False
symmetric: False
transitive: True
```

https://w3.cs.jmu.edu/mayfiecs/cs228/python/
:::info
**Mencari Domain, Range, Invers**
1. Misalkan A = {1, 2, 3, 4, 5, 6, 7}, B = {4, 5, 6, 7, 8, 9} dan relasi R dari A ke B diberikan oleh R = {(1,5),(4,5),(1,4),(4,6),(3,7),(7,6)} carilah: Domain, Range, dan Invers dari R
```python
#Pendefinisian himpunan A,B,R serta variabel Domain, Range dan Invers berupa list
A = [1, 2, 3, 4, 5, 6, 7]
B = [4, 5, 6, 7, 8, 9]
R = [[1,5],[4,5],[1,4],[4,6],[3,7],[7,6]]
Domain = []
Range = []
Invers = []
#Domain
for i in range(len(R)):
hasil = R[i][0]
Domain.append(hasil)
#fromkeys()Returns a dictionary with the specified keys and value
Domain = list(dict.fromkeys(Domain))
print("Domain = ",sorted(Domain))
#Range
for j in range(len(R)):
hasil1 = A[j]
for i in range(len(B)):
hasil2 = B[i]
if hasil1 == hasil2:
Range.append(hasil1)
print("Range = ",Range)
#Invers
for i in range(len(R)):
hasil3 = R[i][0]
R[i][0] = R[i][1]
R[i][1] = hasil3
Invers.append(R[i])
print("Invers= ",Invers)
```
OUTPUT
```
Domain = [1, 3, 4, 7]
Range = [4, 5, 6]
Invers= [[5, 1], [5, 4], [4, 1], [6, 4], [7, 3], [6, 7]]
```
**Membuat himpunan pasangan terurut**
2. Suatu relasi R dari himpunan A ={1, 2, 3, 4} ke himpunan B = {1, 3, 5}, yang didefinisikan oleh "x lebih kecil dari y"
- Tulis R sebagai himpunan pasangan terurut
- Tentukan relasi invers dari R
```python
#Pendefinisian himpunan A dan B serta variabel R,Invers berupa list
A = [1, 2, 3, 4]
B = [1, 3, 5]
R = []
Invers = []
#Iterasi melalui angka (yang dapat digunakan untuk akses indeks A)
for i in range(len(A)):
#Iterasi melalui angka (yang dapat digunakan untuk akses indeks B)
for j in range(len(B)):
#Relasi x (anggota A) lebih kecil dari y (anggota B)
if A[i] < B[j]:
#Pembentuk relasi pasangan terurut
hasil4 = [A[i],B[j]]
R.append(hasil4)
print("R = ",R)
#Relasi Invers dari R
for i in range(len(R)):
hasil3 = R[i][0]
R[i][0] = R[i][1]
R[i][1] = hasil3
Invers.append(R[i])
print("Invers = ",Invers)
```
OUTPUT
```
R = [[1, 3], [1, 5], [2, 3], [2, 5], [3, 5], [4, 5]]
Invers = [[3, 1], [5, 1], [3, 2], [5, 2], [5, 3], [5, 4]]
```
3. Suatu relasi R yang didefinisikan sebagai "x habis membagi y" dari himpunan C ={2, 3, 4, 5} ke himpunan D = {3, 6, 7, 10}
- Tentukan R sebagai himpunan pasangan terurut
- Tentukan relasi invers dari R
```python
#Pendefinisian himpunan C dan D serta variabel R,Invers berupa list
C = [2, 3, 4, 5]
D = [3, 6, 7, 10]
R = []
Invers =[]
#Iterasi melalui angka (yang dapat digunakan untuk akses indeks C)
for i in range(len(C)):
#Iterasi melalui angka (yang dapat digunakan untuk akses indeks D)
for j in range(len(D)):
#Menentukan R sebagai himpunan pasangan terurut
if D[i] % C[j] == 0:
hasil5 = [C[i],D[j]]
R.append(hasil5)
print("R = ",R)
#Invers
for i in range(len(R)):
hasil6 = R[i][0]
R[i][0] = R[i][1]
R[i][1] = hasil6
Invers.append(R[i])
print("Invers = ",Invers)
```
OUTPUT
```
R = [[2, 6], [3, 3], [3, 6], [5, 3], [5, 10]]
Invers = [[6, 2], [3, 3], [6, 3], [3, 5], [10, 5]]
```
Sumber = https://www.youtube.com/watch?v=wk-oxGzqxSQ
:::
# Fungsi
Kita perlu mendownload module `sympy`,`numpy`.
Pertama install `pip` terlebih dahulu:
1. Download `get-pip.py` pada https://bootstrap.pypa.io/get-pip.py

2. Pada command prompt pindah ke directory tempat `get-pip.py` disimpan (dalam contoh ini kita menyimpannya pada folder Downloads)
3. Pada windows, klik Start dan ketikkan "Manage App Execution Aliases", klik icon tersebut dan matikan Python.

4. Tutup command prompt.
5. Ketikkan `pip install sympy numpy` pada command prompt.
:::info
Terdapat beberapa library yang kita butuhkan untuk program fungsi pada Python. Maka kita perlu mendownload module `sympy`,`numpy`. `sympy` merupakan python library untuk symbolic mathematics, `numpy` adalah library python yang digunakan untuk bekerja dengan array dan juga memiliki fungsi yang bekerja dalam domain aljabar linier, transformasi fourier, dan matriks.
Jika sudah mengikuti langkah-langkah pada video tutorial install dan konfigurasi Python3.10 selanjutnya lakukan install untuk library `numpy`
1. Pertama buka folder Python3.10 :

2. Pada *Address bar* ketikan cmd untuk membuka jendela command prompt


3. Selanjutnya, ketikan `pip install sympy numpy` pada jendela command prompt untuk menginstall library `simpy` dan `numpy`.

### Mencari domain, range dari suatu fungsi
#### Contoh 1. Mencari domain, range
Diketahui Himpunan A = {1, 2, 3, 4, 5, 6, 7} dan B = {4, 5, 6, 7, 8, 9, 10}, membentuk suatu relasi fungsi dengan F = {(1,4), (2,5), (3,6), (4,7), (5,8), (6,9), (7,10)}, carilah domain dan range dari relasi fungsi F tersebut
```python
#Pendefinisian himpunan A,B,F serta variabel Domain, Range dan Invers berupa list
A = [1, 2, 3, 4, 5, 6, 7]
B = [4, 5, 6, 7, 8, 9, 10]
F = [[1,4],[2,5],[3,6],[4,7],[5,8],[6,9],[7,10]]
Domain = []
Range = []
#Domain
for i in range(len(F)):
hasil = F[i][0]
Domain.append(hasil)
#fromkeys()Returns a dictionary with the specified keys and value
Domain = list(dict.fromkeys(Domain))
#Mencetak Domain dengan mengganti tipedata menjadi set
print("Domain = ",set(Domain))
#Range
for j in range(len(F)):
hasil1 = A[j]
for i in range(len(B)):
hasil2 = B[i]
Range.append(hasil2)
#Mencetak Range dengan mengganti tipedata menjadi set
print("Range = ",set(Range))
```
OUTPUT
```
Domain = {1, 2, 3, 4, 5, 6, 7}
Range = {4, 5, 6, 7}
```
### Membuat Grafik fungsi dengan python
#### Contoh 2.Membuat grafik fungsi y = 2x+1
1. Grafik fungsi 2x+1 dimana x={-5,0,1,2,3,4,5}
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5,5,100)
y = x*2+1
plt.plot(x,y)
plt.xlabel('koordinat x')
plt.ylabel('koordinat y')
plt.title("diagram 2x-5")
plt.show()
```
Penjelasan program
* Baris 1 Import library `numpy` untuk membuat data imaginer dan menamakan ulang dengan `np`
* Baris 2 mengimport fungsi `pyplot` yang berada dalam module library `matplotlib.pyplot` dan menamakan ulang fungsi tersebut sebagai `plt` digunakan untuk impor fungsi pyplot
* Baris 4 membuat data imaginer yang dibentuk menggunakan `np.linspace()` digunakan untuk membuat array dengan nilai dalam interval.
* Baris 5 mendefinisikan nilai "y" dimana "y" adalah 2x+1
* Baris 7 untuk memvisualisasikan datanya dengan fungsi `Plt.plot`
* Baris 8 memberikan keterangan pada visualisasi diagram untuk koordinat x
* Baris 9 memberikan keterangan pada visualisasi diagram untuk koordinat y
* Baris 10 memberikan keterangan pada visualisasi judul diagram
* Baris 11 menampilkan diagram pada data yang divisualisasikan.
OUTPUT

#### Contoh 3. Membuat grafik fungsi $y = x^2 - 5$
2. Misal carilah grafik fungsi dari $f(x)=x^2-5$ dimana x={-5,0,1,2,3,4,5}
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5,5,100)
y = x**2-5
plt.plot(x,y)
plt.xlabel('koordinat x')
plt.ylabel('koordinat y')
plt.title("diagram x^2-5")
plt.show()
```
Penjelasan program
* Baris 1 Import library `numpy` untuk membuat data imaginer dan menamakan ulang dengan `np`
* Baris 2 mengimport fungsi `pyplot` yang berada dalam module library `matplotlib.pyplot` dan menamakan ulang fungsi tersebut sebagai `plt` digunakan untuk impor fungsi pyplot
* Baris 4 membuat data imaginer yang dibentuk menggunakan `np.linspace()` digunakan untuk membuat array dengan nilai dalam interval.
* Baris 5 mendefinisikan nilai "y" dimana "y" adalah x pangkat 2 dikurangi 5
* Baris 7 untuk memvisualisasikan datanya dengan fungsi `Plt.plot`
* Baris 8 memberikan keterangan pada visualisasi diagram untuk koordinat x
* Baris 9 memberikan keterangan pada visualisasi diagram untuk koordinat y
* Baris 10 memberikan keterangan pada visualisasi judul diagram
* Baris 11 menampilkan diagram pada data yang divisualisasikan.
OUTPUT

#### Contoh 4. Membuat grafik fungsi $y=x^2$
2. Grafik fungsi $y = x^2$ dimana x={2, 3, 4, 5, 6, 7, 8, 9, 10}
```python=
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(2,10,10)
y = x**2
plt.plot(x,y)
plt.xlabel('ini koordinat x')
plt.ylabel('ini koordinat y')
plt.title("diagram x^2")
plt.show()
```
Penjelasan program
* Baris 1 Import library `numpy` untuk membuat data imaginer dan menamakan ulang dengan `np`
* Baris 2 mengimport fungsi `pyplot` yang berada dalam module library `matplotlib.pyplot` dan menamakan ulang fungsi tersebut sebagai `plt` digunakan untuk impor fungsi pyplot
* Baris 4 membuat data imaginer yang dibentuk menggunakan `np.linspace()` digunakan untuk membuat array dengan nilai dalam interval.
* Baris 5 mendefinisikan nilai "y" dimana "y" adalah pangkat 2 dari X
* Baris 7 untuk memvisualisasikan datanya dengan fungsi `Plt.plot`
* Baris 8 memberikan keterangan pada visualisasi diagram untuk koordinat x
* Baris 9 memberikan keterangan pada visualisasi diagram untuk koordinat y
* Baris 10 memberikan keterangan pada visualisasi judul diagram
* Baris 11 menampilkan diagram pada data yang divisualisasikan.
**OUTPUT**

sumber = https://alvinburhani.wordpress.com/2020/10/06/membuat-grafik-fungsi-dengan-python/
https://www.dqlab.id/belajar-python-untuk-hasilkan-visualisasi-data
:::
## Product Fungsi
#### Contoh 5. Produk Fungsi
Kode berikut mencontohkan hasil kali fungsi $f \circ g$ dan $g \circ f$ dimana $f(x) = x^2$ dan $g(x) = x + 3$.
```python=
import sympy
x = sympy.symbols('x')
f = x**2
g = x + 3
print(sympy.compose(f,g)) // Memberikan output f(g(x))
print(sympy.compose(g,f)) // Memberikan output g(f(x))
```
Output dari kode di atas:
```
x**2 + 6*x + 9
x**2 + 3
```
Penjelasan kode:
- Baris 1 mengimpor module `sympy`
- Baris 3 menyatakan bahwa `'x'` adalah simbol yang ditugaskan ke variabel `x`
- Baris 4 mendefinisikan `f` adalah fungsi $x^2$
- Baris 5 mendefinisikan `g` adalah fungsi $x + 3$
- Baris 6 mencetak hasil $f \circ g$
- Baris 7 mencetak hasil $g \circ f$
## Fungsi Invers
#### Contoh 6. Fungsi Invers
Kode berikut mencari fungsi invers dari $f(x) = 2x + 6$.
```python
import sympy
x, y = sympy.symbols('x y')
print(sympy.solve(2*x + 6 - y))
```
Output:
```
[{x: y/2 - 3}]
```
#### Contoh 7. Fungsi Invers dengan `Eq` dan `solve`
Selain menggunakan
```python
print(sympy.solve(sympy.Eq(y, (4*x - 7)/(7*x + 3)), x))
[(-3*y - 7)/(7*y - 4)]
```
:::info
#### Fungsi floor() dan ceil() pada python
Program dibawah ini mencari bilangan bulat dari 1.4
#### Contoh 9. Mencari bilangan bulat dengan floor()
```python
#Import library matematika
import math
#Bulatkan angka ke bawah ke bilangan bulat terdekat
y = math.floor(1.4)
print(y)
```
OUTPUT
```
1
```
#### Contoh 8. Mencari bilangan bulat dengan ceil()
```python
#Import library matematika
import math
#Bulatkan angka ke atas ke bilangan bulat terdekat
x = math.ceil(1.4)
print(x)
```
OUTPUT
```
2
```
sumber = https://dosenit.com/python/fungsi-matematika-di-python
### Fungsi Faktorial
#### Contoh 10. Mencari nilai faktorial
program dibawah ini mencari nilai faktorial dari 6!
```python
# Mendefinisikan fungsi
def hitungFaktorial(n):
if n == 1:
return 1
else:
return n * hitungFaktorial(n-1)
# Mencari Faktorial 2
print(hitungFaktorial(6))
```
output
```
720
```
:::
# Proposisi
#### Negasi
Untuk menadapatkan negasi, kita menggunakan operator `not`.
```python
p = True
print(not p)
```
Kode berikut mencetak tabel kebenaran untuk operasi negasi:
```python
print('p a')
for p in [True, False]:
a = not p
print(p, a)
```
:::info
#### Conjunction
Untuk mencari konjungsi pada python, kita menggunakan operator `and`.Kode berikut mencetak tabel kebenaran untuk operasi konjungsi
```python
def conjunction(p, q):
return p and q
print("p q p^q")
for p in [True, False]:
for q in [True, False]:
a = conjunction(p, q)
print(p, q, a)
```
OUTPUT
```
p q p^q
True True True
True False False
False True False
False False False
```
#### Disjungsi
Untuk mencari disjungsi pada python, kita menggunakan operator `or`.Kode berikut mencetak tabel kebenaran untuk operasi disjungsi
```python
def disjunction(p, q):
return p or q
print("p q pvq")
for p in [True, False]:
for q in [True, False]:
a = disjunction(p, q)
print(p, q, a)
```
OUTPUT
```
p q pvq
True True True
True False True
False True True
False False False
```
#### Implikasi
Banyak pernyataan, khususnya dalam matematika, berbentuk "jika p maka q".Pernyataan demikian disebut statemen kondisional yang dinyatakan dengan tanda "→"
Untuk mencari implikasi pada python, kita menggunakan operator `=>` atau `not(p) or q` .Kode berikut mencetak tabel kebenaran untuk operasi implikasi
```python
def implication(p, q):
return not(p) or q
print("p q p→q")
for p in [True, False]:
for q in [True, False]:
a = implication(p, q)
print(p, q, a)
```
OUTPUT
```
p q p→q
True True True
True False False
False True True
False False True
```
#### Biimplikasi
Bentuk proposisi: “p jika dan hanya jika q”. Aturan Bikondisional Semantik: sebuah Bikondisional bernilai benar jika dan hanya jika pernyataan pada kedua komponen di kedua sisinya bernilai benar atau dikedua sisinya bernilai salah. Notasi/tanda“↔”. Bikondisional, secara logik sama dengan sebuah konjungsi dari dua proposisi kondisi.
Untuk mencari bimplikasi pada python, kita menggunakan `(p and q) or not(p or q)` .Kode berikut mencetak tabel kebenaran untuk operasi biimplikasi
```python
def bi_implication(p, q):
return (p and q) or not(p or q)
print("p q p↔q")
for p in [True, False]:
for q in [True, False]:
a = bi_implication(p, q)
print(p, q, a)
```
OUTPUT
```
p q p↔q
True True True
True False False
False True False
False False True
```
**Membuat Tabel kebenaran**
Contoh: Buatlah tabel kebenaran dari $p \land \neg p$
1. Ketikan program berikut dan simpan dengan nama logic.py
```python
# quantifier: "there exists a unique ..."
# e.g. exactly_one( n*n == 9 for n in range(1,10) ) is True
def exactly_one(S):
return len([ s for s in S if s ]) == 1
#
def in_order(L):
return all( L[i] <= L[i+1] for i in range(0, len(L)-1) )
#
def set_to_predicate(S):
return lambda x: x in S
#
def truth_table_rows(variables):
if len(variables) == 0:
return [dict()]
variables = list(variables)
P = variables[0]
R = truth_table_rows(variables[1:])
add_P = lambda v: [ dict([(P,v)] + list(r.items())) for r in R ]
return add_P(True) + add_P(False)
#
def vars(*var_names):
return ( Variable(name) for name in var_names )
#
def cast_to_proposition(p):
if isinstance(p, Proposition):
return p
elif isinstance(p, str):
return Variable(p)
elif isinstance(p, bool):
return Constant(p)
else:
raise ValueError()
#
class Proposition:
symbol = ''
empty_str = ''
def __init__(self, *children):
self.children = [ cast_to_proposition(c) for c in children ]
def __str__(self):
if len(self.children) == 0: return self.empty_str
return self.symbol.join( c.child_str() for c in self.children )
def evaluate(self, **assignments):
raise NotImplementedError()
def variables(self):
if len(self.children) == 0:
return frozenset()
else:
return frozenset.union(*[ c.variables() for c in self.children ])
def __repr__(self):
return 'Proposition( {0} )'.format(self)
def child_str(self):
return ('{0}' if isinstance(self, (Constant,Variable,Not)) else '({0})').format(self)
def print_truth_table(self):
vars = sorted( self.variables() )
rows = truth_table_rows(vars)
formula_header = str(self)
formula_len = max(5,len(formula_header))
header = '{0} # {1: ^{2}}'.format(' '.join('{0: ^5}'.format(v) for v in vars), formula_header, formula_len)
print(header)
print('#'*len(header))
for r in rows:
var_cols = ' '.join('{0: ^{1}}'.format(str(r[v]), max(5,len(v))) for v in vars)
result_col = '{0: ^{1}}'.format(str(self.evaluate(**r)), formula_len)
print('{0} # {1}'.format(var_cols, result_col))
print()
def to_tree(self):
from trees import ListTree
result = ListTree(value=str(self))
for c in self.children:
result.add_child_node(c.to_tree())
return result
def __and__(self,other):
v = self.children if isinstance(self,And) else [self]
w = other.children if isinstance(other,And) else [other]
return And(*(v+w))
def __rand__(self,other):
return cast_to_proposition(other) & self
def __or__(self,other):
v = self.children if isinstance(self,Or) else [self]
w = other.children if isinstance(other,Or) else [other]
return Or(*(v+w))
def __ror__(self,other):
return cast_to_proposition(other) | self
def __invert__(self):
return Not(self)
def __rshift__(self,other):
return Implies(self,other)
def __rrshift__(self,other):
return Implies(other,self)
def __lshift__(self,other):
return ImpliedBy(self,other)
def __rlshift__(self,other):
return ImpliedBy(other,self)
def disjunction(self,other):
return self | other
def conjunction(self,other):
return self & other
def negation(self):
return ~self
def implies(self,other):
return self >> other
def impliedby(self,other):
return self << other
def iff(self,other):
return Iff(self,other)
def is_tautology(self):
return all( self.evaluate(**r) for r in truth_table_rows(self.variables()) )
def is_contradiction(self):
return all( not self.evaluate(**r) for r in truth_table_rows(self.variables()) )
def is_contingency(self):
return not self.is_tautology() and not self.is_contradiction()
def __eq__(self,other):
return self.is_equivalent(other)
def is_equivalent(self,other):
other = cast_to_proposition(other)
return all( self.evaluate(**r) == other.evaluate(**r) for r in truth_table_rows(self.variables() | other.variables()) )
def is_identical(self,other):
return self.__class__ == other.__class__ \
and len(self.children) == len(other.children) \
and all( c.is_identical(d) for (c,d) in zip(self.children,other.children) )
def substitute(self, e1, e2):
if self.is_identical(e1):
return e2
else:
return self.__class__( *[c.substitute(e1,e2) for c in self.children] )
#
class Constant(Proposition):
def __init__(self,value):
self.children = []
self.value = bool(value)
def substitute(self, e1, e2):
return Constant(self.value)
def __str__(self):
return str(self.value)
def evaluate(self, **assignments):
return self.value
def is_identical(self,other):
return isinstance(other, Constant) and self.value == other.value
#
class Variable(Proposition):
def __init__(self,name):
self.children = []
self.name = name
def substitute(self, e1, e2):
if self.is_identical(e1):
return e2
else:
return Variable(self.name)
def variables(self):
return frozenset({ self.name })
def __str__(self):
return self.name
def evaluate(self, **assignments):
return assignments[self.name]
def is_identical(self,other):
return isinstance(other, Variable) and self.name == other.name
#
class Not(Proposition):
def __init__(self,child):
Proposition.__init__(self,child)
def __str__(self):
return u'¬{0}'.format(self.children[0].child_str())
def evaluate(self, **assignments):
return not self.children[0].evaluate(**assignments)
#
class And(Proposition):
symbol = ' ^ '
empty_str = 'True'
def evaluate(self, **assignments):
return all( child.evaluate(**assignments) for child in self.children )
#
class Or(Proposition):
symbol = ' v '
empty_str = 'False'
def evaluate(self, **assignments):
return any( child.evaluate(**assignments) for child in self.children )
#
class Implies(Proposition):
symbol = ' => '
def __init__(self,child1,child2):
Proposition.__init__(self,child1,child2)
def evaluate(self, **assignments):
if self.children[0].evaluate(**assignments):
return self.children[1].evaluate(**assignments)
else:
return True
#
class ImpliedBy(Proposition):
symbol = ' <= '
def __init__(self,child1,child2):
Proposition.__init__(self,child1,child2)
def evaluate(self, **assignments):
if self.children[1].evaluate(**assignments):
return self.children[0].evaluate(**assignments)
else:
return True
#
class Iff(Proposition):
symbol = ' <=> '
def __init__(self,child1,child2):
Proposition.__init__(self,child1,child2)
def evaluate(self, **assignments):
return self.children[0].evaluate(**assignments) == self.children[1].evaluate(**assignments)
#
class ArgumentForm:
def __init__(self, *premises, conclusion):
self.premises = [ cast_to_proposition(c) for c in premises ]
self.conclusion = cast_to_proposition(conclusion)
def variables(self):
return frozenset.union(self.conclusion.variables(), *[ c.variables() for c in self.premises ])
def __repr__(self):
return 'ArgumentForm( {0} )'.format(self)
def __str__(self):
return ((', '.join(str(c) for c in self.premises) + ', ') if self.premises else '') + 'conclusion = ' + str(self.conclusion)
def print_truth_table(self):
vars = sorted( self.variables() )
rows = truth_table_rows(vars)
var_strings = [ '{0: ^5}'.format(v) for v in vars ]
premise_strings = [ '{0: ^6}'.format(str(c)) for c in self.premises ]
conclusion_string = '{0: ^10}'.format(str(self.conclusion))
vars_header = ' '.join(var_strings)
premises_header = '{0: ^8}'.format(' '.join(premise_strings))
print('{0} # {1: ^{2}} # {3: ^{4}}'.format(' '*len(vars_header), 'premises', len(premises_header), 'conclusion', len(conclusion_string)))
header = '{0} # {1: ^8} # {2}'.format(vars_header, premises_header, conclusion_string)
print(header)
print('#'*len(header))
for r in rows:
premise_values = [ c.evaluate(**r) for c in self.premises ]
conclusion_value = self.conclusion.evaluate(**r)
star = '*' if all( v for v in premise_values ) else ''
var_cols = ' '.join( '{0: ^{1}}'.format(str(r[v]), len(k)) for (k,v) in zip(var_strings, vars) )
premise_cols = ' '.join( '{0: ^{1}}'.format(str(v)+star, len(k)) for (k,v) in zip(premise_strings, premise_values) )
conclusion_col = '{0: ^{1}}'.format(str(conclusion_value)+star, len(conclusion_string))
print('{0} # {1: ^8} # {2}'.format(var_cols, premise_cols, conclusion_col))
print()
def is_valid(self):
vars = (frozenset.union(*[ c.variables() for c in self.premises ]) if self.premises else frozenset()) | self.conclusion.variables()
return all( self.conclusion.evaluate(**r) for r in truth_table_rows(vars) if all( c.evaluate(**r) for c in self.premises ) )
def substitute(self, e1, e2):
return ArgumentForm( *[ c.substitute(e1,e2) for c in self.premises ], conclusion = self.conclusion.substitute(e1,e2) )
#
```
2. Selanjutnya jalankan program tersebut,pada jendela console ketikan program dibawah ini
```python=
from Logic import *
P, Q, R, S, T = vars('P','Q','R','S','T')
P,Q #(Proposition( P ), Proposition( Q ))
(P & ~P).print_truth_table()
```

Penjelasan:
1. Baris 1 digunakan untuk import module logic yang sebelumnya sudah dibuat.
2. Baris 2, mendefinisikan variabel P,Q,R,S,T
3. Baris 3, untuk memeriksa apakah variabel sudah terdefinisi atau belum
4. Baris 4, mencetak tabel kebenaran dari $p \land \neg p$ dengan method.
```(P & ~P).print_truth_table()```
Sumber:
1. https://bitbucket.org/Andrew-Kay/dcaa/src/master/logic.py
2. https://www.youtube.com/watch?v=fW-9YLHBH3E&t=229s
:::
#### Tambahan
```python
"""
formula.py - propositional formulas for Python
by Robin Wellner
Hereby, I waive all rights to this library, as described at <http://creativecommons.org/publicdomain/zero/1.0/>
Examples:
foo = Atom('foo')
bar = Atom('bar')
disjuction = foo | bar
conjunction = foo & bar
implication = foo >> bar
if_and_only_if = foo << bar
inverse = ~foo
simple_tautology = foo | ~foo
simple_negative_tautology = foo & ~foo
#Valuation:
#Formula.v(true_set)
print(simple_tautology.v({foo}) # prints True
print(negative_tautology.v({foo}) # prints True
print(inverse.v({bar}) # prints True
#Tautology checking:
#Formula.t()
#returns a set of atoms which cause Formula.v to return False (a counterexample)
#or None if the formula is a tautology
print(simple_tautology.t()) # prints None
print(implication.t()) # prints {foo}
"""
class Formula:
# Objek formula adalah objek yang operasi logikanya masuk akal
def __invert__(self):
# Overloading untuk ~
return Not(self)
def __and__(self, other):
# Overloading untuk operator &
return And(self, other)
def __or__(self, other):
# Overloading untuk operator |
return Or(self, other)
def __rshift__(self, other):
# Overloading untuk operator >>
return Implies(self, other)
def __lshift__(self, other):
# Overloading untuk operator <<
return Iff(self, other)
def __eq__(self, other):
# Equal
return self.__class__ == other.__class__ and self.eq(other)
def v(self, v):
# Valuasi
raise NotImplementedError("Plain formula can not be valuated")
def _t(self, left, right):
while True:
found = True
for item in left:
if item in right:
return None
if not isinstance(item, Atom):
left.remove(item)
tup = item._tleft(left, right)
left, right = tup[0]
if len(tup) > 1:
v = self._t(*tup[1])
if v is not None:
return v
found = False
break
for item in right:
if item in left:
return None
if not isinstance(item, Atom):
right.remove(item)
tup = item._tright(left, right)
left, right = tup[0]
if len(tup) > 1:
v = self._t(*tup[1])
if v is not None:
return v
found = False
break
if found:
return set(left)
def t(self):
return self._t([], [self])
# Binary operators
class BinOp(Formula):
def __init__(self, lchild, rchild):
self.lchild = lchild
self.rchild = rchild
def __str__(self):
return '(' + str(self.lchild) + ' ' + self.op+ ' ' + str(self.rchild) + ')'
def eq(self, other):
return self.lchild == other.lchild and self.rchild == other.rchild
# Logika And Function
class And(BinOp):
op = '∧'
def v(self, v):
return self.lchild.v(v) and self.rchild.v(v)
def _tleft(self, left, right):
return (left + [self.lchild, self.rchild], right),
def _tright(self, left, right):
return (left, right + [self.lchild]), (left, right + [self.rchild])
# Logika Or Function
class Or(BinOp):
op = '∨'
def v(self, v):
return self.lchild.v(v) or self.rchild.v(v)
def _tleft(self, left, right):
return (left + [self.lchild], right), (left + [self.rchild], right)
def _tright(self, left, right):
return (left, right + [self.lchild, self.rchild]),
# Logika implikasi
class Implies(BinOp):
op = '→'
def v(self, v):
return not self.lchild.v(v) or self.rchild.v(v)
def _tleft(self, left, right):
return (left + [self.rchild], right), (left, right + [self.lchild])
def _tright(self, left, right):
return (left + [self.lchild], right + [self.rchild]),
# Logika bi-implikasi
class Iff(BinOp):
op = '↔'
def v(self, v):
return self.lchild.v(v) is self.rchild.v(v)
def _tleft(self, left, right):
return (left + [self.lchild, self.rchild], right), (left, right + [self.lchild, self.rchild])
def _tright(self, left, right):
return (left + [self.lchild], right + [self.rchild]), (left + [self.rchild], right + [self.lchild])
# Logika fungsi Not (Negasi)
class Not(Formula):
def __init__(self, child):
self.child = child
def v(self, v):
return not self.child.v(v)
def __str__(self):
return '¬' + str(self.child)
def eq(self, other):
return self.child == other.child
def _tleft(self, left, right):
return (left, right + [self.child]),
def _tright(self, left, right):
return (left + [self.child], right),
class Atom(Formula):
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def v(self, v):
return self in v
def __str__(self):
return str(self.name)
__repr__ = __str__
def eq(self, other):
return self.name == other.name
```
```python
from formula import Atom
a = Atom('a')
b = Atom('b')
c = Atom('c')
def dop(f, e):
print("Formula: ", f)
print("Valuation for", e, ": ", f.v(e))
print("Counterexample: ", f.t())
dop(a | b, {a})
dop(a >> b, {a})
dop(a << b, {a})
dop(a & b, {a,b})
dop(a & b >> (c >> a), {b,c})
dop(a & b | b & c, {b,c})
dop(~a & ~~~b, {})
dop(a >> (b >> c), {a, b})
dop(a >> (b >> c), {a, b, c})
dop(a >> b >> c, {a, c})
dop(((c | ~b) >> (b | c)) >> (b | c), {a, c})
dop(a | ~a, {})
dop(a >> a, {a})
dop(a << a, {})
dop((a >> b) | (b >> a), {})
dop((~a | b) | (~b | a), {})
dop((~a | a) | (~b | b), {})
```
OUTPUT
```
Formula: (a ∨ b)
Valuation for {a} : True
Counterexample: set()
Formula: (a → b)
Valuation for {a} : False
Counterexample: {a}
Formula: (a ↔ b)
Valuation for {a} : False
Counterexample: {b}
Formula: (a ∧ b)
Valuation for {a, b} : True
Counterexample: set()
Formula: (a ∧ (b → (c → a)))
Valuation for {c, b} : False
Counterexample: {c, b}
Formula: ((a ∧ b) ∨ (b ∧ c))
Valuation for {c, b} : True
Counterexample: set()
Formula: (¬a ∧ ¬¬¬b)
Valuation for {} : True
Counterexample: {b}
Formula: (a → (b → c))
Valuation for {a, b} : False
Counterexample: {a, b}
Formula: (a → (b → c))
Valuation for {a, c, b} : True
Counterexample: {a, b}
Formula: ((a → b) → c)
Valuation for {a, c} : True
Counterexample: set()
Formula: (((c ∨ ¬b) → (b ∨ c)) → (b ∨ c))
Valuation for {a, c} : True
Counterexample: None
Formula: (a ∨ ¬a)
Valuation for {} : True
Counterexample: None
Formula: (a → a)
Valuation for {a} : True
Counterexample: None
Formula: (a ↔ a)
Valuation for {} : True
Counterexample: None
Formula: ((a → b) ∨ (b → a))
Valuation for {} : True
Counterexample: None
Formula: ((¬a ∨ b) ∨ (¬b ∨ a))
Valuation for {} : True
Counterexample: None
Formula: ((¬a ∨ a) ∨ (¬b ∨ b))
Valuation for {} : True
Counterexample: None
```
https://github.com/minubae/python_mathematics/blob/master/logic.py
```python
# Title: Mathematical Algorithms - Logic in Python
# Date: Oct/27/2015, Tuesday - Current
# Author: Minwoo Bae (minubae.nyc@gmail.com)
# Reference: http://wphooper.com/teaching/2015-fall-308/python/Logic.html
import math
# 01) The Truth Table
# Suppose truth_function is a function which takes as input two boolean values P and Q and
# returns a new Boolean value. Then we can print out a truth table for truth_function.
# Here is a function which does this:
def print_truth_table(truth_function):
print(" P | Q | ", truth_function.__name__,"(P,Q)", sep="")
for P in (True, False):
for Q in (True, False):
print(str(P).ljust(5), "|", str(Q).ljust(5), "|",str(truth_function(P,Q)).ljust(5))
# 02) The Disjunction
# The disjunction of the statement P and Q is the statement P or Q and
# is denoted by P∨Q. Write a function named disjunction(P,Q) that takes
# as input two boolean values P and Q and returns the truth value of the statement " P or Q".
def disjunction(P,Q):
return P or Q
# 03) The Conjunction
# The disjunction of the statement P and Q is the statement P and Q and
# is denoted by P ∧ Q. Write a function named disjunction(P,Q) that takes
# as input two boolean values P and Q and returns the truth value of the statement " P and Q".
def conjunction(P,Q):
return P and Q
# 04) Exclusive Or
# The exclusive or logical operation takes as input Boolean values and returns True or False.
# It returns True if one of the two expressions is true and the other is false (in any order).
# It returns False if the two truth values match. Write a function named xor which takes
# as input two boolean values P and Q and when evaluated as xor(P,Q) returns
# the value of P xor Q (P⊕Q).
def xor(P,Q):
return (P or Q) and not (P and Q)
# 05) The Implication
# For statement P and Q, the implication (or conditional) is the statement If P, then Q
# Write a function named implies(P,Q) that takes as input two boolean values P and Q
# and returns the truth value of the statement " P implies Q".
def implies(P,Q):
if(P and Q) or (not P and Q) or (not P and not Q):
return True
elif(P and not Q):
return False
# 06) The Biconditional
# For statements (or open sentences) PP and QQ , the conjunction (P⟹Q)∧(Q⟹P)
# of the implication P⟹Q and its converse is called the biconditional of P and Q and
# is denoted by P⟺Q. Write a function named iff(P,Q) that takes as input two boolean values
# P and Q and returns the truth value of the statement " P if and only if Q".
def iff(P,Q):
if (P and Q) or (not P and not Q):
return True
elif (not P and Q) or (P and not Q):
return False
# 07) Logical Equivalence
# Let R and S are called logically equivalentlogically equivalent if R and S have the same truth values
# for all combinations of truth values of their component statements.
# If R and S are logically equivalent, then this is denoted by R≡S.
# Write a function named logically_equivalent(tf1, tf2) that takes as input two 2-input truth functions
# tf1 and tf2 and returns the boolean value of the statement ”The two truth functions are logically equivalent.”
# Your function should return True if and only if the two functions tf1 and tf2 return the same output
# whenever they are passed the same input values.
def logically_equivalent(tf1, tf2):
temp_tf1 = [] # List()
temp_tf2 = [] # List()
for P in (True, False):
for Q in (True, False):
temp_tf1.append(tf1(P,Q))
temp_tf2.append(tf2(P,Q))
return temp_tf1 == temp_tf2
def logically_equivalent_01(tf1, tf2):
for P in (True, False):
for Q in (True, False):
if not iff( tf1(P,Q), tf2(P,Q) ):
return False
return True
```
# Boolean Algebra
https://booleanpy.readthedocs.io/en/latest/index.html
#### Contoh 1. Gate AND
Berikut adalah kode fungsi `AND`
```python
def AND(a, b):
if a == 1 and b == 1:
return True
else:
return False
```
Output:
```
p a
True False
False True
```
https://prutor.ai/logic-gates-in-python/
:::info
Bolean algebra pada python
Aljabar Boolean adalah cabang dari aljabar yang berhubungan dengan operasi logika dan variabel biner.
Berikut ini adalah cara mendefinisikan Algebra Boolean pada Python
**Mencari nilai dari suatu ekspresi boolean pada python**
Contoh:
Cari nilai dari $1\cdot 0 + (0 + 1)'$ menggunakan python
```python
print(1*0 + (not(1 + 0))) //not digunakan untuk logika negasi
```
Output
```
0
```
Cara diatas dilakukan dengan mencetak langsung nilai yang dicari dari $1\cdot 0 + (0 + 1)'$, selain dengan cara tersebut untuk mencari nilai dari suatu ekspresi boolean pada python dapat dilakukan dengan cara:
```python=
#definisikan variabel a, b
a = 1
b = 0
print(a*b + (not(a + b)))
```
Output
```
0
```
Penjelasan:
1. Baris 2 dan 3 mendefinisikan ekspresi boolean 1 dan 0 dengan variabel a dan b
2. Baris 4 digunakan untuk mencetak ekspresi dari $1\cdot 0 + (0 + 1)'$
**Mengevaluasi Ekspresi Boolean pada Python**
contoh:
Evaluasi ekspresi Boolean $a' \cdot (b + c))$ jika $a = 0$, $b =1$ dan $c = 0$ dengan Python.
```python=
a = 0
b = 1
c = 0
x = (not(a))*(b+c)
if x == True or 1 + 1:
print('1')
else:
print('0')
```
Output
```
1
```
Penjelasan:
1. Baris 1 sampai 3 inisialiasi variabel
2. Baris 4 inisialisasi variabel `x` dimana berupa ekspresi boolean $a' \cdot (b + c))$
3. kondisi dimana jika bernilai `True` atau ketika bernilai 1 + 1 akan mencetak `1`, sebaliknya jika bernilai `False` akan mencetak `0`
**Fungsi Boolean pada Python**
Program berikut ini digunakan untuk mencari nilai dari fungsi boolean pada Python
Contoh:
Cari nilai fungsi Boolean
$f(x,y,z) = xyz + x'y + y'z$ jika $x = 1, y = 0$ dan $z = 1$ pada python
```python=
x = 1
y = 0
z = 1
fxyz = x*y*z + (not(x))*y + (not(y))*z
if fxyz == True or 1 + 1:
print('1')
else:
print('0')
```
OUTPUT
```
1
```
Penjelasan:
1. Baris 1 sampai 3 Inisialisasi variabel x = 1, y = 0, z = 1
2. Baris 4 inisialisasi variabel fxyz yang berisi fungsi boolean dan dilakukan cetak pada variabel tersebut
3. baris 5 sampai 8 kondisi dimana jika bernilai `True` atau ketika bernilai 1 + 1 akan mencetak `1`, sebaliknya jika bernilai `False` akan mencetak `0`
**14 DESEMBER 2022**
boolean.py pada python digunakan untuk implementasi boolean algebra. Ini mengimplementasikan 2 elemen dasar yaitu TRUE dan FALSE, dan sebuah kelas `symbol` untuk variabel. Ekspresi dibangun dengan menyusun simbol dan elemen dengan AND, OR, dan NOT. komposisi lainya seperti XOR dan NAND tidak di terapkan.
Untuk menggunakan fungsi yang berada pada boolean.py sebelumnya dilakukan installasi dengan
```pip install boolean.py```
## Membuat ekspresi boolean
Ada tiga cara untuk membuat ekspresi boolean. Semuanya dimulai dengan membuat aljabar, lalu menggunakan atribut dan metode aljabar untuk membangun ekspresi.
Kita dapat membuat ekspresi dari string:
```python
import boolean
algebra = boolean.BooleanAlgebra()
algebra.parse('x & y')
algebra.parse('(apple or banana and (orange or pineapple and (lemon or cherry)))')
```
OUTPUT:
```
AND(Symbol('x'), Symbol('y'))
OR(Symbol('apple'), AND(Symbol('banana'), OR(Symbol('orange'), AND(Symbol('pineapple'), OR(Symbol('lemon'), Symbol('cherry'))))))
```
Kita dapat membuat ekspresi dari ekspresi Python:
```python
import boolean
algebra = boolean.BooleanAlgebra()
x, y = algebra.symbols('x', 'y')
x & y
```
OUTPUT
```
AND(Symbol('x'), Symbol('y'))
```
Kita dapat membuat ekspresi dengan menggunakan fungsi aljabar:
```python
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> x, y = algebra.symbols('x', 'y')
>>> TRUE, FALSE, NOT, AND, OR, symbol = algebra.definition()
>>> expr = AND(x, y, NOT(OR(symbol('a'), symbol('b'))))
>>> expr
AND(Symbol('x'), Symbol('y'))
>>> print(expr.pretty())
AND(
Symbol('x'),
Symbol('y'),
NOT(
OR(
Symbol('a'),
Symbol('b')
)
)
)
>>> print(expr)
x&y&(~(a|b))
```
#### Evaluasi dari Ekspresi
Secara default, ekspresi tidak dievaluasi. Anda perlu memanggil metode simplifikasi() secara eksplisit sebuah ekspresi untuk melakukan beberapa penyederhanaan minimal untuk mengevaluasi sebuah ekspresi:
```python
import boolean
algebra = boolean.BooleanAlgebra()
x, y = algebra.symbols('x', 'y')
print(x&~x)
print(x|~x)
print(x|x)
print(x&x)
print(x&(x|y))
print((x&y) | (x&~y))
```
OUTPUT
```
x&~x
x|~x
x|x
x&x
x&(x|y)
(x&y)|(x&~y)
```
Saat `simplify()` dipanggil, hukum logika boolean berikut digunakan secara rekursif pada setiap sub-term ekspresi:
1. Asosiatif
2. Identitas
3. Idempoten
4. Identitas
5. Komplemen
6. Eliminasi
7. Absorpsi
8. Negatif Absorpsi
9. Komutatif
Ekspresi yang disederhanakan adalah pengembalian dan mungkin tidak sepenuhnya dievaluasi atau minimal:
```python
import boolean
algebra = boolean.BooleanAlgebra()
x, y, z = algebra.symbols('x', 'y', 'z')
print((((x|y)&z)|x&y).simplify())
```
OUTPUT
```
(x&y)|(z&(x|y))
```
#### Mencari ekualitas dari ekspresi
Ekualitas dari ekspresi dapat diuji dengan method`__eq__()` dan karenanya output dari `expr1 == expr2` tidak sama dengan persamaan matematis.
Dua ekspresi sama jika struktur dan simbolnya sama.
```python
# Proof x⊕r≡(x∨y)∧¬(x∧y)≡(x∧¬y)∨(¬x∧y)
if __name__ == "__main__":
x = True
y = False
z0 = (x or y) and not (x and y)
z1 = (x and not y) or (not x and y)
print(z0 == z1)
```
OUTPUT
```
True
```
#### Ekualitas dari simbol
Simbol dianggap sama jika sama atau objek terkaitnya sama.
```python
import boolean
algebra = boolean.BooleanAlgebra()
x, y, z = algebra.symbols('x', 'y', 'z')
print(x == y)
x1, x2 = algebra.symbols("x", "x")
print(x1 == x2)
x1, x2 = algebra.symbols(10, 10)
print(x1 == x2)
```
OUTPUT
```
False
True
True
```
#### Ekualitas dari struktur
Berikut adalah beberapa contoh struktur yang sama dan tidak sama:
```
import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> expr1 = algebra.parse("x|y")
>>> expr2 = algebra.parse("y|x")
>>> expr1 == expr2
True
>>> expr = algebra.parse("x|~x")
>>> expr == TRUE
False
>>> expr1 = algebra.parse("x&(~x|y)")
>>> expr2 = algebra.parse("x&y")
>>> expr1 == expr2
False
```
### Analisis Ekspresi boolean
#### Mendapatkan sub-terms
Semua ekspresi memiliki properti `args` yang merupakan tupel dari istilahnya. Untuk simbol dan elemen dasar, tuple ini kosong, untuk fungsi boolean berisi satu atau lebih simbol, elemen, atau sub-ekspresi.
```
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> algebra.parse("x|y|z").args
(Symbol('x'), Symbol('y'), Symbol('z'))
```
### Mendapatkan seluruh simbol
Untuk mendapatkan satu set() dari semua `symbol` unik dalam sebuah ekspresi, gunakan atribut simbolnya
```
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> algebra.parse("x|y&(x|z)").symbols
{Symbol('y'), Symbol('x'), Symbol('z')}
```
Untuk mendapatkan daftar semua simbol dalam ekspresi, gunakan metode get_symbols
```
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> algebra.parse("x|y&(x|z)").get_symbols()
[Symbol('x'), Symbol('y'), Symbol('x'), Symbol('z')]
```
### literal
Simbol dan negasi dari simbol disebut literal. Anda dapat menguji apakah suatu ekspresi adalah literal:
```
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> x, y, z = algebra.symbols('x', 'y', 'z')
>>> x.isliteral
True
>>> (~x).isliteral
True
>>> (x|y).isliteral
False
```
Atau dapatkan set() atau daftar semua literal yang terkandung dalam ekspresi:
```
>>> import boolean
>>> algebra = boolean.BooleanAlgebra()
>>> x, y, z = algebra.symbols('x', 'y', 'z')
>>> x.literals
{Symbol('x')}
>>> (~(x|~y)).get_literals()
[Symbol('x'), NOT(Symbol('y'))]
```
Untuk menghapus negasi kecuali dalam literal gunakan `literalize()`:
```
>>> (~(x|~y)).literalize()
~x&y
```
### Substitusi
Untuk mengganti bagian ekspresi, gunakan metode `subs()` :
```
>>> e = x|y&z
>>> e.subs({y&z:y})
x|y
```
SUMBER: https://booleanpy.readthedocs.io/en/latest/users_guide.html
### 15 DESEMBER 2022
Fungsi bool() memungkinkan Anda untuk mengevaluasi nilai apa pun, dan memberi Anda `True` atau `False` sebagai gantinya.
**Contoh:**
Cari nilai dari $1\cdot 0 + (0 + 1)'$ menggunakan python
```python
print(bool(1*0 + (not(1 + 0)))) //not digunakan untuk logika negasi
```
Output
```
False
```
https://www.w3schools.com/python/python_booleans.asp
Prove the **absorption law** $x(x+y) = x$
```python
import boolean
algebra = boolean.BooleanAlgebra()
x, y, z = algebra.symbols('x', 'y', 'z')
print((x*(x+y)).simplify())
```
OUTPUT
```
x
```
We display steps used to derives this identity and the law used in each step:
\begin{array}{r l l}
x(x+y) &= (x + 0)(x + y) & \qquad \small \text{(identity law for the Boolean sum)}\\
& = x + 0.y & \qquad \small \text{(Distributive law of the boolean sum over the Boolean product)} \\
& = x + y.0 & \qquad \small \text{(Commutative law for the Boolean product)} \\
& = x + 0 & \qquad \small \text{(Domination law for the Boolean product)} \\
& = x & \qquad \small \text{(Identity law for the Boolean sum)} \\
\end{array}
Sumber: Discrete Mathematics Kenneth H. Rosen Ch 12 ex.10 p 816
Contoh: 5.3.4
Cari nilai-nilai dari fungsi Boolean $f(x, y, z) = xy + z'$.
*Solusi:*
Nilai-nilai fungsi ini ditampilkan pada tabel berikut.
```python
print(f'| {"x":^8s} | {"y":^8s} | {"z":^8s} |{"xy":^10s}|{"~z":^9s} | {"a":^10s} | ')
for x in [True, False]:
for y in [True, False]:
for z in [True, False]:
for negz in [not z]:
xy = x and y
fa = (x and y) or (not(z))
if fa == 2:
print(fa = "1")
print(f'| {x!s:8} | {y!s:8} | {z!s:8} | {xy!s:8} | {negz!s:8} | {fa!s:10} | ')
```
OUTPUT
```
| x | y | z | xy | ~z | a |
| True | True | True | True | False | True |
| True | True | False | True | True | True |
| True | False | True | False | False | False |
| True | False | False | False | True | True |
| False | True | True | False | False | False |
| False | True | False | False | True | True |
| False | False | True | False | False | False |
| False | False | False | False | True | True |
```
**19 DESEMBER 2022**
Sumber lainnya:
1. https://cs.stanford.edu/people/nick/py/python-boolean.html
2. https://pyeda.readthedocs.io/en/latest/boolalg.html
3. https://docs.sympy.org/latest/modules/logic.html
:::
:::info
### Gate AND
```python
def AND (a, b):
if a == 1 and b == 1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(AND(1, 1))
print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
```
```
True
+---------------+----------------+
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |
```
#### Gate OR
```python
def OR(a, b):
if a == 1 or b ==1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(OR(0, 0))
print("+---------------+----------------+")
print(" | OR Truth Table | Result |")
print(" A = False, B = False | A OR B =",OR(False,False)," | ")
print(" A = False, B = True | A OR B =",OR(False,True)," | ")
print(" A = True, B = False | A OR B =",OR(True,False)," | ")
print(" A = True, B = True | A OR B =",OR(True,True)," | ")
```
```
False
+---------------+----------------+
| OR Truth Table | Result |
A = False, B = False | A OR B = False |
A = False, B = True | A OR B = True |
A = True, B = False | A OR B = True |
A = True, B = True | A OR B = True |
```
### Gate Not
```python=
def NOT(a):
return not a
# Driver code
if __name__=='__main__':
print(NOT(0))
print("+---------------+----------------+")
print(" | NOT Truth Table | Result |")
print(" A = False | A NOT =",NOT(False)," | ")
print(" A = True, | A NOT =",NOT(True)," | ")
```
```
True
+---------------+----------------+
| NOT Truth Table | Result |
A = False | A NOT = True |
A = True, | A NOT = False |
```
#### Gate NAND
```python
def NAND (a, b):
if a == 1 and b == 1:
return False
else:
return True
# Driver code
if __name__=='__main__':
print(NAND(1, 0))
print("+---------------+----------------+")
print(" | NAND Truth Table | Result |")
print(" A = False, B = False | A AND B =",NAND(False,False)," | ")
print(" A = False, B = True | A AND B =",NAND(False,True)," | ")
print(" A = True, B = False | A AND B =",NAND(True,False)," | ")
print(" A = True, B = True | A AND B =",NAND(True,True)," | ")
```
```
True
+---------------+----------------+
| NAND Truth Table | Result |
A = False, B = False | A AND B = True |
A = False, B = True | A AND B = True |
A = True, B = False | A AND B = True |
A = True, B = True | A AND B = False |
```
#### Gate NOR
```python
def NOR(a, b):
if(a == 0) and (b == 0):
return 1
elif(a == 0) and (b == 1):
return 0
elif(a == 1) and (b == 0):
return 0
elif(a == 1) and (b == 1):
return 0
# Driver code
if __name__=='__main__':
print(NOR(0, 0))
print("+---------------+----------------+")
print(" | NOR Truth Table | Result |")
print(" A = False, B = False | A NOR B =",NOR(False,False)," | ")
print(" A = False, B = True | A NOR B =",NOR(False,True)," | ")
print(" A = True, B = False | A NOR B =",NOR(True,False)," | ")
print(" A = True, B = True | A NOR B =",NOR(True,True)," | ")
```
```
1
+---------------+----------------+
| NOR Truth Table | Result |
A = False, B = False | A NOR B = 1 |
A = False, B = True | A NOR B = 0 |
A = True, B = False | A NOR B = 0 |
A = True, B = True | A NOR B = 0 |
```
#### Gate XOR
```python
def XOR (a, b):
if a != b:
return 1
else:
return 0
# Driver code
if __name__=='__main__':
print(XOR(5, 5))
print("+---------------+----------------+")
print(" | XOR Truth Table | Result |")
print(" A = False, B = False | A XOR B =",XOR(False,False)," | ")
print(" A = False, B = True | A XOR B =",XOR(False,True)," | ")
print(" A = True, B = False | A XOR B =",XOR(True,False)," | ")
print(" A = True, B = True | A XOR B =",XOR(True,True)," | ")
```
```
0
+---------------+----------------+
| XOR Truth Table | Result |
A = False, B = False | A XOR B = 0 |
A = False, B = True | A XOR B = 1 |
A = True, B = False | A XOR B = 1 |
A = True, B = True | A XOR B = 0 |
```
#### EX-NOR
```python
def XNOR(a,b):
if(a == b):
return 1
else:
return 0
# Driver code
if __name__=='__main__':
print(XNOR(1,1))
print("+---------------+----------------+")
print(" | XNOR Truth Table | Result |")
print(" A = False, B = False | A XNOR B =",XNOR(False,False)," | ")
print(" A = False, B = True | A XNOR B =",XNOR(False,True)," | ")
print(" A = True, B = False | A XNOR B =",XNOR(True,False)," | ")
print(" A = True, B = True | A XNOR B =",XNOR(True,True)," | ")
```
```
1
+---------------+----------------+
| XNOR Truth Table | Result |
A = False, B = False | A XNOR B = 1 |
A = False, B = True | A XNOR B = 0 |
A = True, B = False | A XNOR B = 0 |
A = True, B = True | A XNOR B = 1 |
```
:::