prolog-practicals 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ """prolog_practicals - 15 ready-to-run Prolog lab programs.
2
+
3
+ Run ``prolog-practicals`` (or ``python -m prolog_practicals``) for the menu.
4
+
5
+ From Python:
6
+
7
+ >>> from prolog_practicals import get_code
8
+ >>> print(get_code(6)) # factorial program
9
+ """
10
+
11
+ from .practicals import PRACTICALS
12
+
13
+ __version__ = "1.0.0"
14
+ __all__ = ["PRACTICALS", "get_practical", "get_code", "__version__"]
15
+
16
+
17
+ def get_practical(number):
18
+ """Return the practical dictionary for ``number`` (1-15)."""
19
+ for p in PRACTICALS:
20
+ if p["number"] == int(number):
21
+ return p
22
+ raise ValueError("No practical numbered %r (choose 1-%d)" % (number, len(PRACTICALS)))
23
+
24
+
25
+ def get_code(number):
26
+ """Return the Prolog source code of practical ``number`` as a string."""
27
+ return get_practical(number)["code"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,339 @@
1
+ """Command-line menu: pick a practical, enter a roll number, and the
2
+ program is saved to Desktop/<roll number>/<practical>.pl"""
3
+
4
+ import argparse
5
+ import datetime
6
+ import os
7
+ import re
8
+ import sys
9
+ import textwrap
10
+ from pathlib import Path
11
+
12
+ from . import __version__, get_practical
13
+ from .practicals import PRACTICALS
14
+
15
+ # ---------------------------------------------------------------- colours
16
+
17
+ _COLOR = False
18
+
19
+
20
+ def _init_color():
21
+ global _COLOR
22
+ if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
23
+ _COLOR = False
24
+ return
25
+ if sys.platform == "win32":
26
+ os.system("") # turns on ANSI colour codes in Windows 10+ terminals
27
+ _COLOR = True
28
+
29
+
30
+ def _c(text, code):
31
+ return "\033[%sm%s\033[0m" % (code, text) if _COLOR else text
32
+
33
+
34
+ def bold(t):
35
+ return _c(t, "1")
36
+
37
+
38
+ def cyan(t):
39
+ return _c(t, "1;36")
40
+
41
+
42
+ def green(t):
43
+ return _c(t, "1;32")
44
+
45
+
46
+ def yellow(t):
47
+ return _c(t, "33")
48
+
49
+
50
+ def red(t):
51
+ return _c(t, "1;31")
52
+
53
+
54
+ def dim(t):
55
+ return _c(t, "2")
56
+
57
+
58
+ # ---------------------------------------------------------------- Desktop
59
+
60
+ def _windows_desktop():
61
+ """Real Desktop folder on Windows (handles OneDrive-redirected Desktops)."""
62
+ try:
63
+ import ctypes
64
+ import uuid
65
+ from ctypes import wintypes
66
+
67
+ class GUID(ctypes.Structure):
68
+ _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16),
69
+ ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)]
70
+
71
+ folder_id = GUID.from_buffer_copy(
72
+ uuid.UUID("{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}").bytes_le) # FOLDERID_Desktop
73
+ fn = ctypes.windll.shell32.SHGetKnownFolderPath
74
+ fn.argtypes = [ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE,
75
+ ctypes.POINTER(ctypes.c_wchar_p)]
76
+ fn.restype = ctypes.c_long
77
+ out = ctypes.c_wchar_p()
78
+ if fn(ctypes.byref(folder_id), 0, None, ctypes.byref(out)) == 0 and out.value:
79
+ path = Path(out.value)
80
+ ctypes.windll.ole32.CoTaskMemFree(out)
81
+ return path
82
+ except Exception:
83
+ pass
84
+ try: # fallback: registry
85
+ import winreg
86
+ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
87
+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders")
88
+ value, _ = winreg.QueryValueEx(key, "Desktop")
89
+ return Path(os.path.expandvars(value))
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def _xdg_desktop():
95
+ """Desktop folder on Linux, which may be renamed or translated."""
96
+ home = Path.home()
97
+ cfg = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / "user-dirs.dirs"
98
+ try:
99
+ for line in cfg.read_text(errors="ignore").splitlines():
100
+ m = re.match(r'\s*XDG_DESKTOP_DIR\s*=\s*"(.*)"\s*$', line)
101
+ if m:
102
+ p = Path(os.path.expandvars(m.group(1).replace("$HOME", str(home))))
103
+ if p != home:
104
+ return p
105
+ except OSError:
106
+ pass
107
+ return None
108
+
109
+
110
+ def desktop_dir():
111
+ """Best guess of the user's Desktop folder on Windows, macOS and Linux."""
112
+ found = None
113
+ if sys.platform == "win32":
114
+ found = _windows_desktop()
115
+ elif sys.platform.startswith(("linux", "freebsd", "openbsd")):
116
+ found = _xdg_desktop()
117
+ return found or Path.home() / "Desktop"
118
+
119
+
120
+ # ---------------------------------------------------------------- roll number
121
+
122
+ _BAD_CHARS = set('<>:"/\\|?*')
123
+ _RESERVED = {"CON", "PRN", "AUX", "NUL"} | {"COM%d" % i for i in range(1, 10)} \
124
+ | {"LPT%d" % i for i in range(1, 10)}
125
+
126
+
127
+ def check_roll(raw):
128
+ """Return (roll, error). The roll number becomes a folder name, so it must
129
+ be a valid folder name on Windows, macOS and Linux."""
130
+ roll = (raw or "").strip()
131
+ if not roll:
132
+ return None, "Roll number cannot be empty."
133
+ bad = sorted({ch for ch in roll if ch in _BAD_CHARS or ord(ch) < 32})
134
+ if bad:
135
+ shown = " ".join(repr(ch) if ord(ch) < 32 else ch for ch in bad)
136
+ return None, "Roll number cannot contain these characters: %s (try - or _ instead)" % shown
137
+ if roll.endswith("."):
138
+ return None, "Roll number cannot end with a dot."
139
+ if roll.split(".")[0].upper() in _RESERVED:
140
+ return None, "'%s' is a reserved name on Windows. Please use your real roll number." % roll
141
+ if len(roll) > 60:
142
+ return None, "Roll number is too long (max 60 characters)."
143
+ return roll, None
144
+
145
+
146
+ # ---------------------------------------------------------------- file content
147
+
148
+ def build_file_text(p, roll):
149
+ rule = "% " + "=" * 64
150
+ head = [rule, "% Practical " + str(p["number"]) + ": " + p["title"]]
151
+ head += ["% " + ln for ln in textwrap.wrap("Aim: " + p["aim"], 62, subsequent_indent=" ")]
152
+ head += ["% Roll No : " + roll,
153
+ "% Date : " + datetime.date.today().strftime("%d-%m-%Y"),
154
+ rule, ""]
155
+ sample = ["", "% " + "-" * 64, "% Sample run (SWI-Prolog)", "% " + "-" * 64]
156
+ sample += [("% " + ln) if ln else "%" for ln in p["sample_run"].splitlines()]
157
+ return "\n".join(head) + "\n" + p["code"] + "\n".join(sample) + "\n"
158
+
159
+
160
+ def save_practical(p, roll, base_dir, overwrite):
161
+ """Write the practical. ``overwrite`` is True, False, or a function that is
162
+ asked when the file exists. Returns the path, or None if skipped."""
163
+ folder = Path(base_dir) / roll
164
+ folder.mkdir(parents=True, exist_ok=True)
165
+ path = folder / p["filename"]
166
+ if path.exists():
167
+ ok = overwrite(path) if callable(overwrite) else overwrite
168
+ if not ok:
169
+ return None
170
+ text = build_file_text(p, roll)
171
+ with open(path, "w", encoding="utf-8") as fh:
172
+ fh.write(text)
173
+ return path
174
+
175
+
176
+ # ---------------------------------------------------------------- interactive menu
177
+
178
+ def _ask(prompt):
179
+ return input(yellow(prompt))
180
+
181
+
182
+ def _confirm(prompt, default=False):
183
+ hint = " [Y/n]: " if default else " [y/N]: "
184
+ ans = _ask(prompt + hint).strip().lower()
185
+ return default if not ans else ans in ("y", "yes")
186
+
187
+
188
+ def _banner():
189
+ line = "=" * 62
190
+ print(cyan(line))
191
+ print(cyan(" PROLOG PRACTICALS") + dim(" v%s 15 ready-to-run programs" % __version__))
192
+ print(cyan(line))
193
+
194
+
195
+ def _menu():
196
+ print()
197
+ for p in PRACTICALS:
198
+ print(" %s %s" % (bold("%2d." % p["number"]), p["title"]))
199
+ print(" %s Save ALL 15 practicals" % bold(" A."))
200
+ print(" %s Quit" % bold(" Q."))
201
+ print()
202
+
203
+
204
+ def _ask_roll(last_roll):
205
+ while True:
206
+ prompt = "Enter your roll number"
207
+ prompt += (" [%s]: " % last_roll) if last_roll else ": "
208
+ raw = _ask(prompt)
209
+ if not raw.strip() and last_roll:
210
+ return last_roll
211
+ roll, err = check_roll(raw)
212
+ if err:
213
+ print(red(" " + err))
214
+ continue
215
+ return roll
216
+
217
+
218
+ def _ask_overwrite(path):
219
+ return _confirm(" %s already exists. Overwrite?" % path.name)
220
+
221
+
222
+ def interactive(base_dir):
223
+ _banner()
224
+ print(dim("Files will be saved in: %s" % (Path(base_dir) / "<roll number>")))
225
+ last_roll = None
226
+ show_menu = True
227
+ while True:
228
+ if show_menu:
229
+ _menu()
230
+ show_menu = True
231
+ choice = _ask("Choose a practical (1-15, A = all, Q = quit): ").strip().lower()
232
+ if choice in ("q", "quit", "exit"):
233
+ print("Bye!")
234
+ return 0
235
+ if choice in ("a", "all"):
236
+ chosen = list(PRACTICALS)
237
+ elif choice.isdigit() and 1 <= int(choice) <= len(PRACTICALS):
238
+ chosen = [get_practical(int(choice))]
239
+ print(bold("\n Practical %d: %s" % (chosen[0]["number"], chosen[0]["title"])))
240
+ else:
241
+ print(red(" Please type a number from 1 to 15, A or Q."))
242
+ show_menu = False
243
+ continue
244
+
245
+ roll = _ask_roll(last_roll)
246
+ last_roll = roll
247
+ saved = []
248
+ for p in chosen:
249
+ try:
250
+ path = save_practical(p, roll, base_dir, _ask_overwrite)
251
+ except OSError as e:
252
+ print(red(" Could not write the file: %s" % e))
253
+ break
254
+ if path is None:
255
+ print(dim(" Skipped %s" % p["filename"]))
256
+ else:
257
+ saved.append(path)
258
+ print(green(" Saved: ") + str(path))
259
+ if len(saved) == 1:
260
+ print(dim(" Load it in SWI-Prolog with: ?- consult('%s')." % saved[0].as_posix()))
261
+ elif saved:
262
+ print(green("\n Done! %d files saved in %s" % (len(saved), saved[0].parent)))
263
+
264
+
265
+ # ---------------------------------------------------------------- entry point
266
+
267
+ def _parser():
268
+ ap = argparse.ArgumentParser(
269
+ prog="prolog-practicals",
270
+ description="Save ready-to-run Prolog practicals to Desktop/<roll number>/. "
271
+ "Run with no options for the interactive menu.")
272
+ ap.add_argument("-l", "--list", action="store_true", help="list all practicals and exit")
273
+ ap.add_argument("-s", "--show", metavar="N", type=int, help="print the code of practical N and exit")
274
+ ap.add_argument("-q", "--question", metavar="N",
275
+ help="practical number to save without the menu (1-15 or 'all'); needs --roll")
276
+ ap.add_argument("-r", "--roll", help="roll number (folder name)")
277
+ ap.add_argument("-d", "--dir", metavar="PATH",
278
+ help="save under this folder instead of the Desktop")
279
+ ap.add_argument("-f", "--force", action="store_true", help="overwrite existing files without asking")
280
+ ap.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
281
+ return ap
282
+
283
+
284
+ def main(argv=None):
285
+ _init_color()
286
+ args = _parser().parse_args(argv)
287
+ base_dir = Path(args.dir).expanduser() if args.dir else desktop_dir()
288
+
289
+ try:
290
+ if args.list:
291
+ for p in PRACTICALS:
292
+ print("%2d. %s" % (p["number"], p["title"]))
293
+ return 0
294
+
295
+ if args.show is not None:
296
+ try:
297
+ p = get_practical(args.show)
298
+ except ValueError as e:
299
+ print(red(str(e)), file=sys.stderr)
300
+ return 2
301
+ print(p["code"], end="")
302
+ return 0
303
+
304
+ if args.question is not None:
305
+ if args.question.lower() == "all":
306
+ chosen = list(PRACTICALS)
307
+ else:
308
+ try:
309
+ chosen = [get_practical(args.question)]
310
+ except ValueError:
311
+ print(red("--question must be a number from 1 to 15 or 'all'"), file=sys.stderr)
312
+ return 2
313
+ roll, err = check_roll(args.roll if args.roll else _ask("Enter your roll number: "))
314
+ if err:
315
+ print(red(err), file=sys.stderr)
316
+ return 2
317
+ for p in chosen:
318
+ path = save_practical(p, roll, base_dir, True if args.force else _ask_overwrite)
319
+ print(("Saved: %s" % path) if path else ("Skipped %s" % p["filename"]))
320
+ return 0
321
+
322
+ return interactive(base_dir)
323
+
324
+ except KeyboardInterrupt:
325
+ print("\nBye!")
326
+ return 130
327
+ except EOFError:
328
+ print("\nBye!")
329
+ return 0
330
+ except BrokenPipeError: # e.g. output piped into `head`
331
+ try:
332
+ sys.stdout = open(os.devnull, "w")
333
+ except OSError:
334
+ pass
335
+ return 0
336
+
337
+
338
+ if __name__ == "__main__":
339
+ sys.exit(main())
@@ -0,0 +1,513 @@
1
+ """The 15 Prolog practicals, embedded as plain Python strings.
2
+
3
+ Each entry has: number, title, aim, filename, code and sample_run.
4
+ The sample runs were produced with SWI-Prolog 9.
5
+ """
6
+
7
+ PRACTICALS = [
8
+ {
9
+ "number": 1,
10
+ "title": 'Family tree and family relationships',
11
+ "aim": 'Write a PROLOG program to implement the family tree and demonstrate the family relationship.',
12
+ "filename": 'p01_family.pl',
13
+ "code": r"""
14
+ % ---------- Facts ----------
15
+ male(ram). male(shyam). male(mohan).
16
+ male(rohit). male(amit). male(karan).
17
+
18
+ female(sita). female(gita). female(radha).
19
+ female(priya). female(neha).
20
+
21
+ % parent(Parent, Child)
22
+ parent(ram, shyam). parent(sita, shyam).
23
+ parent(ram, gita). parent(sita, gita).
24
+ parent(shyam, rohit). parent(radha, rohit).
25
+ parent(shyam, priya). parent(radha, priya).
26
+ parent(mohan, amit). parent(gita, amit).
27
+ parent(mohan, neha). parent(gita, neha).
28
+ parent(rohit, karan).
29
+
30
+ % ---------- Rules ----------
31
+ father(X, Y) :- parent(X, Y), male(X).
32
+ mother(X, Y) :- parent(X, Y), female(X).
33
+ child(X, Y) :- parent(Y, X).
34
+
35
+ % X and Y share both parents and are different people
36
+ sibling(X, Y) :-
37
+ father(F, X), father(F, Y),
38
+ mother(M, X), mother(M, Y),
39
+ X \= Y.
40
+
41
+ brother(X, Y) :- sibling(X, Y), male(X).
42
+ sister(X, Y) :- sibling(X, Y), female(X).
43
+
44
+ grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
45
+ grandfather(X, Z) :- grandparent(X, Z), male(X).
46
+ grandmother(X, Z) :- grandparent(X, Z), female(X).
47
+
48
+ uncle(X, Y) :- parent(P, Y), brother(X, P).
49
+ aunt(X, Y) :- parent(P, Y), sister(X, P).
50
+
51
+ cousin(X, Y) :- parent(P1, X), parent(P2, Y), sibling(P1, P2).
52
+
53
+ % Recursive rule
54
+ ancestor(X, Y) :- parent(X, Y).
55
+ ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
56
+ """,
57
+ "sample_run": r"""
58
+ ?- father(X, rohit).
59
+ X = shyam.
60
+
61
+ ?- mother(radha, priya).
62
+ true.
63
+
64
+ ?- sibling(rohit, X).
65
+ X = priya.
66
+
67
+ ?- brother(X, gita).
68
+ X = shyam.
69
+
70
+ ?- grandfather(X, amit).
71
+ X = ram.
72
+
73
+ ?- uncle(X, amit).
74
+ X = shyam.
75
+
76
+ ?- aunt(X, rohit).
77
+ X = gita.
78
+
79
+ ?- cousin(rohit, X).
80
+ X = amit ;
81
+ X = neha.
82
+
83
+ ?- grandmother(sita, Y).
84
+ Y = rohit ;
85
+ Y = priya ;
86
+ Y = amit ;
87
+ Y = neha.
88
+
89
+ ?- ancestor(X, karan).
90
+ X = rohit ;
91
+ X = ram ;
92
+ X = sita ;
93
+ X = shyam ;
94
+ X = radha.
95
+ """,
96
+ },
97
+ {
98
+ "number": 2,
99
+ "title": 'Concatenate two lists: conc(L1, L2, L3)',
100
+ "aim": 'Write a PROLOG program to implement conc(L1, L2, L3) where L2 is the list to be appended with L1 to get the resulted list L3.',
101
+ "filename": 'p02_conc.pl',
102
+ "code": r"""
103
+ conc([], L2, L2).
104
+ conc([H|T1], L2, [H|T3]) :-
105
+ conc(T1, L2, T3).
106
+ """,
107
+ "sample_run": r"""
108
+ ?- conc([1,2,3], [4,5], L3).
109
+ L3 = [1, 2, 3, 4, 5].
110
+
111
+ ?- conc([a,b], [c], [a,b,c]).
112
+ true.
113
+
114
+ ?- conc(L1, [5], [1,2,5]).
115
+ L1 = [1, 2].
116
+
117
+ ?- conc(L1, L2, [1,2]).
118
+ L1 = [],
119
+ L2 = [1, 2] ;
120
+ L1 = [1],
121
+ L2 = [2] ;
122
+ L1 = [1, 2],
123
+ L2 = [].
124
+ """,
125
+ },
126
+ {
127
+ "number": 3,
128
+ "title": 'Reverse a list: reverse(L, R)',
129
+ "aim": 'Write a PROLOG program to implement reverse(L, R) where List L is original and List R is reversed list.',
130
+ "filename": 'p03_reverse.pl',
131
+ "code": r"""
132
+ % Method 1: accumulator (efficient, O(n))
133
+ reverse(L, R) :-
134
+ rev_acc(L, [], R).
135
+
136
+ rev_acc([], Acc, Acc).
137
+ rev_acc([H|T], Acc, R) :-
138
+ rev_acc(T, [H|Acc], R).
139
+
140
+ % Method 2: naive reverse using conc/3 (simple, O(n^2))
141
+ naive_reverse([], []).
142
+ naive_reverse([H|T], R) :-
143
+ naive_reverse(T, RT),
144
+ conc(RT, [H], R).
145
+
146
+ conc([], L, L).
147
+ conc([H|T1], L2, [H|T3]) :- conc(T1, L2, T3).
148
+ """,
149
+ "sample_run": r"""
150
+ ?- reverse([1,2,3,4,5], R).
151
+ R = [5, 4, 3, 2, 1].
152
+
153
+ ?- reverse([a,b,c], [c,b,a]).
154
+ true.
155
+
156
+ ?- reverse([], R).
157
+ R = [].
158
+
159
+ ?- naive_reverse([x,y,z], R).
160
+ R = [z, y, x].
161
+ """,
162
+ },
163
+ {
164
+ "number": 4,
165
+ "title": 'Sum of two numbers',
166
+ "aim": 'Write a PROLOG program to calculate the sum of two numbers.',
167
+ "filename": 'p04_sum.pl',
168
+ "code": r"""
169
+ sum(X, Y, S) :-
170
+ S is X + Y.
171
+
172
+ % Interactive version: reads the two numbers from the keyboard
173
+ sum :-
174
+ write('Enter first number: '), read(X),
175
+ write('Enter second number: '), read(Y),
176
+ S is X + Y,
177
+ write('Sum = '), write(S), nl.
178
+ """,
179
+ "sample_run": r"""
180
+ ?- sum(15, 27, S).
181
+ S = 42.
182
+
183
+ ?- sum(3.5, 2, S).
184
+ S = 5.5.
185
+
186
+ ?- sum(-8, 3, S).
187
+ S = -5.
188
+
189
+ ?- sum.
190
+ Enter first number: 12.
191
+ Enter second number: 30.
192
+ Sum = 42
193
+ true.
194
+ """,
195
+ },
196
+ {
197
+ "number": 5,
198
+ "title": 'Maximum of two numbers: max(X, Y, M)',
199
+ "aim": 'Write a PROLOG program to implement max(X, Y, M) so that M is the maximum of two numbers X and Y.',
200
+ "filename": 'p05_max.pl',
201
+ "code": r"""
202
+ max(X, Y, M) :-
203
+ X >= Y, !,
204
+ M = X.
205
+ max(_, Y, Y).
206
+ """,
207
+ "sample_run": r"""
208
+ ?- max(10, 25, M).
209
+ M = 25.
210
+
211
+ ?- max(40, 7, M).
212
+ M = 40.
213
+
214
+ ?- max(6, 6, M).
215
+ M = 6.
216
+
217
+ ?- max(5, 3, 3).
218
+ false.
219
+ """,
220
+ },
221
+ {
222
+ "number": 6,
223
+ "title": 'Factorial of a number: factorial(N, F)',
224
+ "aim": 'Write a program in PROLOG to implement factorial (N, F) where F represents the factorial of a number N.',
225
+ "filename": 'p06_factorial.pl',
226
+ "code": r"""
227
+ factorial(0, 1).
228
+ factorial(N, F) :-
229
+ N > 0,
230
+ N1 is N - 1,
231
+ factorial(N1, F1),
232
+ F is N * F1.
233
+ """,
234
+ "sample_run": r"""
235
+ ?- factorial(0, F).
236
+ F = 1.
237
+
238
+ ?- factorial(5, F).
239
+ F = 120.
240
+
241
+ ?- factorial(10, F).
242
+ F = 3628800.
243
+
244
+ ?- factorial(4, 24).
245
+ true.
246
+ """,
247
+ },
248
+ {
249
+ "number": 7,
250
+ "title": 'Nth Fibonacci term: generate_fib(N, T)',
251
+ "aim": 'Write a program in PROLOG to implement generate_fib(N,T) where T represents the Nth term of the Fibonacci series.',
252
+ "filename": 'p07_fib.pl',
253
+ "code": r"""
254
+ % Series: 0, 1, 1, 2, 3, 5, 8, 13, ... (1st term = 0, 2nd term = 1)
255
+
256
+ generate_fib(1, 0).
257
+ generate_fib(2, 1).
258
+ generate_fib(N, T) :-
259
+ N > 2,
260
+ N1 is N - 1,
261
+ N2 is N - 2,
262
+ generate_fib(N1, T1),
263
+ generate_fib(N2, T2),
264
+ T is T1 + T2.
265
+
266
+ % Print the first N terms of the series
267
+ print_fib(N) :-
268
+ between(1, N, I),
269
+ generate_fib(I, T),
270
+ write(T), write(' '),
271
+ fail.
272
+ print_fib(_) :- nl.
273
+ """,
274
+ "sample_run": r"""
275
+ ?- generate_fib(1, T).
276
+ T = 0.
277
+
278
+ ?- generate_fib(7, T).
279
+ T = 8.
280
+
281
+ ?- generate_fib(10, T).
282
+ T = 34.
283
+
284
+ ?- print_fib(10).
285
+ 0 1 1 2 3 5 8 13 21 34
286
+ true.
287
+ """,
288
+ },
289
+ {
290
+ "number": 8,
291
+ "title": 'Power of a number: power(Num, Pow, Ans)',
292
+ "aim": 'Write a PROLOG program to implement power (Num, Pow, Ans) : where Num is raised to the power Pow to get Ans.',
293
+ "filename": 'p08_power.pl',
294
+ "code": r"""
295
+ power(_, 0, 1).
296
+ power(Num, Pow, Ans) :-
297
+ Pow > 0,
298
+ Pow1 is Pow - 1,
299
+ power(Num, Pow1, Ans1),
300
+ Ans is Num * Ans1.
301
+ """,
302
+ "sample_run": r"""
303
+ ?- power(2, 10, Ans).
304
+ Ans = 1024.
305
+
306
+ ?- power(5, 3, Ans).
307
+ Ans = 125.
308
+
309
+ ?- power(7, 0, Ans).
310
+ Ans = 1.
311
+
312
+ ?- power(3, 4, 81).
313
+ true.
314
+ """,
315
+ },
316
+ {
317
+ "number": 9,
318
+ "title": 'Multiply two numbers: multi(N1, N2, R)',
319
+ "aim": 'PROLOG program to implement multi (N1, N2, R) : where N1 and N2 denotes the numbers to be multiplied and R represents the result.',
320
+ "filename": 'p09_multi.pl',
321
+ "code": r"""
322
+ multi(N1, N2, R) :-
323
+ R is N1 * N2.
324
+
325
+ % Alternative: multiplication as repeated addition (N2 >= 0)
326
+ multi_add(_, 0, 0).
327
+ multi_add(N1, N2, R) :-
328
+ N2 > 0,
329
+ N3 is N2 - 1,
330
+ multi_add(N1, N3, R1),
331
+ R is R1 + N1.
332
+ """,
333
+ "sample_run": r"""
334
+ ?- multi(6, 7, R).
335
+ R = 42.
336
+
337
+ ?- multi(2.5, 4, R).
338
+ R = 10.0.
339
+
340
+ ?- multi(-3, 5, R).
341
+ R = -15.
342
+
343
+ ?- multi_add(6, 4, R).
344
+ R = 24.
345
+ """,
346
+ },
347
+ {
348
+ "number": 10,
349
+ "title": 'Member of a list: memb(X, L)',
350
+ "aim": 'Write a PROLOG program to implement memb(X, L): to check whether X is a member of L or not.',
351
+ "filename": 'p10_memb.pl',
352
+ "code": r"""
353
+ memb(X, [X|_]).
354
+ memb(X, [_|T]) :-
355
+ memb(X, T).
356
+ """,
357
+ "sample_run": r"""
358
+ ?- memb(c, [a,b,c,d]).
359
+ true.
360
+
361
+ ?- memb(z, [a,b,c,d]).
362
+ false.
363
+
364
+ ?- memb(X, [red,green,blue]).
365
+ X = red ;
366
+ X = green ;
367
+ X = blue.
368
+ """,
369
+ },
370
+ {
371
+ "number": 11,
372
+ "title": 'Sum of a list: sumlist(L, S)',
373
+ "aim": 'Write a PROLOG program to implement sumlist(L, S) so that S is the sum of a given list L.',
374
+ "filename": 'p11_sumlist.pl',
375
+ "code": r"""
376
+ sumlist([], 0).
377
+ sumlist([H|T], S) :-
378
+ sumlist(T, S1),
379
+ S is H + S1.
380
+ """,
381
+ "sample_run": r"""
382
+ ?- sumlist([1,2,3,4,5], S).
383
+ S = 15.
384
+
385
+ ?- sumlist([10,-4,6], S).
386
+ S = 12.
387
+
388
+ ?- sumlist([], S).
389
+ S = 0.
390
+ """,
391
+ },
392
+ {
393
+ "number": 12,
394
+ "title": 'Even / odd length list: evenlength, oddlength',
395
+ "aim": 'Write a PROLOG program to implement two predicates evenlength(List) and oddlength(List) so that they are true if their argument is a list of even or odd length respectively.',
396
+ "filename": 'p12_evenodd.pl',
397
+ "code": r"""
398
+ evenlength([]).
399
+ evenlength([_|T]) :-
400
+ oddlength(T).
401
+
402
+ oddlength([_|T]) :-
403
+ evenlength(T).
404
+ """,
405
+ "sample_run": r"""
406
+ ?- evenlength([a,b,c,d]).
407
+ true.
408
+
409
+ ?- evenlength([a,b,c]).
410
+ false.
411
+
412
+ ?- oddlength([1,2,3]).
413
+ true.
414
+
415
+ ?- oddlength([]).
416
+ false.
417
+
418
+ ?- evenlength([]).
419
+ true.
420
+ """,
421
+ },
422
+ {
423
+ "number": 13,
424
+ "title": 'Maximum of a list: maxlist(L, M)',
425
+ "aim": 'Write a PROLOG program to implement maxlist(L, M) so that M is the maximum number in the list.',
426
+ "filename": 'p13_maxlist.pl',
427
+ "code": r"""
428
+ maxlist([X], X).
429
+ maxlist([H|T], M) :-
430
+ T \= [],
431
+ maxlist(T, MT),
432
+ max(H, MT, M).
433
+
434
+ max(X, Y, M) :- X >= Y, !, M = X.
435
+ max(_, Y, Y).
436
+ """,
437
+ "sample_run": r"""
438
+ ?- maxlist([3,9,2,7,5], M).
439
+ M = 9.
440
+
441
+ ?- maxlist([-4,-1,-8], M).
442
+ M = -1.
443
+
444
+ ?- maxlist([42], M).
445
+ M = 42.
446
+
447
+ ?- maxlist([], M).
448
+ false.
449
+ """,
450
+ },
451
+ {
452
+ "number": 14,
453
+ "title": 'Insert at Nth position: insert(I, N, L, R)',
454
+ "aim": 'Write a PROLOG program to implement insert(I, N, L, R) that inserts an item I into Nth position of list L to generate a list R.',
455
+ "filename": 'p14_insert.pl',
456
+ "code": r"""
457
+ % Positions start at 1.
458
+
459
+ insert(I, 1, L, [I|L]).
460
+ insert(I, N, [H|T], [H|R]) :-
461
+ N > 1,
462
+ N1 is N - 1,
463
+ insert(I, N1, T, R).
464
+ """,
465
+ "sample_run": r"""
466
+ ?- insert(x, 3, [a,b,c,d], R).
467
+ R = [a, b, x, c, d].
468
+
469
+ ?- insert(x, 1, [a,b,c], R).
470
+ R = [x, a, b, c].
471
+
472
+ ?- insert(x, 4, [a,b,c], R).
473
+ R = [a, b, c, x].
474
+
475
+ ?- insert(x, 6, [a,b,c], R).
476
+ false.
477
+ """,
478
+ },
479
+ {
480
+ "number": 15,
481
+ "title": 'Delete Nth element: delete(N, L, R)',
482
+ "aim": 'Write a PROLOG program to implement delete(N, L, R) that removes the element on Nth position from a list L to generate a list R.',
483
+ "filename": 'p15_delete.pl',
484
+ "code": r"""
485
+ % Positions start at 1.
486
+
487
+ delete(1, [_|T], T).
488
+ delete(N, [H|T], [H|R]) :-
489
+ N > 1,
490
+ N1 is N - 1,
491
+ delete(N1, T, R).
492
+ """,
493
+ "sample_run": r"""
494
+ ?- delete(3, [a,b,c,d,e], R).
495
+ R = [a, b, d, e].
496
+
497
+ ?- delete(1, [a,b,c], R).
498
+ R = [b, c].
499
+
500
+ ?- delete(3, [a,b,c], R).
501
+ R = [a, b].
502
+
503
+ ?- delete(5, [a,b,c], R).
504
+ false.
505
+ """,
506
+ },
507
+ ]
508
+
509
+ # Drop the newline that follows each opening r""" above.
510
+ for _p in PRACTICALS:
511
+ _p["code"] = _p["code"].lstrip("\n")
512
+ _p["sample_run"] = _p["sample_run"].lstrip("\n")
513
+ del _p
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: prolog-practicals
3
+ Version: 1.0.0
4
+ Summary: 15 ready-to-run Prolog lab programs, saved to a roll-number folder on your Desktop from a simple menu
5
+ Author: Prateek Yadav
6
+ License-Expression: MIT
7
+ Keywords: prolog,swi-prolog,practicals,lab,students,artificial intelligence
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Topic :: Education
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # prolog-practicals
19
+
20
+ 15 ready-to-run Prolog lab programs. Pick one from a menu, type your roll
21
+ number, and the program is saved to a folder named after your roll number
22
+ on your Desktop.
23
+
24
+ ```
25
+ Desktop/
26
+ └── 23CS045/
27
+ ├── p01_family.pl
28
+ ├── p06_factorial.pl
29
+ └── ...
30
+ ```
31
+
32
+ Each saved file has a header with the practical's aim, your roll number and the
33
+ date, then the program, then a sample run as comments.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install prolog-practicals
39
+ ```
40
+
41
+ Requires Python 3.8 or newer. No other packages are needed. To run the saved
42
+ programs you need [SWI-Prolog](https://www.swi-prolog.org/download/stable).
43
+
44
+ ## Use
45
+
46
+ ```bash
47
+ prolog-practicals
48
+ ```
49
+
50
+ ```
51
+ ==============================================================
52
+ PROLOG PRACTICALS v1.0.0 15 ready-to-run programs
53
+ ==============================================================
54
+
55
+ 1. Family tree and family relationships
56
+ 2. Concatenate two lists: conc(L1, L2, L3)
57
+ ...
58
+ 15. Delete Nth element: delete(N, L, R)
59
+ A. Save ALL 15 practicals
60
+ Q. Quit
61
+
62
+ Choose a practical (1-15, A = all, Q = quit): 6
63
+ Enter your roll number: 23CS045
64
+ Saved: C:\Users\you\Desktop\23CS045\p06_factorial.pl
65
+ ```
66
+
67
+ If Windows says `'prolog-practicals' is not recognized`, Python's Scripts
68
+ folder is not on your PATH. Use this instead; it does the same thing:
69
+
70
+ ```bash
71
+ python -m prolog_practicals
72
+ ```
73
+
74
+ ### Options
75
+
76
+ | Command | What it does |
77
+ |---|---|
78
+ | `prolog-practicals` | Interactive menu |
79
+ | `prolog-practicals --list` | List all 15 practicals |
80
+ | `prolog-practicals --show 6` | Print the code of practical 6 |
81
+ | `prolog-practicals -q 6 -r 23CS045` | Save practical 6 for roll number 23CS045 without the menu |
82
+ | `prolog-practicals -q all -r 23CS045` | Save all 15 |
83
+ | `prolog-practicals --dir D:\labs` | Save under another folder instead of the Desktop |
84
+ | `prolog-practicals -f ...` | Overwrite existing files without asking |
85
+
86
+ ## Practicals included
87
+
88
+ 1. Family tree and family relationships
89
+ 2. Concatenate two lists: `conc(L1, L2, L3)`
90
+ 3. Reverse a list: `reverse(L, R)`
91
+ 4. Sum of two numbers
92
+ 5. Maximum of two numbers: `max(X, Y, M)`
93
+ 6. Factorial: `factorial(N, F)`
94
+ 7. Nth Fibonacci term: `generate_fib(N, T)`
95
+ 8. Power: `power(Num, Pow, Ans)`
96
+ 9. Multiplication: `multi(N1, N2, R)`
97
+ 10. List membership: `memb(X, L)`
98
+ 11. Sum of a list: `sumlist(L, S)`
99
+ 12. Even / odd length: `evenlength(List)`, `oddlength(List)`
100
+ 13. Maximum of a list: `maxlist(L, M)`
101
+ 14. Insert at Nth position: `insert(I, N, L, R)`
102
+ 15. Delete Nth element: `delete(N, L, R)`
103
+
104
+ ## Running a saved program
105
+
106
+ 1. Open SWI-Prolog.
107
+ 2. Load the file: **File → Consult** and pick it, or type
108
+ `?- consult('C:/Users/you/Desktop/23CS045/p06_factorial.pl').` (use forward slashes)
109
+ 3. Ask a query, e.g. `?- factorial(5, F).`
110
+
111
+ ## Use from Python
112
+
113
+ ```python
114
+ from prolog_practicals import get_code, PRACTICALS
115
+
116
+ print(get_code(6)) # factorial program
117
+ for p in PRACTICALS:
118
+ print(p["number"], p["title"])
119
+ ```
120
+
121
+ ## License
122
+
123
+ MIT
@@ -0,0 +1,10 @@
1
+ prolog_practicals/__init__.py,sha256=0z0-h2q3eHlissiCbMiuHuduZl4k8BW5DFbXl0zm_D4,798
2
+ prolog_practicals/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ prolog_practicals/cli.py,sha256=Si5YWPh47A6a9nnU2HePERyOsit_eRGo-ZvzeoOu1pE,11365
4
+ prolog_practicals/practicals.py,sha256=Domahk0tI4i9NDkwy1fZXXH9BSDGlGkcQwRajEv4mhk,10963
5
+ prolog_practicals-1.0.0.dist-info/licenses/LICENSE,sha256=r5NTFe2mq12Qgx6CqiGt4OOIJYxe6Alowz9hmDFhv6g,1070
6
+ prolog_practicals-1.0.0.dist-info/METADATA,sha256=IkJx-oCpr7HJPLng4j7zZEa9-amkUIPTC0ab9OJMZWw,3714
7
+ prolog_practicals-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ prolog_practicals-1.0.0.dist-info/entry_points.txt,sha256=hJMeuGMlShgtpb0e89SX2zuYH7_WjAgZyj_Tmud-Tx0,65
9
+ prolog_practicals-1.0.0.dist-info/top_level.txt,sha256=lh-qznF8w3cm7F_r7BDOaP5ovstFWhYoGWabwlMjcQE,18
10
+ prolog_practicals-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prolog-practicals = prolog_practicals.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prateek Yadav
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ prolog_practicals