Вы находитесь на странице: 1из 11

CO-2

SESSION-2

ID NUMBER -> 170040841


26. Write a Python program to find whether a given array of integers contains any duplicate element. Return true
if any value appears at least twice in the said array and return false if every element is distinct

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

from array import *


array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
print("Current memory address and the length in elements of the buffer:
"+str(array_num.buffer_info()))
print("The size of the memory buffer in bytes:
"+str(array_num.buffer_info()[1] * array_num.itemsize))

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

while right_pos >= left_pos:


if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))

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.

items=[n for n in input().split('-')]


items.sort()
print('-'.join(items))

32. Write a Python program to square and cube every number in a given list of integers using Lambda

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


print("Original list of integers:")
print(nums)
print("\nSquare every number of the said list:")
square_nums = list(map(lambda x: x ** 2, nums))
print(square_nums)
print("\nCube every number of the said list:")
cube_nums = list(map(lambda x: x ** 3, nums))
print(cube_nums)
33. Write a Python program to find the second lowest grade of any student(s) from the given names and grades of each
student using lists and lambda. Input number of students, names and grades of each student

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])

print("\nIn reverse order:")


for key in reversed(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

while position>0 and nlist[position-1]>currentvalue:


nlist[position]=nlist[position-1]
position = position-1

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

def append_item(self, data):


#Append items on the list
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.count += 1

def __getitem__(self, index):


if index > self.count - 1:
return "Index out of range"
current_val = self.tail
for n in range(index):
current_val = current_val.next
return current_val.data

items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')

print("Search using index:")


print(items[0])
print(items[1])
print(items[4])
print(items[5])
print(items[10])

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 append_item(self, data):


# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1

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)

def search_item(self, val):


for node in self.iter():
if val == node:
return True
return False

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

def closest_value(root, target):


a = root.val
kid = root.left if target < a else root.right
if not kid:
return a
b = closest_value(kid, target)
return min((a,b), key=lambda x: abs(target-x))

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)

result = closest_value(root, 19)


print(result)

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

def kth_smallest(root, k):


stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
break
root = root.right
return root.val
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)

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

return square_of_sum - sum_of_squares

print(sum_difference(12))

Вам также может понравиться