0% found this document useful (0 votes)
2 views3 pages

Python Exercises: Functions & Data Structures

Artificial Intelligence Lab 1

Uploaded by

21b-039-cs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Python Exercises: Functions & Data Structures

Artificial Intelligence Lab 1

Uploaded by

21b-039-cs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exercise 1

In [30]: def table(num): #for loop concept


for i in range(1,11):
print(num, "*",i, "=", num* i)
def lst(): #list concept
lst_1= []
n = int(input("Enter number of elements"))
for i in range(n):
element=input("Enter elements")
lst_1.append(element)
return lst_1

def dict(): #dictionary concept


dictionary = {}
n = int(input("Enter number of key-value pairs: "))
for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
dictionary[key] = value
return dictionary

In [8]: table(5)

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

In [20]: lst()

Out[20]: ['1', '2', '3']

In [22]: dict()

Out[22]: {'Name': 'Taha', 'Roll No': '21B-039-CS'}

Exercise 2
In [90]: def reverse(strg):
if len(strg) == 0:
return

var = strg[0]
reverse(strg[1:])
print(var, end='')

In [91]: reverse("Taha")

ahaT

Exercise 3
In [42]: nums=[23,5,1,2,3,25,22]

In [43]: def minmax(nums):


min_num = 1000000
max_num = 0
for num in nums:
if num>max_num:
max_num=num
if num<min_num:
min_num=num
print(tuple([min_num,max_num]))

(1, 25)

Exercise 4
In [55]: import numpy as np

def mulp_inverse(lst, row=0, col=0):


if row == len(lst):
return lst

if col == len(lst[row]):
return mulp_inverse(lst, row + 1, 0)

if lst[row][col] != 0:
lst[row][col] = 1 / lst[row][col]

return mulp_inverse(lst, row, col + 1)

In [57]: input_list = [[5, 2], [4, 1]]


result = mulp_inverse_recursive(input_list)
print(result)

[[0.2, 0.5], [0.25, 1.0]]

Exercise 5
In [265… lst=[1,2,3,3,4,5]
unique_lst=[]

In [266… for numbers in lst:


if numbers not in unique_lst:
unique_lst.append(numbers)
print(unique_lst)

[1, 2, 3, 4, 5]

Exercise 6
In [23]: def palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return palindrome(s[1:-1])

In [27]: palindrome("racecar")

Out[27]: True

In [28]: palindrome("TAHA")

Out[28]: False

Common questions

Powered by AI

The 'minmax' function has a computational complexity of O(n), where n is the number of elements in the list. This linear complexity arises from the need to iterate through the entire list once to evaluate each element for minimum and maximum comparison. Its efficiencies lie in its simplicity and minimal overhead beyond basic comparisons .

The 'table' function uses a for loop to iterate from 1 to 10, multiplying a given number 'num' by each iterator 'i'. This results in printing the multiplication table for 'num' as a series of multiplied results, clearly formatted as '<num> * <i> = <product>'. This demonstrates simple iteration for repetitive arithmetic output .

The 'mulp_inverse' function specifically checks if list elements are non-zero before computing their multiplicative inverse. This conditional operation ensures that singularities (division by zero) are avoided, maintaining numerical stability. The implication is that zero elements will be left unchanged in the list, impacting further operations dependent on inversed values .

A limitation of the 'dict' function is its relies on manual input for both keys and values, which could lead to input errors or inconsistencies. It lacks validation mechanisms, which could result in duplicate keys being overwritten or mismatched/malformed data impacting subsequent use. Moreover, it doesn’t handle non-string data types effectively nor does it preprocess inputs for consistent formatting .

The purpose of initializing 'min_num' to a very large number (1000000) and 'max_num' to 0 is to ensure that any number in the list will be correctly evaluated as smaller or larger, respectively, during the first comparisons. These initial values ensure that valid minimum and maximum values are found. Incorrect initialization could result in incorrect min/max if the range of numbers includes values outside the initial max/min values .

The 'lst' function prompts users to input the number of list elements ('n') and then iteratively collects each element through user input to append these into 'lst_1'. This constructs a list based on user-supplied data, resulting in a dynamic list structure determined entirely by runtime input .

The 'mulp_inverse' function recursively iterates through a 2D list (matrix) and replaces each non-zero element with its multiplicative inverse. The parameters 'row' and 'col' represent indices currently being processed; they advance the traversal across each row and to the next row upon reaching the end of a row (when 'col' equals the row length). This allows traversing the entire matrix recursively and modifying it in place .

The condition 'if s[0] != s[-1]' checks if the first and last characters of the string are different, indicating that the string is not a palindrome. If they are unequal, the function returns False immediately, terminating further checks. This check helps in recursively confirming that the string reads the same forward and backward .

The 'reverse' function works by recursively calling itself with the substring excluding the first character until the string is empty. As the recursion unwinds, it prints the first character of each substring, effectively outputting the characters in reverse. This approach utilizes the call stack to defer the printing until the base case (empty string) is reached .

Uniqueness is ensured by iterating over the original list and appending each element to 'unique_lst' only if that element is not already present in 'unique_lst'. This preserves the order of first occurrence, maintaining the original order of the first unique elements encountered due to the linear traversal through the list .

You might also like