#import "tpl.typ": * #show: body => apply(body) #show heading: set text(font: "New Computer Modern Sans", weight: 450) #let semibold(body) = text(weight: 600, body) #let roman(body) = text(weight: 400, body) // #text(size: 1.3em, font: "New Computer Modern Sans", align(center)[#semibold[Practical Assignments] \ _on_ \ #semibold[Programming in Python Lab]]) #text(size: 1.3em, font: "New Computer Modern Sans", align(center)[#semibold[Programming in Python Lab]]) #align(center, text(size: 1.1em)[DSE-B-1 \ Use of user defined functions are encouraged wherever applicable]) #set enum(full: true, numbering: (..args) => { let patterns = ("1.", "(a)") let pattern = patterns.at(calc.min(args.pos().len(), patterns.len()) - 1) numbering(pattern, args.pos().last()) }) #let nntiv = body => [ #set text(size: 0.9em, fill: rgb("#777777")) \ #body ] #set raw(lang: "python") #set par(justify: true) #set heading(numbering: "1 ") #heading(numbering: none)[0 #h(0.25em) Definitions] - _Interactive interpreter_ allows the user to run one or more lines of code interactively, immediately showing the result and output of code. - _Programs_ are to be written and saved in text files, usually with the file extension `.py`, and run using the Python executable from CLI (Command Prompt or Powershell in Windows, shell in Linux etc.) or the inbuilt IDLE. = Basic Python Syntax + Using the Python _interactive interpreter_ as a basic calculator, demonstrate the order of operations using parentheses for arithmetic operations. + Using the Python _interactive interpreter_, demonstrate at least 15 functions in the math module. #nntiv[For example, to find the GCD of two numbers, area and perimeter of circle using `math.pi` etc.] + Using the Python _interactive interpreter_, demonstrate the use of complex numbers and their operations on them. #nntiv[For example, in finding the modulus and phase angle (amplitude or argument) of a complex number.] + Write a Python program to take two numbers from the user and show their the sum, product, difference and the GCD. + Write a Python program to demonstrate the use of _regular expressions_ using `re.split`, `re.join`, `re.search` and `re.match` methods from `re` module. + Write a program to take two floating point numbers as input from the user. Concatenate the integral parts of the two numbers and display them, also display the sum of the input floating point numbers rounded upto 2 decimal places. + Write a program to divide two numbers and check if the digits at one’s place of the quotient and remainder are equal. = Decision Control Statements + Write a Python program to calculate the sum a list of number of (i) even length and then (ii) any length, using `while` loop: at each step, add $k$th number from the start and end of the list and display it, for $k$ from $0$ to half the length the list. #nntiv[For example: if the list is `[1, 2, 3, 4, 5, 6]`, the program should output `1 + 6`, `2 + 5`, and `3 + 4` in separate lines, and the result of the addition `21`.] + Write a Python program to sperate prime numbers from a given list of numbers and store them in another list. + Write a Python program to demonstrate keyword argument `key` of `sum()`, `min()`, `max()`, and `sort()` functions using `lambda`s. + Write a Python program to design the following random number guessing game. A random number from 1 to 10 (inclusive) is selected as a secret number, then the user is prompted to guess the number. If the user’s guess matches the secret number, the game ends with an appropriate message, otherwise the user is asked to try again. After 3 unsuccessful guesses, the user loses and the game ends with an appropriate message revealing the secret number. At the end of the game, ask the user whether to play again. (Use the `random` module to obtain the secret number.) + Write a Python program to generate the calendar of a month given the start day (`1` for Sunday, `2` for Monday, ... `7` is Saturday) and the number of days in the month. #nntiv[An example:] #[ #show raw: block.with(inset: 0pt, fill: white, width: 20em, outset: 0pt) #show: it => align(center, it) ```text Enter the starting day: 5 Enter the number of days in the month: 30 Calender for this month: SUN MON TUE WED THU FRI SAT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ```] + Write a Python program to take input from user as a string and count the lowercase characters, uppercase characters and digits in it. + #table( columns: (1fr, 4em), stroke: none, inset: 0pt, gutter: 0pt, column-gutter: 5pt, [Write a Python program to print the following star pattern of the given size. \ #nntiv[Example (with size 4):]], [ #set par(leading: 0em) #set block(inset: 0pt, width: 4em, outset: 0pt) ```text **** * * * * **** ``` ]) = Strings + Write a Python program to ask the user for two strings, print a new string where the first string is reversed, and the second string is converted to upper case, only using string slicing and `+` operator. #nntiv[Sample strings: `Pets`, `party`, output: `steP PARTY`.] + Write a Python program to from a list of words, join all the words in the odd and even indices to form two strings using list slicing and `join` method. #nntiv[Example: for a list `['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']`, the result are: `'abcghimnotuv'` and `'defjklpqrswxyz'`.] + #text(fill: red, sym.convolve) Write a Python program to input your name in a string, separate the first name and last name using the slice operator with negative indexing, and display your name in reverse using a formatted string. + Write a Python program to implement a function that works like `str.count()` method. + Write a Python program to take input a string and display it after removing all the vowels. + Write a Python program that take a plain text string and generate cyphertext by using $k$th next character with wrap around for each character for a given constant key value $k$. #nntiv[Also known as _Caesar Cipher_. \ Example: for key $k = 23$, the message `"The quick brown fox jumps over the lazy dog."` encrypts to `"Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald."`.] + Write a Python program to sperate the username and domain name of an email address. #{ /* + Write a Python program to separate the `local-part` and `domain` of an email address given as per RFC 5322 format for `addr-spec` (§3.4.1): ```text addr-spec = local-part "@" domain local-part = dot-atom / quoted-string / obs-local-part domain = dot-atom / domain-literal / obs-domain dtext = %d33-90 / ; Printable US-ASCII %d94-126 / ; characters not including obs-dtext ; "[", "]", or "\" FWS = ([*WSP CRLF] 1*WSP) / obs-FW ; Folding white space ctext = %d33-39 / ; Printable US-ASCII %d42-91 / ; characters not including %d93-126 / ; "(", ")", or "\" obs-ctext ccontent = ctext / quoted-pair / comment comment = "(" *([FWS] ccontent) [FWS] ")" CFWS = (1*([FWS] comment) [FWS]) / FWS atext = ALPHA / DIGIT / ; Printable US-ASCII "!" / "#" / ; characters not including "$" / "%" / ; specials. Used for atoms. "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" atom = [CFWS] 1*atext [CFWS] dot-atom-text = 1*atext *("." 1*atext) dot-atom = [CFWS] dot-atom-text [CFWS] qtext = %d33 / ; Printable US-ASCII %d35-91 / ; characters not including %d93-126 / ; "\" or the quote character obs-qtext quoted-pair = ("\" (VCHAR / WSP)) / obs-qp obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) qcontent = qtext / quoted-pair quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS] word = atom / quoted-string obs-local-part = word *("." word) obs-domain = atom *("." atom) obs-dtext = obs-NO-WS-CTL / quoted-pair obs-NO-WS-CTL = %d1-8 / ; US-ASCII control %d11 / ; characters that do not %d12 / ; include the carriage %d14-31 / ; return, line feed, and %d127 ; white space characters ``` */} = Lists + Write a Python program to simulate a stack and a queue using lists using functions. + Write a Python program to find all the odd numbers and numbers divisible by 3 from a list of numbers using list comprehension. + Write a Python program to find the third largest number in a list of numbers without sorting. + Write a Python program to generate a list of numbers `items` using list comprehension as per the following description: $ "items"[ i ] = cases( i^2 quad "if " i "is even", i^3 quad "if " i "is odd", ) $ where $i$ denotes the index of the list. + Write a Python program to use the `map()` method to square each number in a list. + Write a Python program to remove all duplicate items in a list. = Tuples + Write a Python program that, given sequences of first and last names, generate another sequence which contains the full name of each person, using the `zip()` function. + Write a Python program to take a nested tuple with the name, Roll No. and marks of some students and find the name of the student having highest marks. + Write a Python program to take a list of numbers (both positive and negative) and make a new tuple out from this list with only the positive values using generator expression. + Write a Python program to add variable number of arguments (scatter and gather) using the `*` symbol. = Sets + Write a Python program to implement the Jaccard and cosine similarity of two sets using the set union and intersection operations. + Write a Python program that creates two sets of even numbers in the range 1 to 50 and composite numbers in the range 1 to 50 to demonstrate the use of `all()`, `issuperset()`, `len()`, `sum()` methods on the sets. + Write a Python program that generates a set of prime numbers and another set of odd numbers to demonstrate the result of _union_, _intersection_, _difference_, _symmetric difference_ operations on these sets. + Write a Python program that creates two sets: squares and cubes in the range 1 to 50 to demonstrate the use of `update()`, `pop()`, `remove()`, `add()` and `clear()` methods. + Write a Python program to demonstrate the use of frozensets. = Dictionaries + Write a Python function which takes a string and returns a dictionary containing the number of words and letters in the provided string. + Write a Python program to invert a dictionary such the previous keys become values and values become keys. #nntiv[For example: if the initial and inverted dictionaries are `d1` and `d2`, where `d1 = {1: 'a', 2: 'b', 3: 120}`, then `d2 = {'a': 1, 2: 'b', 120: 3}`.] + Write a Python program with a function to generate the Fibonacci numbers in + Exponential time using the naïve algorithm. + Linear time using dynamic programming (memoization) with a dictionary. + Write a Python program to generate a dictionary where each key is a number and the corresponding value is the number’s square using dictionary comprehension. + Write a Python program to store a sparse matrix as a dictionary. + Write a Python program that combines two lists, one of keys, and another of values, into a dictionary. = User-Defined Functions + Write a Python program to implement quick sort and merge sort algorithms to sort lists of numbers. + Write a Python program that displays the Pascal’s triangle of a given size. + Three positive integers $a$, $b$, and $c$ are Pythagorean triples if $a^2 + b^2 = c^2$. Write a Python program with a function to generate all Pythagorean triples in a certain range. + Write two functions that simulate the toss of a fair coin, and the roll of an unbiased $n$ sided die using the `random` module. + Modify the previous assignment. Now the coin and the die are not fair, with each outcome having a given probability. = File Handling; `sys`, `pickle` and `csv` modules + Basic file operations. Explore the different file modes. + Emulate the unix `cp`, `grep`, `cat` programs in Python. In each case, the user should pass the arguments to the program as command line arguments. + Use pickle for persistent storage of variables. = Object Oriented Programming + Create a `Graph` class to store and manipulate graphs. It should have the following functions: + Read an edge list file, where each edge `(u, v)` appears exactly once in the file as space separated values. + Add and remove nodes and edges. + Print nodes, and edges in a user readable format. + Computes basic statistics of the graph like degree distribution, clustering coefficient, and the number of connected components. + Finding all the neighbors of a node. + Finding all the connected components and storing them as individual Graph objects inside the class. + Finding single source shortest paths using Breadth First Search. + Make a `DiGraph` class to handle directed graphs which inherits from the `Graph` class. In addition to all of the functionalities of 1, it should support the following operations + Finding the predecessors and successors of a node. + Creating a new `DiGraph` object where all the edges are reversed. + Finding the strongly connected components. + Extend 1 and 2 to handle weighted graphs, and implement Dijkstra’s and Floyd-Warshall algorithms to compute the single source and all pairs shortest paths. + Use the graph containers in 1, 2, and 3 to implement additional graph algorithms.