Академический Документы
Профессиональный Документы
Культура Документы
SESSION-2
def test_duplicate(array_nums):
nums_set = set(array_nums)
return len(array_nums) != len(nums_set)
print(test_duplicate([1,2,3,4,5]))
print(test_duplicate([1,2,3,4, 4]))
print(test_duplicate([1,1,2,2,3,3,4,4,5]))
27.Write a Python program to get the current memory address and the length in elements of the buffer used to
hold an array?s contents and also find the size of the memory buffer in bytes
28. Write a Python program to convert temperatures to and from celsius, fahrenheit. [ Formula : c/5 = f-32/9 [ where c
= temperature in celsius and f = temperature in fahrenheit ]Expected Output :60°C is 140 in Fahrenheit 45°F is 7 in Celsius
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.)
: ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
30. Write a Python function that checks whether a passed string is palindrome or not. Go to the editor Note: A
palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
31. Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a
hyphen-separated sequence after sorting them alphabetically.
32. Write a Python program to square and cube every number in a given list of integers using Lambda
students = []
sec_name = []
second_low = 0
n = int(input("Input number of students: "))
for _ in range(n):
s_name = input("Name: ")
score = float(input("Grade: "))
students.append([s_name,score])
print("\nNames and Grades of all students:")
print(students)
order =sorted(students, key = lambda x: int(x[1]))
for i in range(n):
if order[i][1] != order[0][1]:
second_low = order[i][1]
break
print("\nSecond lowest grade: ",second_low)
sec_student_name = [x[0] for x in order if x[1] == second_low]
sec_student_name.sort()
print("\nNames:")
for s_name in sec_student_name:
print(s_name)
34. Write a Python program to check for access to a specified path. Test the existence, readability, writability and
executability of the specified path
import os
print('Exist:', os.access('c:\\Users\\Public\\C programming library.docx',
os.F_OK))
print('Readable:', os.access('c:\\Users\\Public\\C programming library.docx',
os.R_OK))
print('Writable:', os.access('c:\\Users\\Public\\C programming library.docx',
os.W_OK))
print('Executable:', os.access('c:\\Users\\Public\\C programming library.docx',
os.X_OK))
35. Write a Python program to get information about the file pertaining to the file mode. Print the information - ID of
device containing file, inode number, protection, number of hard links, user ID of owner, group ID of owner, total size
(in bytes), time of last access, time of last modification and time of last status change
import os
path = 'e:\\testpath\\p.txt'
fd = os.open(path, os.O_RDWR)
info = os.fstat(fd)
print (f"ID of device containing file: {info.st_dev}")
print (f"Inode number: {info.st_ino}")
print (f"Protection: {info.st_mode}")
print (f"Number of hard links: {info.st_nlink}")
print (f"User ID of owner: {info.st_uid}")
print (f"Group ID of owner: {info.st_gid}")
print (f"Total size, in bytes: {info.st_size}")
print (f"Time of last access: {info.st_atime}")
print (f"Time of last modification: {info.st_mtime }")
print (f"Time of last status change: {info.st_ctime }")
os.close( fd)
36. Write a Python program to get different time values with components timezone, timezone abbreviations, the offset
of the local (non-DST) timezone, DST timezone and time of different timezones.
import time
import os
def zone_info():
print('TZ :', os.environ.get('TZ', '(not set)'))
print('Timezone abbreviations:', time.tzname)
print('Timezone : {} ({})'.format(
time.timezone, (time.timezone / 3600)))
print('DST timezone ', time.daylight)
print('Time :', time.strftime('%X %x %Z'),'\n')
print('Default Zone:')
zone_info()
TIME_ZONES = [
'Pacific/Auckland',
'Europe/Berlin',
'America/Detroit',
'Singapore',
]
for zone in TIME_ZONES:
os.environ['TZ'] = zone
time.tzset()
print(zone, ':')
zone_info()
37. Write a Python script to display the various Date Time formats a) Current date and time
b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week
import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))
38. Write a Python program to create 12 fixed dates from a specified date over a given period. The
difference between two dates will be 20.
import datetime
def every_20_days(date):
print('Starting Date: {d}'.format(d=date))
print("Next 12 days :")
for _ in range(12):
date=date+datetime.timedelta(days=20)
print('{d}'.format(d=date))
dt = datetime.date(2016,8,1)
every_20_days(dt)
39. Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These
brackets must be close in the correct order, for example "()" and "()[]{}" are valid but "[)", "({[)]" and
"{{{" are invalid.
class py_solution:
def is_valid_parenthese(self, str1):
stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in str1:
if parenthese in pchar:
stack.append(parenthese)
elif len(stack) == 0 or pchar[stack.pop()] != parenthese:
return False
return len(stack) == 0
print(py_solution().is_valid_parenthese("(){}[]"))
print(py_solution().is_valid_parenthese("()[{)}"))
print(py_solution().is_valid_parenthese("()"))
40. Write a Python class which has two methods get_String and print_String. get_String accept
a string from the user and print_String print the string in upper case.
class IOString():
def __init__(self):
self.str1 = ""
def get_String(self):
self.str1 = input()
def print_String(self):
print(self.str1.upper())
str1 = IOString()
str1.get_String()
str1.print_String()
41. Write a Python program to create an instance of an OrderedDict using a given dictionary. Sort
the dictionary during the creation and print the members of the dictionary in reverse order.
from collections import OrderedDict
dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376,
'Angola': 244}
new_dict = OrderedDict(dict.items())
for key in new_dict:
print (key, new_dict[key])
42. Write a Python program to push three items into a heap and return the smallest item from the
heap. Also Pop and return the smallest item from the heap
import heapq
heap = []
heapq.heappush(heap, ('V', 3))
heapq.heappush(heap, ('V', 2))
heapq.heappush(heap, ('V', 1))
print("Items in the heap:")
for a in heap:
print(a)
print("----------------------")
print("The smallest item in the heap:")
print(heap[0])
print("----------------------")
print("Pop the smallest item in the heap:")
heapq.heappop(heap)
for a in heap:
print(a)
43. Write a Python program to sort a list of elements using the insertion sort algorithm .
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
44. Write a Python program to sort a list of elements using Selection sort.
def selection_sort(nums):
for i, n in enumerate(nums):
mn = min(range(i,len(nums)), key=nums.__getitem__)
nums[i], nums[mn] = nums[mn], n
return nums
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(selection_sort(nums))
45. Write a Python program to access a specific item in a singly linked list using index value.
class Node:
# Singly linked node
def __init__(self, data=None):
self.data = data
self.next = None
class singly_linked_list:
def __init__(self):
# Createe an empty list
self.tail = None
self.head = None
self.count = 0
items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
46. Write a Python program to search a specific item in a given doubly linked list and return true if
the item is found otherwise return false.
class Node(object):
# Singly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
def print_foward(self):
for node in self.iter():
print(node)
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
items.append_item('SQL')
print("Original list:")
items.print_foward()
print("\n")
if items.search_item('SQL'):
print("True")
else:
print("False")
if items.search_item('C+'):
print("True")
else:
print("False")
47. Write a Python program to find the closest value of a given target value in a given non-empty
Binary Search Tree (BST) of unique values.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(8)
root.left = TreeNode(5)
root.right = TreeNode(14)
root.left.left = TreeNode(4)
root.left.right = TreeNode(6)
root.left.right.left = TreeNode(8)
root.left.right.right = TreeNode(7)
root.right.right = TreeNode(24)
root.right.right.left = TreeNode(22)
48. Write a Python program to find the kth smallest element in a given a binary search tree.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
print(kth_smallest(root, 2))
print(kth_smallest(root, 3))
49. Write a Python program to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-
x =< 0).
def sum_series(n):
if n < 1:
return 0
else:
return n + sum_series(n - 2)
print(sum_series(6))
print(sum_series(10))
50. Write a Python program to calculate the difference between the squared sum of first n natural
numbers and the sum of squared first n natural numbers.(default value of number=2)
def sum_difference(n=2):
sum_of_squares = 0
square_of_sum = 0
for num in range(1, n+1):
sum_of_squares += num * num
square_of_sum += num
square_of_sum = square_of_sum ** 2
print(sum_difference(12))