Solved Questions on Python for Practice Write a Python program to reverse a string. def string_reverse(str1): rstr1 = '' index = len(str1) while index > 0: rstr1 += str1[ index - 1 ] index = index - 1 return rstr1 Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("Input a number to compute the factiorial : ")) print(factorial(n)) Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print ("Original String : ", s) print ("No. of Upper case chara Write a Python function that takes a list and returns a new list with unique elements of the first def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x
19
Embed
Solved Questions on Python for Practicebtechuptunotes.com/menu/oc/python/Solved Problems for Practice.pdf · pass print ("Original String : ", s) print ("No. of Upper case chara Write
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Solved Questions on Python for Practice
Write a Python program to reverse a string. def string_reverse(str1): rstr1 = '' index = len(str1) while index > 0: rstr1 += str1[ index - 1 ] index = index - 1 return rstr1
Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("Input a number to compute the factiorial : ")) print(factorial(n))
Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters
def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print ("Original String : ", s) print ("No. of Upper case chara
Write a Python function that takes a list and returns a new list with unique elements of the first
def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x
Write a Python function that checks whether a passed string is palindrome or not. 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'))
Write a Python function to check whether a string is a pangram or not. import string, sys def ispangram(str1, alphabet=string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(str1.lower()) print ( ispangram('The quick brown fox jumps over the lazy dog'))
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))
Write a Python program to make a chain of function decorators (bold, italic, underline etc.).
Write a Python program to detect the number of local variables declared in a function
def abc(): x = 1 y = 2 str1= "w3resource" print("Python Exercises") print(abc.__code__.co_nlocals)
Write a Python program to combine a one and a two dimensional array together and display their elements
Write a Python program to create a record array from a (flat) list of arrays. Sample arrays: [1,2,3,4], ['Red', 'Green', 'White', 'Orange'], [12.20,15,20,40] Expected Output: (1, 'Red', 12.2) (2, 'Green', 15.0) (3, 'White', 20.0)
Write a Python program of recursion list sum
def recursive_list_sum(data_list): total = 0 for element in data_list: if type(element) == type([]): total = total + recursive_list_sum(element) else: total = total + element return total print( recursive_list_sum([1, 2, [3,4],[5,6]]))
Write a Python program to solve the Fibonacci sequence using recursion
def fibonacci(n): if n == 1 or n == 2: return 1 else: return (fibonacci(n - 1) + (fibonacci(n - 2))) print(fibonacci(7))
Write a Python program to calculate the harmonic sum of n-1
Example:
def harmonic_sum(n): if n < 2: return 1 else: return 1 / n + (harmonic_sum(n - 1)) print(harmonic_sum(7)) print(harmonic_sum(4))
Write a Python program to calculate the value of 'a' to the power 'b'.
def power(a,b): if b==0: return 1 elif a==0: return 0 elif b==1: return a else: return a*power(a,b-1) print(power(3,4))
Write a Python program to find the greatest common divisor (gcd) of two integers.
def Recurgcd(a, b): low = min(a, b) high = max(a, b) if low == 0: return high elif low == 1: return 1 else: return Recurgcd(low, high%low) print(Recurgcd(12,14))
Write a Python program to read an entire text file.
def file_read(fname): txt = open(fname)
print(txt.read()) file_read('test.txt')
Write a Python program to append text to a file and display the text
def file_read(fname): from itertools import islice with open(fname, "w") as myfile: myfile.write("Python Exercises\n") myfile.write("Java Exercises") txt = open(fname) print(txt.read()) file_read('abc.txt')
Write a Python program to read a file line by line and store it into a list.
def file_read(fname): with open(fname) as f: #Content_list is the list that contains the read lines. content_list = f.readlines() print(content_list) file_read(\'test.txt\')
Write a python program to find the longest words def longest_word(filename): with open(filename, 'r') as infile: words = infile.read().split() max_len = len(max(words, key=len)) return [word for word in words if len(word) == max_len] print(longest_word('test.txt'))
Write a Python program to count the number of lines in a text file
def file_lengthy(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 print("Number of lines in the file: ",file_lengthy("test.txt"))
Write a Python program to count the frequency of words in a file
from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print("Number of words in the file :",word_count("test.txt"))
Write a Python program to write a list to a file.
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] with open('abc.txt', "w") as myfile: for c in color: myfile.write("%s\n" % c) content = open('abc.txt') print(content.read())
Write a Python program to remove newline characters from a file
def remove_newlines(fname): flist = open(fname).readlines() return [s.rstrip('\n') for s in flist] print(remove_newlines("test.txt"))
Write a Python class to implement pow(x, n).
class py_solution: def pow(self, x, n): if x==0 or x==1 or n==1: return x if x==-1: if n%2 ==0: return 1 else: return -1 if n==0: return 1 if n<0: return 1/self.pow(x,-n) val = self.pow(x,n//2) if n%2 ==0: return val*val
Write a Python class to reverse a string word by word
class py_solution: def reverse_words(self, s): return ' '.join(reversed(s.split())) print(py_solution().reverse_words('hello .py'))
Write a Python program for binary search
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
Write a Python program for sequential search.
def Sequential_Search(dlist, item): pos = 0 found = False
while pos < len(dlist) and not found: if dlist[pos] == item: found = True else: pos = pos + 1 return found, pos print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))
Write a Python program to sort a list of elements using the bubble sort algorithm
Step by step pictorial presentation :
def bubbleSort(nlist): for passnum in range(len(nlist)-1,0,-1): for i in range(passnum): if nlist[i]>nlist[i+1]: temp = nlist[i] nlist[i] = nlist[i+1] nlist[i+1] = temp nlist = [14,46,43,27,57,41,45,21,70] bubbleSort(nlist) print(nlist)
Write a Python program to sort a list of elements using the selection sort algorithm
Pictorial Presentation : Selection Sort
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
Write a Python program to sort a list of elements using the insertion sort
algorithm.
Pictorial Presentation: Insertion Sort
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)
Write a Python program to sort a list of elements using the merge sort
algorithm
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
Write a Python program to sort a list of elements using the quick sort algorithm
def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
def quickSortHlp(data_list,first,last):
if first < last:
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
Write a Python script to sort (ascending and descending) a dictionary by value
import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True) print('Dictionary in descending order by value : ',sorted_d)
Write a Python script to concatenate following dictionaries to create a new one.
dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic4 = {} for d in (dic1, dic2, dic3): dic4.update(d) print(dic4)
Write a Python script to check if a given key already exists in a dictionary
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} def is_key_present(x): if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary') is_key_present(5) is_key_present(9)
Write a Python program to sum all the items in a dictionary.
Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9)
import re def is_allowed_specific_char(string): charRe = re.compile(r'[^a-zA-Z0-9.]') string = charRe.search(string) return not bool(string) print(is_allowed_specific_char("ABCDEFabcdef123450")) print(is_allowed_specific_char("*&%@#!}{"))
Write a Python program that matches a string that has an a followed by zero or more b's.
import re def text_match(text): patterns = 'ab*?' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(text_match("ac")) print(text_match("abc")) print(text_match("abbc"))
Write a Python program that matches a string that has an a followed by three 'b'
import re def text_match(text): patterns = 'ab{3}?' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(text_match("abbb")) print(text_match("aabbbbbc"))
Write a Python program that matches a word at the beginning of a string
import re def text_match(text): patterns = '^\w+' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match(" The quick brown fox jumps over the lazy dog."))
Write a Python program to remove leading zeros from an IP address.
import re
ip = "216.08.094.196"
string = re.sub('\.[0]*', '.', ip)
print(string)
Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string.
import re results = re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13, and 345 are important") print("Number of length 1 to 3") for n in results: print(n.group(0))
Write a Python program to search a literals string in a string and also find the location within the original string where the pattern occurs
Sample text : 'The quick brown fox jumps over the lazy dog.' Searched words : 'fox'
import re pattern = 'fox' text = 'The quick brown fox jumps over the lazy dog.' match = re.search(pattern, text) s = match.start() e = match.end() print('Found "%s" in "%s" from %d to %d ' % \ (match.re.pattern, match.string, s, e))
Write a Python program to find the substrings within a string
Sample text :
'Python exercises, PHP exercises, C# exercises'
Pattern :
'exercises'
Note: There are two instances of exercises in the input string.
import re text = 'Python exercises, PHP exercises, C# exercises' pattern = 'exercises' for match in re.findall(pattern, text): print('Found "%s"' % match)
Write a Python program to extract year, month and date from a an url.
import re def extract_date(url): return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url) url1= "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/" print(extract_date(url1))
Write a Python program to find all three, four, five characters long words in a string.
import re text = 'The quick brown fox jumps over the lazy dog.' print(re.findall(r"\b\w{3,5}\b", text))
Write a Python program to remove multiple spaces in a string
import re text1 = 'Python Exercises' print("Original string:",text1) print("Without extra spaces:",re.sub(' +',' ',text1))
Write a Python class to get all possible unique subsets from a set of distinct integers. -
Write a Python class to find a pair of elements (indices of the two numbers) from a given
array whose sum equals a specific target number. –
Input: numbers= [10,20,10,40,50,60,70], target=50
Output: 3, 4
class py_solution: def twoSum(self, nums, target): lookup = {} for i, num in enumerate(nums): if target - num in lookup: return (lookup[target - num] + 1, i + 1) lookup[num] = i print("index1=%d, index2=%d" %
py_solution().twoSum((10,20,10,40,50,60,70),50))
Write a Python class to implement pow(x, n)
class py_solution: def pow(self, x, n): if x==0 or x==1 or n==1: return x if x==-1: if n%2 ==0: return 1 else: return -1 if n==0: return 1 if n<0: return 1/self.pow(x,-n) val = self.pow(x,n//2) if n%2 ==0: return val*val return val*val*x print(py_solution().pow(2, -3));