Utoljára aktív 1715846539

practical-file.tex Eredeti
1%! Author = Sujal Singh
2%! Date = 5/8/24
3
4% Preamble
5%! suppress = FileNotFound
6\documentclass[11pt]{ipu-python}
7\usepackage[
8 pdftitle={Programming in Python Practical File},
9 pdfsubject={Programming in Python Practical File},
10 pdfauthor={Sujal Singh},
11 pdfdisplaydoctitle,
12 hidelinks,
13]{hyperref}
14
15% Packages
16\usepackage{amsmath}
17
18\graphicspath{figures/}
19
20% Document
21\makeindex
22\begin{document}
23 \maketitle
24 % ---------------------------------------------------------------------------------------------------------------- %
25
26 % ---------------------------------------------------------------------------------------------------------------- %
27 \question{%
28 Write a program to perform string maniuplation operations using set of pre-defined functions such as:
29 \begin{itemize}
30 \item find()
31 \item upper()
32 \item len()
33 \item max() and min()
34 \item fetching specific content from string
35 \end{itemize}}\vspace*{10pt}
36 \begin{code}
37 {Program}{python}
38string = "Hello, World!"
39
40print(
41 f'string: "{string}"\n',
42 f'find("llo"): {string.find("llo")}',
43 f'upper(): {string.upper()}',
44 f'len(): {len(string)}',
45 f'max(): "{max(string)}"',
46 f'min(): "{min(string)}"',
47 f'fetching "llo": "{string[(start := string.find("llo")):start + len("llo")]}"',
48 sep="\n"
49)
50 \end{code}
51 \begin{code}
52 {Output}{text}
53string: "Hello, World!"
54
55find("llo"): 2
56upper(): HELLO, WORLD!
57len(): 13
58max(): "r"
59min(): " "
60fetching "llo": "llo"
61 \end{code}
62 % ---------------------------------------------------------------------------------------------------------------- %
63
64 % ---------------------------------------------------------------------------------------------------------------- %
65 \\~\vfill%
66 \question{%
67 Write a program to test and check the mathematical functions such as:
68 \begin{itemize}
69 \item ciel()
70 \item sqrt()
71 \item pow()
72 \item factorial()
73 \end{itemize}}\vfill
74 \newpage
75 \begin{code}
76 {Program}{python}
77from math import ceil, sqrt, pow, factorial
78
79num = 3.14
80
81print(
82 f"num: {num}\n",
83 f"ceil(num): {ceil(num)}",
84 f"sqrt(num): {sqrt(num)}",
85 f"pow(num, 2): {pow(num, 2)}",
86 f"factorial(5): {factorial(5)}",
87 sep="\n"
88)
89 \end{code}
90 \begin{code}
91 {Output}{text}
92num: 3.14
93
94ceil(num): 4
95sqrt(num): 1.772004514666935
96pow(num, 2): 9.8596
97factorial(5): 120
98 \end{code}
99 % ---------------------------------------------------------------------------------------------------------------- %
100
101 % ---------------------------------------------------------------------------------------------------------------- %
102 \\~\\%
103 \question{Write a program that receives a number as input from user and returns if it's an odd or even number.}
104 \begin{code}
105 {Program}{python}
106num = int(input("Enter an integer: "))
107print(f"{num} is {'even' if num % 2 == 0 else 'odd'}.")
108 \end{code}
109 \begin{code}
110 {Output}{text}
111Enter an integer: 42
11242 is even.
113 \end{code}
114 % ---------------------------------------------------------------------------------------------------------------- %
115
116 % ---------------------------------------------------------------------------------------------------------------- %
117 \\~\\
118 \question{Write a program that receives input from the user to calculate the area of a triangle.}
119 \begin{code}
120 {Program}{python}
121base = int(input("Enter base length of triangle(m): "))
122height = int(input("Enter height of triangle(m): "))
123print("area =", 0.5 * base * height)
124 \end{code}
125 \begin{code}
126 {Output}{text}
127Enter base length of triangle(m): 5
128Enter height of triangle(m): 4
129area = 10.0
130 \end{code}
131 \newpage
132 % ---------------------------------------------------------------------------------------------------------------- %
133
134 % ---------------------------------------------------------------------------------------------------------------- %
135 \question{Write a program that receives input from the user to calculate the area of a square.}
136 \begin{code}
137 {Program}{python}
138side = int(input("Enter side length of square(m): "))
139print(f"Area of square of side length {side} is {side * side}.")
140 \end{code}
141 \begin{code}
142 {Output}{text}
143Enter side length of square(m): 4
144Area of square of side length 4 is 16.
145 \end{code}
146 % ---------------------------------------------------------------------------------------------------------------- %
147
148 % ---------------------------------------------------------------------------------------------------------------- %
149 \\~\\
150 \question{Write a program that receives input from the user to calculate the area of a rectangle.}
151 \begin{code}
152 {Program}{python}
153length = int(input("Enter length: "))
154breadth = int(input("Enter breadth: "))
155print(f"Area of rectangle having length {length} and breadth {breadth} is {length * breadth}.")
156 \end{code}
157 \begin{code}
158 {Output}{text}
159Enter length: 5
160Enter breadth: 4
161Area of rectangle having length 5 and breadth 4 is 20.
162 \end{code}
163 % ---------------------------------------------------------------------------------------------------------------- %
164
165 % ---------------------------------------------------------------------------------------------------------------- %
166 \\~\\
167 \question{Write a program to check if the input string is a palindrome or not.}
168 \begin{code}
169 {Program}{python}
170original = input("Enter a string: ")
171print("Given string is", "a" if original == original[::-1] else "not a", "palindrome.")
172 \end{code}
173 \begin{code}
174 {Output}{text}
175Enter a string: ehehe
176Given string is a palindrome.
177 \end{code}
178 % ---------------------------------------------------------------------------------------------------------------- %
179
180 % ---------------------------------------------------------------------------------------------------------------- %
181 \question{Write a program that receives marks of a student for a subject as input and assigns a grade A$\|$B$\|$C%
182 $\|$D$\|$E$\|$F.}
183 \begin{code}
184 {Program}{python}
185offset = 9 - int(input("Enter marks for subject (0 - 100): ")) // 10
186# Makes negative offset values equal zero
187positive_offset = (abs(offset) + offset) // 2
188print(chr(65 + positive_offset) if offset <= 5 else "F")
189 \end{code}
190 \begin{code}
191 {Output}{text}
192Enter marks for subject (0 - 100): 90
193A
194 \end{code}
195 % ---------------------------------------------------------------------------------------------------------------- %
196
197 % ---------------------------------------------------------------------------------------------------------------- %
198 \question{Write a program to compute the GCD of two numbers.}
199 \begin{code}
200 {Program}{python}
201def gcd(a, b):
202 # Using the Euclidean algorithm
203 if a < b:
204 return gcd(a, b - a)
205 elif a > b:
206 return gcd(a - b, b)
207 return a # if a equals b, then gcd is the same as a and b.
208
209
210print(gcd(
211 int(input("Enter first number: ")),
212 int(input("Enter second number: "))
213))
214 \end{code}
215 \begin{code}
216 {Output}{text}
217Enter first number: 10
218Enter second number: 4
2192
220 \end{code}
221 % ---------------------------------------------------------------------------------------------------------------- %
222
223 % ---------------------------------------------------------------------------------------------------------------- %
224 \\~\\
225 \question{Write a program to check if the given number is an Armstrong number or not. Examples of Armstrong number
226 are 153, 370, 371 etc.}
227 \begin{code}
228 {Program}{python}
229num = int(str_num := input("Enter a number: "))
230
231power = len(str_num)
232print(
233 "Given number is",
234 "not an" if sum([int(digit) ** power for digit in str_num]) != num else "an",
235 "Armstrong number."
236)
237 \end{code}
238 \begin{code}
239 {Output}{text}
240Enter a number: 153
241Given number is an Armstrong number.
242 \end{code}
243 % ---------------------------------------------------------------------------------------------------------------- %
244
245 % ---------------------------------------------------------------------------------------------------------------- %
246 \newpage
247 \question{Write a program to check if the input year is a leap year or not.}
248 \begin{code}
249 {Program}{python}
250from calendar import isleap
251
252print(
253 "Given year is",
254 "a" if isleap(int(input("Enter a year: "))) else "not a",
255 "leap year."
256)
257 \end{code}
258 \begin{code}
259 {Output}{text}
260Enter a year: 2024
261Given year is a leap year.
262 \end{code}
263 % ---------------------------------------------------------------------------------------------------------------- %
264
265 % ---------------------------------------------------------------------------------------------------------------- %
266 \\~\\
267 \question{Write a program to compute factorial of a given number.}
268 \begin{code}
269 {Program}{python}
270def fac(n):
271 if n == 0:
272 return 1
273 return n * fac(n - 1)
274
275
276print(fac(int(input("Enter a number: "))))
277 \end{code}
278 \begin{code}
279 {Output}{text}
280Enter a number: 5
281120
282 \end{code}
283 % ---------------------------------------------------------------------------------------------------------------- %
284
285 % ---------------------------------------------------------------------------------------------------------------- %
286 \\~\\
287 \question{Write a program to generate the Fibonacci sequence till 100.}
288 \begin{code}
289 {Program}{python}
290a, b = 0, 1
291print(a, end=" ")
292while b <= 100:
293 print(b, end=" ")
294 a, b = b, b + a
295 \end{code}
296 \begin{code}
297 {Output}{text}
2980 1 1 2 3 5 8 13 21 34 55 89
299 \end{code}
300 \vfill
301 % ---------------------------------------------------------------------------------------------------------------- %
302
303 % ---------------------------------------------------------------------------------------------------------------- %
304 \newpage
305 \question{Write a program to print the multiplication table of a given number.}
306 \begin{code}
307 {Program}{python}
308def table(n):
309 for i in range(1, 11):
310 print(f"{n} x {i} = {n * i}")
311
312
313table(int(input("Enter a number: ")))
314 \end{code}
315 \begin{code}
316 {Output}{text}
317Enter a number: 3
3183 x 1 = 3
3193 x 2 = 6
3203 x 3 = 9
3213 x 4 = 12
3223 x 5 = 15
3233 x 6 = 18
3243 x 7 = 21
3253 x 8 = 24
3263 x 9 = 27
3273 x 10 = 30
328 \end{code}
329 % ---------------------------------------------------------------------------------------------------------------- %
330
331 % ---------------------------------------------------------------------------------------------------------------- %
332 \question{Write a program to create two lists and perform the following operation's:%
333 \begin{enumerate}
334 \item Add the elements of the two list.
335 \item Compare the contents of the two list.
336 \item Find the number of elements in the list.
337 \item Sort the elements of the list.
338 \item Reverse the contents of the list.
339 \end{enumerate}}
340 \begin{code}
341 {Program}{python}
342a, b = [1, 3, 2, 4, 5], [6, 5, 7, 9, 8]
343print(
344 [x + y for x, y in zip(a, b)], # Only works for lists having same lengths
345 a[2] == a[3],
346 len(a), len(b),
347 sorted(b),
348 list(reversed(a)),
349 sep="\n"
350)
351 \end{code}
352 \newpage
353 \begin{code}
354 {Output}{text}
355[7, 8, 9, 13, 13]
356False
3575
3585
359[5, 6, 7, 8, 9]
360[5, 4, 2, 3, 1]
361 \end{code}
362 % ---------------------------------------------------------------------------------------------------------------- %
363
364 % ---------------------------------------------------------------------------------------------------------------- %
365 \question{Write a Program to create and display the content of the tuple. Initialize the tuple with the name of
366 the cities. Display content of the tuple along with name/index positions of the cities.}
367 \begin{code}
368 {Program}{python}
369cities = ("New Delhi", "Pune", "Jaipur", "Amritsar")
370print(cities)
371print(*[f"({i}): {name}" for i, name in enumerate(cities)], sep="\n")
372 \end{code}
373 \begin{code}
374 {Output}{text}
375('New Delhi', 'Pune', 'Jaipur', 'Amritsar')
376(0): New Delhi
377(1): Pune
378(2): Jaipur
379(3): Amritsar
380 \end{code}
381 % ---------------------------------------------------------------------------------------------------------------- %
382
383 % ---------------------------------------------------------------------------------------------------------------- %
384 \question{Write a program to create an array of even numbers till 14. Display the contents of array, compute the
385 length of the array and also show how to delete a element from the desired position from the array.}
386 \begin{code}
387 {Program}{python}
388array = list(range(0, 15, 2))
389print(array)
390print(len(array))
391del array[3]
392print(array)
393 \end{code}
394 \begin{code}
395 {Output}{text}
396[0, 2, 4, 6, 8, 10, 12, 14]
3978
398[0, 2, 4, 8, 10, 12, 14]
399 \end{code}
400 % ---------------------------------------------------------------------------------------------------------------- %
401
402 % ---------------------------------------------------------------------------------------------------------------- %
403 \question{Using \texttt{filter()} function, write a program to filter the elements which are greater than 9.}
404 \begin{code}
405 {Program}{python}
406from random import randrange
407
408data = [randrange(0, 20) for _ in range(20)]
409print(list(filter(lambda x: x > 9, data)))
410 \end{code}
411 \newpage
412 \begin{code}
413 {Output}{text}
414[12, 12, 17, 14, 15, 16, 12, 13, 11, 15, 14, 12]
415 \end{code}
416 % ---------------------------------------------------------------------------------------------------------------- %
417
418 % ---------------------------------------------------------------------------------------------------------------- %
419 \\~\\
420 \question{Using \texttt{filter()} function, write a program to filter the elements which are greater than 9.}
421 \begin{code}
422 {Program}{python}
423from random import randrange
424
425data = [randrange(0, 100) for _ in range(30)]
426print(data)
427print(list(filter(lambda x: x % 5 == 0, data)))
428 \end{code}
429 \begin{code}
430 {Output}{text}
431[94, 39, 28, 55, 56, 39, 1, 53, 82, 24, 71, 20, 22, 36, 27, 40, 33, 67, 42, 94, 51, 41, 50, 3, 71, 15, 68, 29, 78, 79]
432[55, 20, 40, 50, 15]
433 \end{code}
434 % ---------------------------------------------------------------------------------------------------------------- %
435
436 % ---------------------------------------------------------------------------------------------------------------- %
437 \\~\\
438 \question{Write a program to create a file called “input.txt”, perform write/read operation on it with a string
439 ``Computer Science''.}
440 \begin{code}
441 {Program}{python}
442with open("input.txt", "w") as file:
443 file.write("Computer Science")
444
445with open("input.txt") as file:
446 print(file.read())
447 \end{code}
448 \begin{code}
449 {Output}{text}
450Computer Science
451 \end{code}
452 % ---------------------------------------------------------------------------------------------------------------- %
453
454 % ---------------------------------------------------------------------------------------------------------------- %
455 \\~\\
456 \question{Write a program to create a file called “input.txt”, initialize it with a string of your choice and
457 perform the read operation to read only the first 3 characters from the file.}
458 \begin{code}
459 {Program}{python}
460with open("input.txt", "w") as file:
461 file.write("Hello, World!")
462
463with open("input.txt") as file:
464 print(file.read(3))
465 \end{code}
466 \begin{code}
467 {Output}{text}
468Hel
469 \end{code}
470 \newpage
471 % ---------------------------------------------------------------------------------------------------------------- %
472
473 % ---------------------------------------------------------------------------------------------------------------- %
474 \question{Using NumPy, write a program to create 1-dimensional array, load it with numbers, and perform the
475 operation of iteration and slicing on it.}
476 \begin{code}
477 {Program}{python}
478import numpy as np
479
480print(arr := np.array([2, 3, 4, 1, 7, 6], np.int32))
481for e in np.nditer(arr):
482 print(e, end=" ")
483print()
484print(arr[2:5])
485 \end{code}
486 \begin{code}
487 {Output}{text}
488[2 3 4 1 7 6]
4892 3 4 1 7 6
490[4 1 7]
491 \end{code}
492 % ---------------------------------------------------------------------------------------------------------------- %
493
494 % ---------------------------------------------------------------------------------------------------------------- %
495 \\~\\
496 \question{Using NumPy, write a program to create multidimensional array, load it with the numbers and display the
497 content of it.}
498 \begin{code}
499 {Program}{python}
500import numpy as np
501
502arr = np.array([[1, 2, 3], [4, 5, 6]])
503print(arr)
504 \end{code}
505 \begin{code}
506 {Output}{text}
507[[1 2 3]
508 [4 5 6]]
509 \end{code}
510 % ---------------------------------------------------------------------------------------------------------------- %
511
512 % ---------------------------------------------------------------------------------------------------------------- %
513 \\~\\
514 \question{Using NumPy, write a program to create two 1-dimensional array and perform the operation of iteration,
515 sorting the contents of array and concatenating the contents of the array.}
516 \begin{code}
517 {Program}{python}
518import numpy as np
519
520arr = np.array([9, 4, 6, 2, 7])
521
522for e in np.nditer(arr):
523 print(e)
524
525print(np.sort(arr))
526print(np.concatenate((arr, np.array([38, 77, 29, 84, 75]))))
527 \end{code}
528 \begin{code}
529 {Output}{text}
5309
5314
5326
5332
5347
535[2 4 6 7 9]
536[ 9 4 6 2 7 38 77 29 84 75]
537 \end{code}
538 % ---------------------------------------------------------------------------------------------------------------- %
539
540 % ---------------------------------------------------------------------------------------------------------------- %
541 \\~\\
542 \question{Using NumPy, initialize an array and display its dimensionality.}
543 \begin{code}
544 {Program}{python}
545import numpy as np
546
547arr = np.array([[[1, 2], [3, 4]], [[5, 6], [6, 7]], [[8, 9], [9, 10]]])
548print(arr.shape)
549 \end{code}
550 \begin{code}
551 {Output}{text}
552(3, 2, 2)
553 \end{code}
554 % ---------------------------------------------------------------------------------------------------------------- %
555
556 % ---------------------------------------------------------------------------------------------------------------- %
557 \\~\\
558 \question{Using Pandas, create a dataframe, initialize it with the contents such as your enrollment Number and
559 name and display them.}
560 \begin{code}
561 {Program}{python}
562import numpy as np
563import pandas as pd
564
565class_list = pd.DataFrame(np.array([
566 ["Name", "Enrollment Number"],
567 ["Alice", 1],
568 ["Bob", 2],
569 ["Bob", 3]
570]))
571
572print(class_list)
573 \end{code}
574 \begin{code}
575 {Output}{text}
576 0 1
5770 Name Enrollment Number
5781 Alice 1
5792 Bob 2
5803 Bob 3
581 \end{code}
582 % ---------------------------------------------------------------------------------------------------------------- %
583
584 % ---------------------------------------------------------------------------------------------------------------- %
585 \\~\\
586 \question{Create 2 arrays, using MatPlotLib, plot the graph with the content of the two arrays, with coordinates
587 plotted on x-axis and y-axis.}
588 \begin{code}
589 {Program}{python}
590import numpy as np
591import matplotlib.pyplot as plt
592from random import randint
593
594points = np.array([
595 [randint(0, 100) for _ in range(50)],
596 [randint(0, 100) for _ in range(50)],
597])
598
599fig, ax = plt.subplots()
600ax.plot(points[0], points[1], 'ro')
601plt.show()
602 \end{code}
603 \outputfigure{q27}
604 % ---------------------------------------------------------------------------------------------------------------- %
605\end{document}