# write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') # write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum # write a program to find and print the largest among three numbers num1 = 10 num2 = 12 num3 = 14 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}') # write a program to find and print the smallest among three numbers num1 = 10 num2 = 12 num3 = 14 if (num1 <= num2) and (num1 <= num3): smallest = num1 elif (num2 <= num1) and (num2 <= num3): smallest = num2 else: smallest = num3 print(f'smallest:{smallest}') # Write a python function to merge two given lists into one def merge_lists(l1, l2): return l1 + l2 # Write a program to check whether a number is prime or not num = 337 if num > 1: for i in range(2, num//2 + 1): if (num % i) == 0: print(num,"is not a prime number") print(f"{i} times {num//i} is {num}") break else: print(f"{num} is a prime number") else: print(f"{num} is not a prime number") # Write a python function that prints the factors of a given number def print_factors(x): print(f"The factors of {x} are:") for i in range(1, x + 1): if x % i == 0: print(i) # Write a program to find the factorial of a number num = 13 factorial = 1 if num < 0: print("No factorials for negative numbers!") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print(f"The factorial of {num} is {factorial}") # Write a python function to print whether a number is negative, positive or zero def check_pnz(num): if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # Write a program to print the multiplication table of a given number num = 9 for i in range(1, 11): print(f"{num} x {i} = {num*i}") # Write a python function to print powers of 2, for given number of terms def two_power(terms): result = list(map(lambda x: 2 ** x, range(terms))) print(f"The total terms are: {terms}") for i in range(terms): print(f"2^{i} = {result[i]}") # Write a program to filter the numbers in a list which are divisible by a given number my_list = [11, 45, 74, 89, 132, 239, 721, 21] num = 3 result = list(filter(lambda x: (x % num == 0), my_list)) print(f"Numbers divisible by {num} are {result}") # Write a python function that returns the sum of n natural numbers def sum_natural(num): if num < 0: print("Please enter a positive number!") else: sum = 0 while(num > 0): sum += num num -= 1 return num # Write a program to swap first and last elements in a list my_list = [1, 2, 3, 4, 5, 6] my_list[0], my_list[-1] = my_list[-1], my_list[0] # Write a python function to find the area of a circle, whose radius is given def findArea(r): PI = 3.142 return PI * (r*r) # Write a program to print the sum of squares of first n natural numbers n = 21 sum_n = 0 for i in range(1, n+1): sum_n += i**2 print(sum_n) # Write a program to print the length of a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(len(my_list)) # Write a pythno function to print the length of a given tuple my_tuple = (1, 2, 3, 4, 5, 6, 7, 8) print(len(my_tuple)) # Write a python function to print the elements of a given list, one element in a line def custom_print(l): for _ in l: print(_) # Write a python function to remove all the odd numbers from a list and return the remaining list def remove_odd(my_list): result = list(filter(lambda x: (x % 2 == 0), my_list)) return result # Write a python function to remove all the even numbers from a list and return the remaining list def remove_even(my_list): result = list(filter(lambda x: (x % 2 != 0), my_list)) return result # Write a function that takes two lists as input and returns a zipped list of corresponding elements def zip_list(list1, list2): return list(zip(list1, list2)) # Write a program to to print the contents of a given file file_name = 'temp.txt' with open(file_name, 'r') as f: print(f.read()) # Write a functin that returns the LCM of two input numbers def lcm(a, b): if a>b: min_ = a else: min_ = b while True: if min_%a==0 and min_%b==0: break min_+=1 return min_ # Write a program to print the unique elements in a list my_list = [1, 2, 4, 5, 2, 3, 1, 5, 4, 7, 8, 2, 4, 5, 2, 7, 3] print(set(my_list)) # Write a function that returns the sum of digits of a given number def digisum(num): sum_=0 while num > 0: dig = num % 10 sum_+=dig num//=10 return sum_ # Write a program to check and print whether a number is palindrome or not num = 12321 temp = num rev = 0 while num > 0: dig = num % 10 rev = rev*10 + dig num//=10 if temp==rev : print("The number is a palindrome!") else: print("The number isn't a palindrome!") # Write a function that prints a given value, n number of times def print_n(val, n): for _ in range(n): print(val) # Write a function to find the area of sqaure def square_area(a): return a*a # Write a function to find the perimeter of a square def square_perimeter(a): return 4*a # Write a function to find the area of rectangle def rectangle_area(l, b): return l*b # Write a function to find the permieter of a rectangle def rectangle_perimeter(l, b): return 2*(l+b) # Write a python function to find the area of a circle, whose radius is given def findArea(r): PI = 3.142 return PI * (r*r) # Write a function to calculate and return electricity bill. Units used are given. Price per unit is fixed and is increased after 750 units. def calc_elect_bill(units): if units > 0: if units <= 750: return 5*units else: return 5*(750) + 7*(units-750) else: return -1 # Write a function to return day of a week, given the number def give_day(n): day_dict = {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'} return day_dict[n] # Write a program to calculate and print the volume of a cylender r = 3 h = 5 pi = 3.14 volume = pi*(r**2)*h print(volume) # Write a function to calculate and return the average of input numbers def calc_avg(*args): if len(args) > 0: return sum(args)/len(args) return None # Write a function to calculate compound interest, given p, r, t def comp_int(p, r, t): amount = p * (1 + (r/100))**t interest = amount - p return interest # Write a function to calculate simple interest, given p, r, t def simp_int(p, r, t): interest = (p*r*t)/100 return interest # Write a program to print a given string, replacing all the vowels with '_' st = "Where is this going? Could you please help me understand!" vowels = "AEIOUaeiou" for v in vowels: st = st.replace(v, '_') print(st) # Write a functio to check whether a number if perfect or not def is_perfect(n): sum_ = 0 for i in range(1, n//2 + 1): if n%i == 0: sum_+=i if sum_ == n: return True return False # Write a function that returns seperate lists of positive and negative numbers from an input list def seperate_pn(l): pos_list = [] neg_list = [] for _ in l: if _<0: neg_list.append(_) else: pos_list.append(_) return pos_list, neg_list # Write a program to find and print the area of a triangle, whose hight and width are given. h = 12 w = 11 area = 0.5*h*w print(area) # Write a function to find acceleration, given u, v and t def acc(u, v, t): return (v-u)/t # Write a lambda function to multiply two numbers multiply = lambda a, b: a*b # Write a lambda function to add two numbers add = lambda a, b: a+b # Write a lambda function that gives True if the input number is even otherwise False even = lambda a: True if a%2 == 0 else False # Write a lambda function to to give character grom it's ascii value ascii = lambda a: chr(a) # Write a lambda function to that gives the number of digits in a number dig_cnt = lambda a: len(str(a)) # Write a program to to check if a triangle is valid or not, given it's all three angles def is_valid_triangle_angle(a, b c): if a+b+c == 180: return True return False # Write a program to to check if a triangle is valid or not, given it's all three sides' length def is_valid_triangle_length(a, b c): if a>0 and b>0 and c>0: if a+b > c and a+c > b and b+c > a: return True return False # Write a lambda functio that gives the word count in a statement. count_word = lambda s: len(s.split(' ')) # Write a program to extract and print digits of a number in reverse order. The number is input from user. num = int(input("Enter a number with multiple digit: ")) n=0 while num>0: a = num%10 num = num - a num = num/10 print(int(a),end="") n = n + 1 # Write a function that takes in height(m) and weight(kg), calculates BMI and prints the comments def bmi(height: "Meters", weight: "Kgs"): bmi = weight/(height**2) print("Your BMI is: {0} and you are ".format(bmi), end='') if ( bmi < 16): print("severely underweight.") elif ( bmi >= 16 and bmi < 18.5): print("underweight.") elif ( bmi >= 18.5 and bmi < 25): print("healthy.") elif ( bmi >= 25 and bmi < 30): print("overweight.") elif ( bmi >=30): print("severely overweight.") # Write a program that prints all the alphabets in a string and skips all other characters string = "$john.snow#@Got.bad_ending/com" for ch in string: if (ch>='A' and ch<='Z') or (ch>='a' and ch<='z'): print(ch, end='') else: pass # Write a function that takes number of disks in tower of hanaoi problem and returns the minimum number of steps required def hanoi(x): if x == 1: return 1 else: return 2*hanoi(x-1) + 1 # Write a lambda function to convert centimeters to inches cm_to_inch = lambda x: x/2.54 # Write a lambda function to find the union of two lists union = lambda a, b: list(set(a)|set(b)) # Write a lambda function to find the intersection of two lists intersection = lambda a, b: list(set(a)&set(b)) # Write a program that adds the square of two numbers and prints it a = 32 b = 21 result = a**2 + b**2 print(result) # Write a python function to concat the input strings and there's also a choice for seperator def con_str(*args, sep = ' '): return sep.join(args) # Write a program to print all the even numbers in a range r1, r2 = 1, 28 for _ in range(r1, r2+1): if _%2 == 0: print(_) # write a python program to sort dictionary items dict1 = {'car': [7, 6, 3], 'bike': [2, 10, 3], 'truck': [19, 4]} print(f"The original dictionary is : {str(dict1)}") res = dict() for key in sorted(dict1): res[key] = sorted(dict1[key]) print(f"The sorted dictionary : {str(res)}") # write a program to display date and time import datetime now = datetime.datetime.now() time= now.strftime("%Y-%m-%d %H:%M:%S") print(f"Current date and time : {time}") # write a program to return the absolute value num = -10 print(f'Absolute of {num} is {abs(num)}') # write a python program to check the length of list sample_list = ['a','b','c'] print(f'length of sample_list is {len(sample_list)}') # write a Python program to calculate number of days between two dates. from datetime import date f_date = date(2019, 4, 15) # YYYY/MM/DD l_date = date(2020, 4, 15) # YYYY/MM/DD delta = l_date - f_date print(f'No of days between {f_date} and {l_date} is:{delta.days}') # write a Python program to convert Python objects into JSON strings. import json python_dict = {"name": "David", "age": 6, "class":"I"} json_dict = json.dumps(python_dict, sort_keys=True, indent=4) print(f"json dict : {json_dict}") # write a Python program to get the largest number from a list def max_num_in_list(list): max = list[0] for a in list: max = a if a > max else max return max print(f'max_num_in_list [1, 10, -8, 0], Ans:{max_num_in_list([1, 10, -8, 0])}') # write a Python program to remove duplicates from a list a = [10,20,30,20,10,50,60,40,80,50,40] dup_items = set() uniq_items = [] for x in a: if x not in dup_items: uniq_items.append(x) dup_items.add(x) print(f'dup_items:{dup_items}') # write a Python program to flatten a shallow list import itertools original_list = [[2,4,3],[1,5,6], [9], [7,9,0], [1,2,3,4]] new_merged_list = list(itertools.chain(*original_list)) print(f'merged list/flatten:{new_merged_list}') # write a Python program to create multiple list obj = {} for i in range(1, 11): obj[str(i)] = [] print(f'create multiple list:{obj}') # write a Python program to merge two dictionaries d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(f'merge two dictionaries:{d}') # write a Python program to Sum all the items in a dictionary my_dict = {'data1':100,'data2':-54,'data3':247} print(f'Sum all the items in a dictionary:{sum(my_dict.values())}') # write a python program to Get the maximum and minimum value in a dictionary my_dict = {'x':500, 'y':5874, 'z': 560} key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Maximum Value in a dictionary: ',my_dict[key_max]) print('Minimum Value in a dictionary: ',my_dict[key_min]) # write a python program to do nothing for a condition if 1 + 1 == 2: pass # Nothing # write a python program to make use of enumerate method for count, value in enumerate(obj): print(count, value) # write a python program to make use of setdefault for missing dictionary keys a_dict = {'a':1} a_dict.setdefault('b',2) print(f'After appending with new value:{a_dict}') # write a python program to make use of maps def square(number): return number ** 2 numbers = [1, 2, 3, 4, 5] squared = map(square, numbers) print(f'mapped numbers:{list(squared)}') # write a python program to make use of modulo operator print(f'modulo 15 % 4: Sol->{15 % 4}') # write a python program to explain enclosing and global scope x = 'global' def f(): x = 'enclosing' def g(): print(x) g() return x obj1 = f() print('explain global scope:',obj1) # write a python program to expain local and global scope def f1(): x = 'enclosing' def g(): x = 'local' return x x=g() return x obj2 = f1() print('explain local scope:',obj2) # write a python program to make use of regular expression for matching import re print('Find the characters in the given string:',re.findall(r'[a-z]+', '123FOO456', flags=re.IGNORECASE)) # write a python program to make use of regular expression for matching s = 'foo123bar' m = re.findall('123', s) print('find the number position:',m) # write a python program to convert lower string to UPPERCASE a = 'string' print(f'convert lowercase to uppercase:{a.upper()}') # write a python program to convert uppercase string to lower a = 'STRING' print(f'convert lowercase to uppercase:{a.lower()}') # write a Python Program to Find the Square Root num = 8 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) # write a Python Program to Convert Kilometers to Miles kilometers = 10.0 conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) # write a Python Program to Convert Celsius To Fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) # write a Python Program to Check if a Number is Positive, Negative or 0 num = 10 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # Python Program to Check if a Number is Odd or Even num = 100 if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) # Python Program to Display the multiplication Table num = 12 for i in range(1, 11): print(num, 'x', i, '=', num*i) # write a program for Rolling the dices import random min = 1 max = 6 print("Rolling the dices...and the values are",random.randint(min, max)) print("Rolling the dices...and the values are",random.randint(min, max)) # write a python program to calculate the average list1 = [1,3,4,5] average = (sum(list1)) / len(list1) print(f"the average score is: {average} ") # write a python program to print reverse list print(f'reverese the given list elements:{list1[::-1]}') # write a python program for creating the thread import threading from threading import Thread import time def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % ( threadName, time.ctime(time.time()) )) # try: # Thread(target=print_time, args=("Thread-1", 2, )).start() # Thread(target=print_time, args=("Thread-1", 4, )).start() # except: # print("Error: unable to start thread") # write a python program to check a num is less than 1000 def near_thousand(n): return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) print('near to 1000',near_thousand(1000)) print('near to 1300',near_thousand(1300)) # write a python program to convert lower case to upper for list of elements x = ['ab', 'cd'] for i in x: print(i.upper()) # write a python program to break when the num is perfectly divisible i = 1 while True: if i%3 == 0: break print(i) i+= 1 # write a python program to check name exists in given list names1 = ['Amir', 'Bala', 'Chales'] for n in names1: name = n.lower() if 'amir' == name: print('Yes name exists:',name) else: print('No') # write a python program to print a matrix as output matrix = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] for i in range(0, 4): print(matrix[i][1], end = " ") # write a python program to calculate the time taken from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting' } time_now = localtime() hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < activity_time: print (activities[activity_time]) break else: print ('Unknown, AFK or sleeping!') # write a python program to search a key in the text file fname = 'sample.txt' l='keyword' # Enter letter to be searched k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==l): k=k+1 print("Occurrences of the letter:",k) # write a python program to expalin list comprehension and print alternative values t = (1, 2, 4, 3, 8, 9) print([t[i] for i in range(0, len(t), 2)]) # write a python program to sort tuple values a=(2,3,1,5) tuple_sorted = sorted(a) print(tuple(tuple_sorted)) # write a python program to multiple two list values l1=[1,2,3] l2=[4,5,6] print('multiply two list values:',[x*y for x in l1 for y in l2]) # write the list comprehension to pick out only negative integers from a given list ā€˜lā€™. l1=[1,2,3,-4,-8] print('negative integers:', [x for x in l1 if x<0]) # write a python program to convert all list elements to upper case s=["pune", "mumbai", "delhi"] print([(w.upper(), len(w)) for w in s]) # write a python program to expalin python zip method l1=[2,4,6] l2=[-2,-4,-6] for i in zip(l1, l2): print(i) # write a python program to add two list using python zip method l1=[10, 20, 30] l2=[-10, -20, -30] l3=[x+y for x, y in zip(l1, l2)] print('added two list:',l3) # write a list comprehension for number and its cube l=[1, 2, 3, 4, 5, 6, 7, 8, 9] print([x**3 for x in l]) # write a list comprehension for printing rows into columns and vv l=[[1 ,2, 3], [4, 5, 6], [7, 8, 9]] print([[row[i] for row in l] for i in range(3)]) # write a list comprehension for printing rows into columns and vv def unpack(a,b,c,d): print(a+d) x = [1,2,3,4] unpack(*x) # write a python program to use python lambda function lamb = lambda x: x ** 3 print(lamb(5)) # write a python program to multiply a string n times a = 'python' print(a*5) # write a python to check two numbers are greater than or equal or less than def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y print(maximum(2, 3)) # write a python to dict to zip and print as dictionary elements in original form a={"a":1,"b":2,"c":3} b=dict(zip(a.values(),a.keys())) print(b) # write a python program to delete an dictionary element a={1:5,2:3,3:4} a.pop(3) print(a) # write a python program to check two dictionary are equal or not d1 = {"john":40, "peter":45} d2 = {"john":466, "peter":45} d1 == d2 # write a python program to print only dictionary keys as list d = {"john":40, "peter":45} print(list(d.keys())) #write a python program to check two lists are equal or not a=[1, 4, 3, 5, 2] b=[3, 1, 5, 2, 4] print(a==b) #write a python program to check two lists are equal or not a=frozenset(set([5,6,7])) print(a) #write a python program to sum the set of unqiue elements a={5,6,7} print(sum(a,5)) #write a python program to implement try catch code try: s={5,6} s*3 except Exception as e: print(e) #write a python program to count the len of unique elements nums = set([1,1,2,3,3,3,4,4]) print(len(nums)) #write a python program to split in python print('abcdefcdghcd'.split('cd', 2)) # write a python program to add title to string print('ab cd-ef'.title()) # write a python program to print equal lenght of string print('ab'.zfill(5)) # write a python program to use string replace print('abcdef12'.replace('cd', '12')) # write a python program to check string istitle str1 = 'Hello!2@#World' if str1.istitle(): print('Yes string is title') # write a python program to do lstrip on string print('xyyzxxyxyy'.lstrip('xyy')) # write a python program to check identifier/keyword print('for'.isidentifier()) # write a python program to check is an num/int print('11'.isnumeric()) # write a python program to check is an variable is printable print('1@ a'.isprintable()) # write a python program to check it contains any space print(''''''.isspace()) # write a python program to check is an title print('HelloWorld'.istitle()) # write a python program to check is all are num/int print('ab,12'.isalnum()) # write a python program to check is all are alphanumeric print('ab'.isalpha()) # write a python program to check is all are digit print('0xa'.isdigit()) # write a python program to use f string var1 = 'python language' print(f'f-string is an good feature in {var1}') # write a python program to iterate an dict and concatenate D=dict(p='san', q='foundry') print('{p}{q}'.format(**D)) # write a python program to replace blank space to 1 a='1 0 0 1' print(a.replace(' ', '1')) # write a python program to explain the generator def f11(x): yield x+1 g=f11(8) print(next(g)) # write a python program to replace blank space to 1 def f12(x): yield x+1 print("test") yield x+2 g=f12(9) print(next(g)) # write a python program to replace blank space to 1 a = re.compile('[0-9]') z= a.findall('3 trees') print(z) # write a python program to print current working directory import os print(os.getcwd()) # write a python program to print the ascii value of a string print([ord(ch) for ch in 'abc']) # write a python program to use extend in list/ append to a list a=[13,56,17] a.append([87]) a.extend([45,67]) print(a) # write a python program to replace blank space to 1 my_string = 'balaji' k = [print(i) for i in my_string if i not in "aeiou"] print('Not a vowel',k) # write a python program to add and square a range of number x = [i**+1 for i in range(3)]; print(x) # write a python program to replace blank space to 1 print([i+j for i in "abc" for j in "def"]) # write a python program to multiply two list with list comprehensive l1=[1,2,3] l2=[4,5,6] print([x*y for x in l1 for y in l2]) # write a python program to print only digit or only apha charac in a given list l=["good", "oh!", "excellent!", "#450"] print([n for n in l if n.isalpha() or n.isdigit()]) # write a python program to print todays date tday=datetime.date.today() print(tday) # write a python program to check tuple are immutable a=(1,2,3) try: a = a+1 except Exception as e: print(e) # write a python program to calculate factorial sum using list comprehensive import functools n =5 print(functools.reduce(lambda x, y: x * y, range(1, n+1))) # write a python program to print len of each characters words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) # write a python program to make increment on each call of method using lambda function def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) f(0) print(f(1)) # write a python program to sort using list comprehensive pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) print(pairs) # write a python program to del the first element of the array/list a = [-1, 1, 66.25, 333, 333, 1234.5] del a[0] print(a) # write a python program to replace the first character of a given word word = "goal" word = "f" + word[1:] print(word) # write a python program to find a string in a given phrase phrase = "the surprise is in here somewhere" print(phrase.find("surprise")) # write a python program to expalin the use of f-string n = 3 m = 4 print(f"{n} times {m} is {n*m}") # write a python program to explain the use of assert x=1 y=8 assert x>y, 'X too small' # write a python program to multiply three numbers num1 = 1.5 num2 = 6.3 num3 = -2.3 product = num1 * num2 * num3 print(f'Product: {product}') # write a python function that when given two numbers, would divide the first number by second number and return the quotient and remainder def divide_first_number_by_second(num1, num2): return (num1 // num2), (num1 % num2) # write a python function to return the largest and smallest numbers in the given list and return None if the list is empty def largest_and_smallest(list_of_nums): if list_of_nums: return max(list_of_nums), min(list_of_nums) else: return # write a recursive python function to print the nth fibonacci number, where n is provided as the argument def fibonacci_recursive(n): if n <= 1: return n else: return (recur_fibo(n-1) + recur_fibo(n-2)) # write a python function that would read the given input file path and print its contents def read_and_print_file(filepath): with open(filepath, "r") as infile: print( infile.read() ) # write a python program that would print the first n positive integers using a for loop n = 62 for num in range(n): print(num) # write a python function that returns the input list sorted in ascending order def sort_ascending(list_to_be_sorted): return sorted(list_to_be_sorted) # write a python function that returns the input list sorted in descending order def sort_descending(list_to_be_sorted): return sorted(list_to_be_sorted, reverse=True) # write a python function that would return the sum of first n natural numbers, where n is the input def sum_first_n(n): return ( n * (n+1) ) // 2 # write a recursive python function that would return the sum of first n natural numbers, where n is the input def sum_first_n_recursive(n): if n == 0: return 0 return sum_first_n_recursive(n-1) + n # write a python function that would filter a list of dictionaries where a specified key equals given value, list_of_dictionaries, key and value are inputs to this function. def filter_with_key_value(list_of_dicts, key, value): return list( filter( lambda x: x.get(key) == value, list_of_dicts ) ) # write a recursive python function that takes either a list or tuple as input and reverses the order of its elements def reverse(seq): SeqType = type(seq) emptySeq = SeqType() if seq == emptySeq: return emptySeq restrev = reverse(seq[1:]) first = seq[0:1] result = restrev + first return result # write a python function that returns the square of a given input number def square(x): return x**2 # write a python function that performs selection sort on the given list or tuple or string and returns the new sorted sequence def selection_sort(list_to_be_sorted): sorted_list = list_to_be_sorted[:] for i in range(len(sorted_list)): new_min = sorted_list[i] new_min_old_place = i for j in range(i+1, len(sorted_list)): if new_min > sorted_list[j]: new_min = sorted_list[j] new_min_old_place = j old_val = sorted_list[i] sorted_list[i] = new_min sorted_list[new_min_old_place] = old_val return sorted_list # write a python program that asks for user input and prints the given input a = input("User Input") print(a) # write a python function shifts and scales all numbers in the given list by the given mean and standard deviation def shift_and_scale(list_of_nums, mean, std): return [ (x-mean) / std for x in list_of_nums ] # write a python function that takes in a list of sequences and zips each corresponding element from the list into a tuple and returns the list of such tuples def zip_(list_of_seq): return list(zip(*list_of_seq)) # write a python program that asks user to guess a number between 1 and 5 and guess it within 3 guesses print("Please guess a number between 1 and 5 and I will guess within 3 chances!") guess1 = input("Is it <= 3? enter y/n \n") if guess1 == "y": guess2 = input("Is it <= 2? enter y/n \n") if guess2 == "y": guess3 = input("Is it 1? enter y/n \n") if guess3 == "y": print("Yay! found the number, its 1") else: print("Yay! found the number, its 2") else: print("Yay! found the number, its 3") else: guess2 = input("Is it 4? enter y/n \n") if guess2 == "y": print("Yay! found the number, its 4") else: print("Yay! found the number, its 5") # write python program that would merge two dictionaries by adding the second one into the first a = {"a": 1, "b": 3} b = {"c": 1, "d": 3} a.update(b) # write a python function that would reverse the given string def reverse_string(str_to_be_reversed): return str_to_be_reversed[::-1] # write a python program that would print "Hello World" print("Hello World") # write a python program that would swap variable values a = 10 b = 15 a, b = b, a # write a python program that iterates over a dictionary and prints its keys and values a = {"a":1, "b":2, "c":3, "d":4} for k, v in a.items(): print(k, v) # write a python function that would print the ASCII value of a given character def print_ascii(char): print(ord(char)) # write a python function that takes in two numbers and returns their HCF def hcf(num1, num2): smaller = num1 if num1 < num2 else num2 for i in range(1, smaller+1): if (num1 % i == 0) and (num2 % i == 0): hcf = i return hcf # write a python function that takes in two numbers and returns their LCM def lcm(num1, num2): bigger = num1 if num1 > num2 else num2 while True: if (bigger % num1 == 0) and (bigger % num2 == 0): break bigger += 1 return bigger # write a recursive python function to calculate sum of natural numbers upto n, where n is an argument def recursive_sum(n): if n <= 1: return n else: return n + recursive_sum(n-1) # write a python function that deletes the last element of a list and returns the list and the deleted element def delete_last_element(list_to_be_processed): deleted_element = list_to_be_processed.pop() return list_to_be_processed, deleted_element # write a python function that takes in a list and returns a list containing the squares of the elements of the input list def square_list_elements(list_to_be_squared): return list( map(lambda x: x**2, list_to_be_squared) ) # write a python function that finds square roots of a given number, if the square root is an integer, else returns the message "Error - the square root is not an integer" def find_integer_square_roots(num): found = False for k in range(1, (num//2)+1): if ((k**2)==num): found = True break if not found: return "Error - the square root is not an integer" return -k, k # write a python program that prints out natural numbers less than or equal to the given number using a while loop input_num = 27 while input_num: print(input_num) input_num -= 1 # write a python function that takes two numbers. The function divides the first number by the second and returns the answer. The function returns None, if the second number is 0 def divide(num1, num2): if num2 == 0: return else: return num1 / num2 # write a python program uses else with for loop seq = "abcde" for k in seq: if k == "f": break else: print("f Not Found!") # write a recursive python function that performs merge sort on the given list or tuple or string and returns the new sorted sequence def sort_and_merge(l1, l2): new_list = [] i = 0 j = 0 l1_len = len(l1) l2_len = len(l2) while (i <= l1_len-1) and (j <= l2_len-1): if l1[i] < l2[j]: new_list.append(l1[i]) i +=1 else: new_list.append(l2[j]) j +=1 if i <= (l1_len-1): new_list += l1[i:] if j <= (l2_len-1): new_list += l2[j:] return new_list def recursive_merge_sort(list_to_be_sorted): final_list = [] first = 0 last = len(list_to_be_sorted) if last <= 1: final_list.extend( list_to_be_sorted ) else: mid = last // 2 l1 = recursive_merge_sort( list_to_be_sorted[:mid] ) l2 = recursive_merge_sort( list_to_be_sorted[mid:] ) final_list.extend( sort_and_merge( l1, l2 ) ) return final_list # Write a function to return the mean of numbers in a list def cal_mean(num_list:list)->float: if num_list: return sum(num_list)/len(num_list) else: return None # Write a function to return the median of numbers in a list def cal_median(num_list:list)->float: if num_list: if len(num_list)%2 != 0: return sorted(num_list)[int(len(num_list)/2) - 1] else: return (sorted(num_list)[int(len(num_list)/2) - 1] + sorted(num_list)[int(len(num_list)/2)])/2 else: return None # Write a function to return the area of triangle by heros formula def cal_triangle_area(a:float,b:float,c:float)->float: if a or b or c: s = (a+b+c)/2 if s>a and s>b and s>c: area = (s*(s-a)*(s-b)*(s-c))**(1/2) return round(area,2) else: return None return None # Write a function to return the area of a equilateral triangle def cal_eq_triangle_area(a:float)->float: if a: return (3**(1/2))*(a**2)/4 else: return None # Write a function to return the area of a right angle triangle def cal_rt_triangle_area(base:float,height:float)->float: if base and height: return (base*height)/2 else: return None # Write a function to return the cartisian distance of a point from origin def cal_dist_from_orign(x:float,y:float)->float: return (x**2+y**2)**(1/2) # Write a function to return the cartisian distance between two points def cal_cart_distance(x1:float,y1:float,x2:float,y2:float)->float: return ((x1-x2)**2+(y1-y2)**2)**(1/2) # Write a function to return the type roots of a quadratic equation ax**2 + bx + c = 0 def root_type(a:float,b:float,c:float): if b**2-4*a*c >= 0: return 'real' else: return 'imaginary' # Write a function to return the sum of the roots of a quadratic equation ax**2 + bx + c = 0 def sum_of_roots(a:float,c:float): if a: return c/a else: return None # Write a function to return the product of the roots of a quadratic equation ax**2 + bx + c = 0 def prod_of_roots(a:float,b:float): if a: return -b/a else: return None # Write a function to return the real of the roots of a quadratic equation else return None ax**2 + bx + c = 0 def roots_of_qad_eq(a:float,b:float,c:float): d = b**2-4*a*c if d >= 0: return (-b+(d)**(1/2))/2*a,(-b-(d)**(1/2))/2*a else: return None # Write a function to return the profit or loss based on cost price and selling price def find_profit_or_loss(cp,sp): if cp > sp: return 'loss', cp-sp elif cp < sp: return 'profit', sp-cp else: return 'no profit or loss', 0 # Write a function to return the area of a rectangle def cal_area_rect(length, breadth): return length*breadth # Write a function to return the area of a square def cal_area_square(side): return side**2 # Write a function to return the area of a rhombus with diagonals q1 and q2 def cal_area_rhombus(q1,q2): return (q1*q2)/2 # Write a function to return the area of a trapezium with base a base b and height h between parallel sides def cal_area_trapezium(a,b,h): return h*(a+b)/2 # Write a function to return the area of a circle of raidus r def cal_area_circle(r): pi = 3.14 return pi*r**2 # Write a function to return the circumference of a circle def cal_circumference(r): pi = 3.14 return 2*pi*r # Write a function to return the perimeter of a rectangle def cal_perimeter_rect(length, bredth): return 2*(length+bredth) # Write a function to return the perimeter of a triangle def cal_perimeter_triangle(s1,s2,s3): return s1+s2+s3 # Write a function to return the perimeter of a square def cal_perimeter_square(side): return 4*side # Write a function to return the perimeter of an equilateral triangle def cal_perimeter_eq_triangle(a): return 3*a # Write a function to return the perimeter of a isoscales triangle def cal_perimeter_iso_triangle(s1,s2): return 2*s1+s2 # Write a function to return the area of an ellipse def cal_area_ellipse(minor, major): pi = 3.14 return pi*(minor*major) # Write a function to return the lateral surface area of a cylinder def cal_cylinder_lat_surf_area(height,radius): pi=3.14 return 2*pi*radius*height # Write a function to return the curved surface area of a cone def cal_cone_curved_surf_area(slant_height,radius): pi=3.14 return pi*radius*slant_height # Write a function to return the total surface area of a cube of side a def cal_surface_area_cube(a): return 6*(a**2) # Write a function to return the total surface area of a cuboid of length l, bredth b and height h def cal_surface_area_cuboid(l,b,h): return 2*(l*b+b*h+h*l) # Write a function to return the surface area of a sphere def cal_area_sphere(radius): pi = 3.14 return 4*pi*(radius**2) # Write a function to return the surface area of a hemi-sphere def cal_area_hemisphere(radius): pi = 3.14 return 2*pi*(radius**2) # Write a function to return the total surface area of a cylinder def cal_cylinder_surf_area(height,radius): pi=3.14 return 2*pi*radius**2*+2*pi*radius*height # Write a function to return the lateral surface area of a cone def cal_cone_lateral_surf_area(height,radius): pi=3.14 return pi*radius*(((height**2)+(radius**2))**(1/2)) # Write a function to return the volume of a cylinder def cal_cylinder_volume(height, radius): pi=3.14 return pi*(radius**2)*height # Write a function to return the volume of a cone def cal_cone_volume(height,radius): pi=3.14 return pi*(radius**2)*height/3 # Write a function to return the volume of a hemi sphere def cal_hemisphere_volume(radius:float)->float: pi=3.14 return (2/3)*pi*(radius**3) # Write a function to return the volume of a sphere def cal_sphere_volume(radius:float)->float: pi=3.14 return (4/3)*pi*(radius**3) # Write a function to return the volume of a cuboid def cal_cuboid_volume(length:float, breadth:float, height:float)->float: return length*breadth*height # Write a function to return the volume of a cube def cal_cube_volume(side:float)->float: return side**3 # Write a function to return the speed of moving object based of distance travelled in given time def cal_speed(distance:float,time:float)->float: return distance/time # Write a function to return the distance covered by a moving object based on speend and given time def cal_distance(time:float,speed:float)->float: return time*speed # Write a function to return the time taken by a given of moving object based of distance travelled in given time def cal_time(distance:float,speed:float)->float: return distance/speed # Write a function to return the torque when a force f is applied at angle thea and distance for axis of rotation to place force applied is r def cal_torque(force:float,theta:float,r:float)->float: import math return force*r*math.sin(theta) # Write a function to return the angualr veolcity based on augualr distance travelled in radian unit and time taken def cal_angular_velocity(angular_dist:float,time:float)->float: return angular_dist/time # Write a function to calculate the focal length of a lense buy the distance of object and distance of image from lense def cal_focal_length_of_lense(u:float,v:float)->float: return (u*v)/(u+v) # Write a function to calculate the gravitational force between two objects of mass m1 and m2 and distance of r between them def cal_gforce(mass1:float,mass2:float, distance:float)->float: g = 6.674*(10)**(-11) return (g*mass1*mass2)/(distance**2) # Write a function to calculate the current in the curcit where the resistance is R and voltage is V def cal_current(resistance:float, voltage:float)->float: return voltage/resistance # Write a function to calculate the total capacitance of capacitors in parallel in a given list def cal_total_cap_in_parallel(cap_list:list)->float: return sum(cap_list) # Write a function to calculate the total resistance of resistances in parallel in a given list def cal_total_res_in_parallel(res_list:list)->float: return sum([1/r for r in res_list]) # Write a function to calculate the total resistance of resistances in series in a given list def cal_total_res_in_series(res_list:list)->float: return sum(res_list) # Write a function to calculate the moment of inertia of a ring of mass M and radius R def cal_mi_ring(mass:float,radius:float)->float: return mass*(radius**2) # Write a function to calculate the moment of inertia of a sphere of mass M and radius R def cal_mi_sphere(mass:float,radius:float)->float: return (7/5)*mass*(radius**2) # Write a function to calculate the pressure P of ideal gas based on ideal gas equation - Volume V, and Temperatue T are given def find_pressure_of_ideal_gas(volume:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/volume # Write a function to calculate the volume V of ideal gas based on ideal gas equation Pressure P and Tempreature T given def find_volume_of_ideal_gas(pressure:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/pressure # Write a function to calculate the Temprature T of ideal gas based on ideal gas equation Pressure P and Volume V given def find_temp_of_ideal_gas(pressure:float, volume:float,n:float)->float: r = 8.3145 # gas constant R return (pressure*volume)/n*r # Write a function to calculate the velocity of an object with initial velocity u, time t and acceleration a def cal_final_velocity(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity + accelration*time # Write a function to calculate the displacement of an object with initial velocity u, time t and acceleration a def cal_displacement(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity*time + .5*accelration*(time)**2 # Write a function to calculate amount of radioactive element left based on initial amount and half life def cal_half_life(initail_quatity:float, time_elapsed:float, half_life:float)->float: return initail_quatity*((1/2)**(time_elapsed/half_life)) # Write a function to calculate the new selling price based on discount percentage def cal_sp_after_discount(sp:float,discount:float)->float: return sp*(1 - discount/100) # Write a function to calculate the simple interest for principal p, rate r and time in years y def get_si(p:float, r:float, t:float)->float: return (p*r*t)/100 # Write a function to calculate the compound interest for principal p, rate r and time in years y def get_ci(p:float, r:float, t:float, n:float)->float: return round(p*((1+(r/(n*100)))**(n*t)) - p,2) # Write a function to calculate the energy released by converting mass m in kg to energy def cal_energy_by_mass(mass:float)->float: c = 300000 return mass * (c**2) # Write a function to calculate the kinetic energy of an object of mass m and velocity v def cal_ke(mass:float,velocity:float)->float: return (mass*(velocity)**2)/2 # Write a function to calculate the potential energy of an object of mass m at height h def cal_pe(mass:float,height:float)->float: g = 9.8 return (mass*g*height) # Write a function to calculate the electrostatic force between two charged particles with charge q1 and q2 at a distance d apart def cal_electrostatic_force(q1,q2,d): k = 9*(10**9) return (k*q1*q2)/(d**2) # Write a function to calculate the density given mass and volume def cal_density(mass,volume): return (mass/volume) # Write a function to convert the temprature celsius 'c' to fahrenheit 'f' or fahrenheit to celsius def temp_converter(temp,temp_given_in = 'f'): # Return the converted temprature if temp_given_in.lower() == 'f': # Convert to C return (temp - 32) * (5/9) else: # Convert to F return (temp * 9/5) + 32 #python code to merge dictionaries def merge1(): test_list1 = [{"a": 1, "b": 4}, {"c": 10, "d": 15}, {"f": "gfg"}] test_list2 = [{"e": 6}, {"f": 3, "fg": 10, "h": 1}, {"i": 10}] print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) for idx in range(0, len(test_list1)): id_keys = list(test_list1[idx].keys()) for key in test_list2[idx]: if key not in id_keys: test_list1[idx][key] = test_list2[idx][key] print("The Merged Dictionary list : " + str(test_list1)) #python program for vertical concatenating of mqatrix def vertical_concatenation(): test_list = [["this","is"], ["program", "for"], ["vertical","concatenation"]] print("The original list : " + str(test_list)) res = [] N = 0 while N != len(test_list): temp = '' for idx in test_list: try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] print("List after column Concatenation : " + str(res)) vertical_concatenation() # Python code to Get Kth Column of Matrix def kth_column(test_list=[[4, 5, 6], [8, 1, 10], [7, 12, 5]],k=2): print("The original list is : " + str(test_list)) K =k res = list(zip(*test_list)[K]) print("The Kth column of matrix is : " + str(res)) # python code to print all possible subarrays using recursion def printSubArrays(arr, start, end): if end == len(arr): return elif start > end: return printSubArrays(arr, 0, end + 1) else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) arr = [1, 2, 3] printSubArrays(arr, 0, 0) # Python Program to find sum of nested list using Recursion total = 0 def sum_nestedlist(l): global total for j in range(len(l)): if type(l[j]) == list: sum_nestedlist(l[j]) else: total += l[j] sum_nestedlist([[1, 2, 3], [4, [5, 6]], 7]) print(total) #python program to find power of number using recursion def power(N, P): if (P == 0 or P == 1): return N else: return (N * power(N, P - 1)) print(power(5, 2)) # python program to Filter String with substring at specific position def f_substring(): test_list = ['program ', 'to', 'filter', 'for', 'substring'] print("The original list is : " + str(test_list)) sub_str = 'geeks' i, j = 0, 5 res = list(filter(lambda ele: ele[i: j] == sub_str, test_list)) print("Filtered list : " + str(res)) # python code to remove punctuation from the string def r_punc(): test_str = "end, is best : for ! Nlp ;" print("The original string is : " + test_str) punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~''' for ele in test_str: if ele in punc: test_str = test_str.replace(ele, "") print("The string after punctuation filter : " + test_str) # Python program to implement Gnome Sort def gnomeSort(arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index = index - 1 return arr arr = [34, 2, 10, -9] n = len(arr) arr = gnomeSort(arr, n) print("Sorted seqquence after applying Gnome Sort :") for i in arr: print(i) # Python program to implement Pigeonhole Sort */ def pigeonhole_sort(a): my_min = min(a) my_max = max(a) size = my_max - my_min + 1 holes = [0] * size for x in a: assert type(x) is int, "integers only please" holes[x - my_min] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3, 2, 7, 4, 6, 8] print("Sorted order is : ", end=" ") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end=" ") #python program to implement stooge sort def stoogesort(arr, l, h): if l >= h: return if arr[l] > arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t if h - l + 1 > 2: t = (int)((h - l + 1) / 3) stoogesort(arr, l, (h - t)) stoogesort(arr, l + t, (h)) stoogesort(arr, l, (h - t)) arr = [2, 4, 5, 3, 1] n = len(arr) stoogesort(arr, 0, n - 1) for i in range(0, n): print(arr[i], end= \' \') # Python program to find the difference between two times def difference(h1, m1, h2, m2): t1 = h1 * 60 + m1 t2 = h2 * 60 + m2 if (t1 == t2): print("Both are same times") return else: diff = t2 - t1 h = (int(diff / 60)) % 24 m = diff % 60 print(h, ":", m) difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) # Python program to convert time from 12 hour to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] print(convert24("08:05:45 PM")) # Python 3 program to find time for a given angle. def calcAngle(hh, mm): hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm angle = abs(hour_angle - minute_angle) angle = min(360 - angle, angle) return angle # python function to print all time when angle between hour hand and minute def printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm) == theta): print(hh, ":", mm, sep="") return print("Input angle not valid.") return theta = 90.0 printTime(theta) # write a python function to count number of times a function is called def counter(fn): count = 0 def inner(*args, **kwargs): nonlocal count count += 1 print(f'Function {fn.__name__} was called {count} times.') return fn(*"args, **kwargs) return inner # write a python function to remove duplicate items from the list def remove_duplicatesinlist(lst): return len(lst) == len(set(lst)) # write a python decorator function to find how much time user given function takes to execute def timed(fn): from time import perf_counter from functools import wraps @wraps(fn) def inner(*args, **kwargs): start = perf_counter() result = fn(*args, **kwargs) end = perf_counter() elapsed = end - start args_ = [str(a) for a in args] kwargs_ = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] all_args = args_ + kwargs_ args_str = ','.join(all_args) # now it is comma delimited print(f'{fn.__name__}({args_str}) took {elapsed} seconds') return result # inner = wraps(fn)(inner) return inner # write a python program to add and print two user defined list using map input_string = input("Enter a list element separated by space ") list1 = input_string.split() input_string = input("Enter a list element separated by space ") list2 = input_string.split() list1 = [int(i) for i in list1] list2 = [int(i) for i in list2] result = map(lambda x, y: x + y, list1, list2) print(list(result)) # write a python function to convert list of strings to list of integers def stringlist_to_intlist(sList): return(list(map(int, sList))) # write a python function to map multiple lists using zip def map_values(*args): return set(zip(*args)) # write a generator function in python to generate infinite square of numbers using yield def nextSquare(): i = 1; # An Infinite loop to generate squares while True: yield i*i i += 1 # write a python generator function for generating Fibonacci Numbers def fib(limit): # Initialize first two Fibonacci Numbers a, b = 0, 1 # One by one yield next Fibonacci Number while a < limit: yield a a, b = b, a + b # write a python program which takes user input tuple and prints length of each tuple element userInput = input("Enter a tuple:") x = map(lambda x:len(x), tuple(x.strip() for x in userInput.split(','))) print(list(x)) # write a python function using list comprehension to find even numbers in a list def find_evennumbers(input_list): list_using_comp = [var for var in input_list if var % 2 == 0] return list_using_comp # write a python function to return dictionary of two lists using zip def dict_using_comp(list1, list2): dict_using_comp = {key:value for (key, value) in zip(list1, list2)} return dict_using_comp #Write a function to get list of profanity words from Google profanity URL def profanitytextfile(): url = "https://github.com/RobertJGabriel/Google-profanity-words/blob/master/list.txt" html = urlopen(url).read() soup = BeautifulSoup(html, features="html.parser") textlist = [] table = soup.find('table') trs = table.find_all('tr') for tr in trs: tds = tr.find_all('td') for td in tds: textlist.append(td.text) return textlist #write a python program to find the biggest character in a string bigChar = lambda word: reduce(lambda x,y: x if ord(x) > ord(y) else y, word) #write a python function to sort list using heapq def heapsort(iterable): from heapq import heappush, heappop h = [] for value in iterable: heappush(h, value) return [heappop(h) for i in range(len(h))] # write a python function to return first n items of the iterable as a list def take(n, iterable): import itertools return list(itertools.islice(iterable, n)) # write a python function to prepend a single value in front of an iterator def prepend(value, iterator): import itertools return itertools.chain([value], iterator) # write a python function to return an iterator over the last n items def tail(n, iterable): from collections import deque return iter(deque(iterable, maxlen=n)) # write a python function to advance the iterator n-steps ahead def consume(iterator, n=None): import itertools from collections import deque "Advance the iterator n-steps ahead. If n is None, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(itertools.islice(iterator, n, n), None) # write a python function to return nth item or a default value def nth(iterable, n, default=None): from itertools import islice return next(islice(iterable, n, None), default) # write a python function to check whether all elements are equal to each other def all_equal(iterable): from itertools import groupby g = groupby(iterable) return next(g, True) and not next(g, False) # write a python function to count how many times the predicate is true def quantify(iterable, pred=bool): return sum(map(pred, iterable)) # write a python function to emulate the behavior of built-in map() function def pad_none(iterable): """Returns the sequence elements and then returns None indefinitely. Useful for emulating the behavior of the built-in map() function. """ from itertools import chain, repeat return chain(iterable, repeat(None)) # write a python function to return the sequence elements n times def ncycles(iterable, n): from itertools import chain, repeat return chain.from_iterable(repeat(tuple(iterable), n)) # write a python function to return the dot product of two vectors def dotproduct(vec1, vec2): return sum(map(operator.mul, vec1, vec2)) # write a python function to flatten one level of nesting def flatten(list_of_lists): from itertools import chain return chain.from_iterable(list_of_lists) # write a python function to repeat calls to function with specified arguments def repeatfunc(func, times=None, *args): from itertools import starmap, repeat if times is None: return starmap(func, repeat(args)) return starmap(func, repeat(args, times)) # write a python function to convert iterable to pairwise iterable def pairwise(iterable): from itertools import tee a, b = tee(iterable) next(b, None) return zip(a, b) # write a python function to collect data into fixed-length chunks or blocks def grouper(iterable, n, fillvalue=None): from itertools import zip_longest # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) # write a python program to create round robin algorithm: "roundrobin('ABC', 'D', 'EF') --> A D E B F C" def roundrobin(*iterables): from itertools import islice, cycle # Recipe credited to George Sakkis num_active = len(iterables) nexts = cycle(iter(it).__next__ for it in iterables) while num_active: try: for next in nexts: yield next() except StopIteration: # Remove the iterator we just exhausted from the cycle. num_active -= 1 nexts = cycle(islice(nexts, num_active)) # write a python function to use a predicate and return entries particition into false entries and true entries def partition(pred, iterable): from itertools import filterfalse, tee # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) # write a python function to return powerset of iterable def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" from itertools import chain, combinations s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) list(powerset([1,2,3])) # write a python function to list all unique elements, preserving order def unique_everseen(iterable, key=None): from itertools import filterfalse # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element # write a python function to list unique elements, preserving order remembering only the element just seen." def unique_justseen(iterable, key=None): import operator from itertools import groupby # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return map(next, map(operator.itemgetter(1), groupby(iterable, key))) # write a python function to call a function repeatedly until an exception is raised. def iter_except(func, exception, first=None): """Converts a call-until-exception interface to an iterator interface. Like builtins.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop. Examples: iter_except(s.pop, KeyError) # non-blocking set iterator """ try: if first is not None: yield first() # For database APIs needing an initial cast to db.first() while True: yield func() except exception: pass # write a python function to return random selection from itertools.product(*args, **kwds) def random_product(*args, repeat=1): import random pools = [tuple(pool) for pool in args] * repeat return tuple(map(random.choice, pools)) # write a python function to return random selection from itertools.permutations(iterable, r) def random_permutation(iterable, r=None): import random pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) # write a python function to random select from itertools.combinations(iterable, r) def random_combination(iterable, r): import random pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(range(n), r)) return tuple(pool[i] for i in indices) # write a python function to perform random selection from itertools.combinations_with_replacement(iterable, r) def random_combination_with_replacement(iterable, r): import random pool = tuple(iterable) n = len(pool) indices = sorted(random.choices(range(n), k=r)) return tuple(pool[i] for i in indices) # write a python function to locate the leftmost value exactly equal to x def index(a, x): from bisect import bisect_left i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError # write a python function to locate the rightmost value less than x def find_lt(a, x): from bisect import bisect_left i = bisect_left(a, x) if i: return a[i-1] raise ValueError # write a python function to find rightmost value less than or equal to x def find_le(a, x): from bisect import bisect_right i = bisect_right(a, x) if i: return a[i-1] raise ValueError # write a python function to find leftmost value greater than x def find_gt(a, x): from bisect import bisect_right i = bisect_right(a, x) if i != len(a): return a[i] raise ValueError # write a python function to find leftmost item greater than or equal to x def find_ge(a, x): from bisect import bisect_left i = bisect_left(a, x) if i != len(a): return a[i] raise ValueError # write a python function to map a numeric lookup using bisect def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): from bisect import bisect i = bisect(breakpoints, score) return grades[i] # write a regex pattern in python to print all adverbs and their positions in user input text import re text = input("Enter a string: ") for m in re.finditer(r"\w+ly", text): print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) # write a python function to read a CSV file and print its content def read_csv(filename): import csv with open(filename, newline='') as f: reader = csv.reader(f) for row in reader: print(row) # write a python snippet to convert list into indexed tuple test_list = [4, 5, 8, 9, 10] list(zip(range(len(test_list)), test_list)) # write a python function to split word into chars def split(word): return [char for char in word] # write a python function to pickle data to a file def pickle_data(data, pickle_file): import pickle with open(pickle_file, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) return None # write a python function to load pickle data from a file def load_pickle_data(pickle_file): import pickle with open(pickle_file, 'rb') as f: data = pickle.load(f) return data # Write a function that adds 2 iterables a and b such that a is even and b is odd def add_even_odd_list(l1:list,l2:list)-> list: return [a+b for a,b in zip(l1,l2) if a%2==0 and b%2!=0] # Write a function that strips every vowel from a string provided def strip_vowels(input_str:str)->str: vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ] return ''.join(list(filter(lambda x: x not in vowels, input_str))) # write a function that acts like a ReLU function for a 1D array def relu_list(input_list:list)->list: return [(lambda x: x if x >= 0 else 0)(x) for x in input_list] # Write a function that generates Factorial of number def factorial(n): if n == 0 or n ==1: return 1 else: return n*factorial(n-1) # Write a function that returns length of the list def list_length(l): return len(l) # Write a function that sorts list of numbers and returns top element def biggest_no(l:list)->int: sorted(l) # Write a function to print a string by repeating it n times def print_repeatnstring(text:str, n:int)-> str: return text*n # Write a function to merge two lists element wise def merge_lists(l1:list, l2:list): return list(zip(l1,l2)) # Write a function to merge two lists element wise def merge_lists(l1:list, l2:list): return list(zip(l1,l2)) # Write a function to append two lists def append_lists(l1:list, l2:list)->list: return l1.extend(l2) # Write a function to return reverse of a list def reverse_list(l1:list)->list: return l1[::-1] # Write a function to adds two lists element wise def adds_listelements(l1:list, l2:list): return [i+j for i, j in zip(l1,l2)] # Write a function to Subtracts two lists element wise def sub_listelements(l1:list, l2:list): return [i-j for i, j in zip(l1,l2)] # Write a function to adds two lists element wise only if numbers are even def adds_listevenelements(l1:list, l2:list): return [i+j for i, j in zip(l1,l2) if i*j%2 == 0] # Write a function to multiplies two lists element wise only if numbers are odd def adds_listoddelements(l1:list, l2:list): return [i*j for i, j in zip(l1,l2) if i*j%2 == 1] # Write a function that returns list of elements with n power to elements of list def n_power(l1:list, power:int)->list: return [i**power for i in l1] # Write a function that generates fibbonacci series def Fibonacci(n:int)-> int: if n==1: fibonacci = 0 elif n==2: fibonacci = 1 else: fibonacci = Fibonacci(n-1) + Fibonacci(n-2) return fibonacci # Write a function that returns sine value of the input def sin(x:float) -> float: import math return math.sin(x) # Write a function that returns derivative of sine value of the input def derivative_sin(x:float)-> float: import math return math.cos(x) # Write a function that returns tan value of the input def tan(x:float) -> float: import math return math.tan(x) # Write a function that returns derivative of tan value of the input def derivative_tan(x:float)-> float: import math return (1/math.cos(x))**2 # Write a function that returns cosine value of the input def cos(x:float) -> float: import math return math.cos(x) # Write a function that returns cosine value of the input def derivative_cos(x:float)-> float: import math return -(math.sin(x)) # Write a function that returns the exponential value of the input def exp(x) -> float: import math return math.exp(x) # Write a function that returns Gets the derivative of exponential of x def derivative_exp(x:float) -> float: import math return math.exp(x) # Write a function that returns log of a function def log(x:float)->float: import math return math.log(x) # Write a function that returns derivative of log of a function def derivative_log(x:float)->float: return (1/x) # Write a function that returns relu value of the input def relu(x:float) -> float: x = 0 if x < 0 else x return x # Write a function that returns derivative derivative relu value of the input def derivative_relu(x:float) -> float: x = 1 if x > 0 else 0 return x # Write a function that returns runs a garbage collector def clear_memory(): import gc gc.collect() # Write a function that calculates the average time taken to perform any transaction by Function fn averaging the total time taken for transaction over Repetations def time_it(fn, *args, repetitons= 1, **kwargs): import time total_time = [] for _ in range(repetitons): start_time = time.perf_counter() fn(*args,**kwargs) end_time = time.perf_counter() ins_time = end_time - start_time total_time.append(ins_time) return sum(total_time)/len(total_time) # Write a function to identify if value is present inside a dictionary or not def check_value(d:dict, value)->bool: return any(v == value for v in dict.values()) # Write a function to identify to count no of instances of a value inside a dictionary def count_value(d:dict, value)->bool: return list(v == value for v in dict.values()).count(True) # Write a function to identify if value is present inside a list or not def check_listvalue(l:list, value)->bool: return value in l # Write a function to identify if value is present inside a tuple or not def check_tuplevalue(l:tuple, value)->bool: return value in l # Write a function that returns lowercase string def str_lowercase(s:str): return s.lower() # Write a function that returns uppercase string def str_uppercase(s:str): return s.upper() # Write a function that removes all special characters def clean_str(s): import re return re.sub('[^A-Za-z0-9]+', '', s) # Write a function that returns a list sorted ascending def ascending_sort(l:list): sorted(l, reverse=False) # Write a function that returns a list sorted descending def descending_sort(l:list): sorted(l, reverse=True) # Write a function that returns a dictionary sorted descending by its values def descending_dict_valuesort(d:dict): return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[1])} # Write a function that returns a dictionary sorted ascending by its values def ascending_dict_valuesort(d:dict): return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1])} # Write a function that returns a dictionary sorted descending by its keys def descending_dict_keysort(d:dict): return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[0])} # Write a function that returns a dictionary sorted ascending by its keys def ascending_dict_keysort(d:dict): return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[0])} # Write a function that returns a replace values in string with values provided def replace_values(s:str, old, new)->str: s.replace(old, new) # Write a function that joins elements of list def join_elements(l:list)-> str: return (''.join(str(l))) # Write a function that splits the elements of string def split_elements(s:str, seperator)-> list: return s.split(seperator) # Write a function that returns sum of all elements in the list def sum_elements(l:list): return sum(l) # Write a function that returns sum of all odd elements in the list def sum_even_elements(l:list): return sum([i for i in l if i%2==0]) # Write a function that returns sum of all odd elements in the list def sum_odd_elements(l:list): return sum([i for i in l if i%2==1]) #1 write a program to reverse a list lst = [11, 5, 17, 18, 23] def reverse(lst): new_lst = lst[::-1] return new_lst #2 write a program to find sum of elements in list list1 = [11, 5, 17, 18, 23] total = sum(list1) print("Sum of all elements in given list: ", total) #3 write a program to find the largest number in a list list1 = [10, 20, 4, 45, 99] list1.sort() print("Largest element is:", list1[-1]) #4 write a program to print Even Numbers in a List list1 = [10, 21, 4, 45, 66, 93] for num in list1: if num % 2 == 0: print(num, end = " ") #5 write a program to print negative Numbers in given range start, end = -4, 19 for num in range(start, end + 1): if num < 0: print(num, end = " ") #6 write a program to remove empty List from List using list comprehension test_list = [5, 6, [], 3, [], [], 9] print("The original list is : " + str(test_list)) res = [ele for ele in test_list if ele != []] print ("List after empty list removal : " + str(res)) #7 write a program to remove empty tuples from a list of tuples def Remove(tuples): tuples = filter(None, tuples) return tuples # Driver Code tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()] print Remove(tuples) #8 write a program to break a list into chunks of size N l = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 4 x = [l[i:i + n] for i in range(0, len(l), n)] print(x) #9 write a program to find the frequency of words present in a string test_str = 'times of india times new india express' print("The original string is : " + str(test_str)) res = {key: test_str.count(key) for key in test_str.split()} print("The words frequency : " + str(res)) #10 write a program to accept a string if it contains all vowels def check(string): if len(set(string).intersection("AEIOUaeiou"))>=5: return ('accepted') else: return ("not accepted") if __name__=="__main__": string="helloworld" print(check(string)) #11 write a program to rotate string left and right by d length def rotate(input,d): Lfirst = input[0 : d] Lsecond = input[d :] Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] print ("Left Rotation : ", (Lsecond + Lfirst) ) print ("Right Rotation : ", (Rsecond + Rfirst)) if __name__ == "__main__": input = 'helloworld' d=2 rotate(input,d) #12 write a program to convert key-values list to flat dictionary from itertools import product test_dict = {'month' : [1, 2, 3], 'name' : ['Jan', 'Feb', 'March']} print("The original dictionary is : " + str(test_dict)) res = dict(zip(test_dict['month'], test_dict['name'])) print("Flattened dictionary : " + str(res)) # write a program to remove the duplicate words s = "Hello world Hello" l = s.split() k = [] for i in l: if (s.count(i)>1 and (i not in k)or s.count(i)==1): k.append(i) print(' '.join(k)) #13 write a program to convert into dictionary def Convert(tup, di): for a, b in tup: di.setdefault(a, []).append(b) return di tups = [("A", 10), ("B", 20), ("C", 30), ("D", 40), ("E", 50), ("F", 60)] dictionary = {} print (Convert(tups, dictionary)) #14 write program to extract digits from Tuple list from itertools import chain test_list = [(15, 3), (3, 9), (1, 10), (99, 2)] print("The original list is : " + str(test_list)) temp = map(lambda ele: str(ele), chain.from_iterable(test_list)) res = set() for sub in temp: for ele in sub: res.add(ele) print("The extrated digits : " + str(res)) #15 write a program to Remove Tuples of Length K Using list comprehension test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] print("The original list : " + str(test_list)) K = 1 res = [ele for ele in test_list if len(ele) != K] print("Filtered list : " + str(res)) #16 write a program to find Maximum and Minimum K elements in Tuple test_tup = (5, 20, 3, 7, 6, 8) print("The original tuple is : " + str(test_tup)) K = 2 test_tup = list(test_tup) temp = sorted(test_tup) res = tuple(temp[:K] + temp[-K:]) print("The extracted values : " + str(res)) #17 write a program to get current date and time import datetime current_time = datetime.datetime.now() print ("Time now at greenwich meridian is : " , end = "") print (current_time) #18 write a program to convert time from 12 hour to 24 hour format def convert24(str1): # Checking if last two elements of time # is AM and first two elements are 12 if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] # remove the AM elif str1[-2:] == "AM": return str1[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: # add 12 to hours and remove PM return str(int(str1[:2]) + 12) + str1[2:8] # Driver Code print(convert24("08:05:45 PM")) #19 write a program to find the difference between two times # function to obtain the time in minutes form def difference(h1, m1, h2, m2): # convert h1 : m1 into minutes t1 = h1 * 60 + m1 # convert h2 : m2 into minutes t2 = h2 * 60 + m2 if (t1 == t2): print("Both are same times") return else: # calculating the difference diff = t2-t1 # calculating hours from difference h = (int(diff / 60)) % 24 # calculating minutes from difference m = diff % 60 print(h, ":", m) # Driver's code if __name__ == "__main__": difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) #20 write program to find yesterday, today and tomorrow # Import datetime and timedelta # class from datetime module from datetime import datetime, timedelta # Get today's date presentday = datetime.now() # or presentday = datetime.today() # Get Yesterday yesterday = presentday - timedelta(1) # Get Tomorrow tomorrow = presentday + timedelta(1) # strftime() is to format date according to # the need by converting them to string print("Yesterday = ", yesterday.strftime('%d-%m-%Y')) print("Today = ", presentday.strftime('%d-%m-%Y')) print("Tomorrow = ", tomorrow.strftime('%d-%m-%Y')) #21 write a program to remove all the characters except numbers and alphabets import re # initialising string ini_string = "123abcjw:, .@! eiw" # printing initial string print ("initial string : ", ini_string) result = re.sub('[\W_]+', '', ini_string) # printing final string print ("final string", result) #22 write a program to merge dict using update() method def Merge(dict1, dict2): return(dict2.update(dict1)) # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} print(Merge(dict1, dict2)) print(dict2) #23 write a program to print even length words in a string def printWords(s): s = s.split(' ') for word in s: if len(word)%2==0: print(word) # Driver Code s = "hello world" printWords(s) #24 write a program to delete all duplicate letters in a string def removeDuplicate(str): s=set(str) s="".join(s) print("Without Order:",s) t="" for i in str: if(i in t): pass else: t=t+i print("With Order:",t) str="helloworld" removeDuplicate(str) #25 write a program to print Maximum frequency character in String # initializing string test_str = "Helloworld" print ("The original string is : " + test_str) all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = max(all_freq, key = all_freq.get) print ("The maximum of all characters in Helloworld is : " + str(res)) #26 write a program to check if a string contains any special character import re def run(string): regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') if(regex.search(string) == None): print("String is accepted") else: print("String is not accepted.") if __name__ == '__main__' : # Enter the string string = "Hello@World" # calling run function run(string) #27 write a program to check if a string is binary or not def check(string) : p = set(string) s = {'0', '1'} if s == p or p == {'0'} or p == {'1'}: print("Yes") else : print("No") # driver code if __name__ == "__main__" : string = "101010000111" check(string) #28 write a program to check whether a given string is Heterogram or not def heterogram(input): alphabets = [ ch for ch in input if ( ord(ch) >= ord('a') and ord(ch) <= ord('z') )] if len(set(alphabets))==len(alphabets): print ('Yes') else: print ('No') # Driver program if __name__ == "__main__": input = 'Hello World' heterogram(input) #29 write a program to check whether a given key already exists in a dictionary. def checkKey(dict, key): if key in dict.keys(): print("Present, ", end =" ") print("value =", dict[key]) else: print("Not present") # Driver Code dict = {'a': 100, 'b':200, 'c':300} key = 'b' checkKey(dict, key) key = 'w' checkKey(dict, key) #30 write a program to check whether the string is a palindrome or not def isPalindrome(s): return s == s[::-1] s = "malayalam" ans = isPalindrome(s) if ans: print("Yes") else: print("No") #31 write a program that extract words starting with Vowel From A list # initializing list test_list = ["have", "a", "good", "one"] # printing original list print("The original list is : " + str(test_list)) res = [] vow = "aeiou" for sub in test_list: flag = False # checking for begin char for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) # printing result print("The extracted words : " + str(res)) #32 write a program to replace vowels by next vowel using list comprehension + zip() test_str = 'helloworld' print("The original string is : " + str(test_str)) vow = 'a e i o u'.split() temp = dict(zip(vow, vow[1:] + [vow[0]])) res = "".join([temp.get(ele, ele) for ele in test_str]) print("The replaced string : " + str(res)) #33 write a program to reverse words of string def rev_sentence(sentence): words = sentence.split(' ') reverse_sentence = ' '.join(reversed(words)) return reverse_sentence if __name__ == "__main__": input = 'have a good day' print (rev_sentence(input)) #34 write a program to find the least Frequent Character in String test_str = "helloworld" print ("The original string is : " + test_str) all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print ("The minimum of all characters in the given word is : " + str(res)) #35 write a program to find the most frequent element in a list def most_frequent(List): counter = 0 num = List[0] for i in List: curr_frequency = List.count(i) if(curr_frequency> counter): counter = curr_frequency num = i return num List = [2, 1, 2, 2, 1, 3] print(most_frequent(List)) #36 write a program insert character after every character pair # initializing string test_str = "HellowWorld" print("The original string is : " + test_str) res = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2)) print("The string after inserting comma after every character pair : " + res) #37 write a program to remove i-th indexed character from a string def remove(string, i): a = string[ : i] b = string[i + 1: ] return a + b # Driver Code if __name__ == '__main__': string = "HellowWorld" # Remove nth index element i = 5 # Print the new string print(remove(string, i)) #38 write a program to check if a string has at least one letter and one number def checkString(str): flag_l = False flag_n = False for i in str: # if string has letter if i.isalpha(): flag_l = True # if string has number if i.isdigit(): flag_n = True return flag_l and flag_n # driver code print(checkString('helloworld')) print(checkString('helloworld2020')) #39 write a program extract least frequency element from collections import defaultdict test_list = [1, 3, 4, 5, 1, 3, 5] # printing original list print("The original list : " + str(test_list)) # Extract least frequency element res = defaultdict(int) for ele in test_list: res[ele] += 1 min_occ = 9999 for ele in res: if min_occ > res[ele]: min_occ = res[ele] tar_ele = ele # printing result print("The minimum occurring element is : " + str(tar_ele)) #40 write a program to check 2 lists and find if any element is common def common_data(list1, list2): result = False for x in list1: # traverse in the 2nd list for y in list2: # if one common if x == y: result = True return result return result # driver code a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] print(common_data(a, b)) a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9] print(common_data(a, b)) #41 write a program to find area of a triangle a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) s = (a + b + c) / 2 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) #42 write a program to swap two variables x = input('Enter value of x: ') y = input('Enter value of y: ') temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) #43 write a program to convert kilometers to miles kilometers = float(input('How many kilometers?: ')) conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) #44 write a program to convert Celsius to Fahrenheit celsius = float(input('Enter temperature in Celsius: ')) fahrenheit = (celsius * 1.8) + 32 print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit)) #45 write a program to display the calender import calendar yy = int(input("Enter year: ")) mm = int(input("Enter month: ")) print(calendar.month(yy,mm)) #46 write a program to check if the year is a leap year year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) #47 write a program to check if the number is a prime numnber num = int(input("Enter a number: ")) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") #48 write a program to print all prime numbers between an interval lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower,upper + 1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num) #49 write a program to find the factorial of a number num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) #50 write a program to display the multiplication table of a number num = int(input("Show the multiplication table of? ")) # using for loop to iterate multiplication 10 times for i in range(1,11): print(num,'x',i,'=',num*i) #51 write a program to print Fibonacci sequence nterms = int(input("How many terms you want? ")) # first two terms n1 = 0 n2 = 1 count = 2 # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") elif nterms == 1: print("Fibonacci sequence:") print(n1) else: print("Fibonacci sequence:") print(n1,",",n2,end=', ') while count < nterms: nth = n1 + n2 print(nth,end=' , ') # update values n1 = n2 n2 = nth count += 1 #52 write a program to check Armstrong number num = int(input("Enter a number: ")) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #53 write a program to find Armstrong number in an interval lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower,upper + 1): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num) #54 write a program to find the sum of natural numbers num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print("The sum is",sum) #55 write a program to find LCM def lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)) #56 write a program to find HCF def hcf(x, y): if x > y: smaller = y else: smaller = x for i in range(1,smaller + 1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2)) #57 write a program to convert decimal to binary, octal and hexadecimal dec = int(input("Enter a decimal number: ")) print(bin(dec),"in binary.") print(oct(dec),"in octal.") print(hex(dec),"in hexadecimal." #58 python program to find ascii value of a character c = input("Enter a character: ") print("The ASCII value of '" + c + "' is",ord(c)) #59 write a program to make a simple calculator # define functions def add(x, y): """This function adds two numbers""" return x + y def subtract(x, y): """This function subtracts two numbers""" return x - y def multiply(x, y): """This function multiplies two numbers""" return x * y def divide(x, y): """This function divides two numbers""" return x / y # take input from the user print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") #60 write a program to sort words in alphabetic order my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() # sort the list words.sort() # display the sorted words for word in words: print(word) #61 write a program to print the elements of an array present on even position arr = [1, 2, 3, 4, 5]; print("Elements of given array present on even position: "); for i in range(1, len(arr), 2): print(arr[i]); #62 write a program to sort the elements of the array arr = [5, 2, 8, 7, 1]; temp = 0; print("Elements of original array: "); for i in range(0, len(arr)): print(arr[i], end=" "); for i in range(0, len(arr)): for j in range(i+1, len(arr)): if(arr[i] > arr[j]): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; print(); print("Elements of array sorted in ascending order: "); for i in range(0, len(arr)): print(arr[i], end=" "); #63 write a program to check if the given number is a disarium number def calculateLength(n): length = 0; while(n != 0): length = length + 1; n = n//10; return length; num = 175; rem = sum = 0; len = calculateLength(num); n = num; while(num > 0): rem = num%10; sum = sum + int(rem**len); num = num//10; len = len - 1; if(sum == n): print(str(n) + " is a disarium number"); else: print(str(n) + " is not a disarium number"); #64 write a program to print all disarium numbers between 1 and 100 def calculateLength(n): length = 0; while(n != 0): length = length + 1; n = n//10; return length; def sumOfDigits(num): rem = sum = 0; len = calculateLength(num); while(num > 0): rem = num%10; sum = sum + (rem**len); num = num//10; len = len - 1; return sum; result = 0; print("Disarium numbers between 1 and 100 are"); for i in range(1, 101): result = sumOfDigits(i); if(result == i): print(i), #65 write a program to add two matrices using nested loop X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) #66 write a program to transpose a matrix using a nested loop X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) #67 write a program to multiply two matrices using nested loops X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) #68 write a program to remove punctuation from a string punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) #69 write a program to shuffle a deck of card import itertools, random deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) random.shuffle(deck) print("You got:") for i in range(5): print(deck[i][0], "of", deck[i][1]) #70 write a program to display the powers of 2 using anonymous function terms = 10 result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) #71 write a program to add 2 binary numbers num1 = '00001' num2 = '10001' sum = bin(int(num1,2) + int(num2,2)) print(sum) #71 write a program to find simple interest p = float(input("Enter the principle amount : ")) r = float(input("Enter the rate of interest : ")) t = float(input("Enter the time in the years: ")) # calculating simple interest si = (p*r*t)/100 # printing the values print("Principle amount: ", p) print("Interest rate : ", r) print("Time in years : ", t) print("Simple Interest : ", si) #72 write a program to find compound interest p = float(input("Enter the principle amount : ")) r = float(input("Enter the rate of interest : ")) t = float(input("Enter the time in the years: ")) # calculating compound interest ci = p * (pow((1 + r / 100), t)) # printing the values print("Principle amount : ", p) print("Interest rate : ", r) print("Time in years : ", t) print("compound Interest : ", ci) #73 write a program to print a pattern of stars (*) for row in range (0,5): for column in range (0, row+1): print ("*", end="") # ending row print('\r') #74 write a program to return the absolute value in Python def get_absolute_value(n): if n >= 0: return n else: return -n print(get_absolute_value(101)) #75 write a program to find the power of a number a = 10 b = 3 result = a**b print (a, " to the power of ", b, " is = ", result) #76 write a program to print the binary value of the numbers from 1 to N n = int(input("Enter the value of N: ")) for i in range(1, n+1): print("Binary value of ", i, " is: ", bin(i)) #77 write a program to find number of bits necessary to represent an integer in binary num = int(input("Enter an integer number: ")) bits = num.bit_length() print("bits required to store ", num, " = ", bits) print("binary value of ", num, " is = ", bin(num)) #78 write a program to find the difference between 2 lists list1 = [10, 20, 30, 40, 50] list2 = [10, 20, 30, 60, 70] print "list1:", list1 print "list2:", list2 print "Difference elements:" print (list (set(list1) - set (list2))) #79 write a program to add an element at specified index in a list list = [10, 20, 30] print (list) list.insert (1, "ABC") print (list) list.insert (3, "PQR") print (list) #80 write a program to print EVEN length words of a string str = "Python is a programming language" words = list(str.split(' ')) print "str: ", str print "list converted string: ", words print "EVEN length words:" for W in words: if(len(W)%2==0 ): print W #81 write a program to create N copies of a given string str1 = "Hello" n = 3 str2 = str1 * 3 print "str1: ", str1 print "str2: ", str2 #82 write a program to extract the mobile number from the given string in Python # importing the module import re # string string='''hello you can call me at 018002089898.''' # extracting the mobile number Phonenumber=re.compile(r'\d\d\d\d\d\d\d\d\d\d\d\d') m=Phonenumber.search(string) # printing the result print('mobile number found from the string : ',m.group()) #83 write a program to Capitalizes the first letter of each word in a string def capitalize(text): return text.title() str1 = "Hello world!" str2 = "hello world!" str3 = "HELLO WORLD!" str4 = "includehelp.com is a tutorials site" print("str1: ", str1) print("str2: ", str2) print("str3: ", str3) print("str4: ", str4) print() #84 write a program to design a dice throw function import random def dice(): return random.choice([1,2,3,4,5,6]) #85 write a program to print perfect numbers from the given list of integers def checkPerfectNum(n) : i = 2;sum = 1; while(i <= n//2 ) : if (n % i == 0) : sum += i i += 1 if sum == n : print(n,end=' ') if __name__ == "__main__" : print("Enter list of integers: ") list_of_intgers = list(map(int,input().split())) print("Given list of integers:",list_of_intgers) print("Perfect numbers present in the list is: ") for num in list_of_intgers : checkPerfectNum(num) #86 write a program to convert meters into yards num = float(input("Enter the distance measured in centimeter : ")) inc = num/2.54 print("Distance in inch : ", inc) #87 write a program Tower of Hanoi def hanoi(x): global repN repN += 1 if x == 1: return 2 else: return 3*hanoi(x-1) + 2 x = int(input("ENTER THE NUMBER OF DISKS: ")) global repN repN =0 print('NUMBER OF STEPS: ', hanoi(x), ' :', repN) #88 write a program to find variance of a dataset def variance(X): mean = sum(X)/len(X) tot = 0.0 for x in X: tot = tot + (x - mean)**2 return tot/len(X) # main code # a simple data-set sample = [1, 2, 3, 4, 5] print("variance of the sample is: ", variance(sample)) #89 write a program to find winner of the day def find_winner_of_the_day(*match_tuple): team1_count = 0 team2_count = 0 for team_name in match_tuple : if team_name == "Team1" : team1_count += 1 else : team2_count += 1 if team1_count == team2_count : return "Tie" elif team1_count > team2_count : return "Team1" else : return "Team2" if __name__ == "__main__" : print(find_winner_of_the_day("Team1","Team2","Team1")) print(find_winner_of_the_day("Team1","Team2","Team1","Team2")) print(find_winner_of_the_day("Team1","Team2","Team2","Team1","Team2")) #90 write a program for swapping the value of two integers without third variable x = int(input("Enter the value of x :")) y = int(input("Enter the value of y :")) (x,y) = (y,x) print('Value of x: ', x, '\nValue of y: ', y, '\nWOO!! Values SWAPPEDDD') #91 write a program to check eligibility for voting # input age age = int(input("Enter Age : ")) if age>=18: status="Eligible" else: status="Not Eligible" print("You are ",status," for Vote.") #92 write a program to print the version information import sys print("Python version: ", sys.version) print("Python version info: ", sys.version_info) #93 write a program to find sum of all digits of a number def sumDigits(num): if num == 0: return 0 else: return num % 10 + sumDigits(int(num / 10)) x = 0 print("Number: ", x) print("Sum of digits: ", sumDigits(x)) print() #94 write a program to print double quotes with the string variable str1 = "Hello world"; print("\"%s\"" % str1) print('"%s"' % str1) print('"{}"'.format(str1)) #95 write a program to Remove leading zeros from an IP address import re def removeLeadingZeros(ip): modified_ip = re.sub(regex, '.', ip) print(modified_ip) if __name__ == '__main__' : ip = "216.08.094.196" removeLeadingZeros(ip) #96 write a program for binary search def binary_search(l, num_find): start = 0 end = len(l) - 1 mid = (start + end) // 2 found = False position = -1 while start <= end: if l[mid] == num_find: found = True position = mid break if num_find > l[mid]: start = mid + 1 mid = (start + end) // 2 else: end = mid - 1 mid = (start + end) // 2 return (found, position) if __name__=='__main__': l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] num = 6 found = binary_search(l, num) if found[0]: print('Number %d found at position %d'%(num, found[1]+1)) else: print('Number %d not found'%num) #97 write a program to copy odd lines of one file to another file file1 = open('file1.txt', 'r') file2 = open('file2.txt', 'w') lines = file1.readlines() type(lines) for i in range(0, len(lines)): if(i % 2 != 0): file2.write(lines[i]) file1.close() file2.close() file1 = open('file1.txt', 'r') file2 = open('file2.txt', 'r') str1 = file1.read() str2 = file2.read() print("file1 content...") print(str1) print() # to print new line print("file2 content...") print(str2) file1.close() file2.close() #98 write a program to reverse a string that contains digits in Python def reverse(n): s=str(n) p=s[::-1] return p num = int(input('Enter a positive value: ')) print('The reverse integer:',reverse(num)) #99 write a program to input a string and find total number uppercase and lowercase letters print("Input a string: ") str1 = input() no_of_ucase, no_of_lcase = 0,0 for c in str1: if c>='A' and c<='Z': no_of_ucase += 1 if c>='a' and c<='z': no_of_lcase += 1 print("Input string is: ", str1) print("Total number of uppercase letters: ", no_of_ucase) print("Total number of lowercase letters: ", no_of_lcase) #100 write a program to input a string and find total number of letters and digits print("Input a string: ") str1 = input() no_of_letters, no_of_digits = 0,0 for c in str1: if (c>='a' and c<='z') or (c>='A' and c<='Z'): no_of_letters += 1 if c>='0' and c<='9': no_of_digits += 1 print("Input string is: ", str1) print("Total number of letters: ", no_of_letters) print("Total number of digits: ", no_of_digits) # Write a python function to implement tower of hanoi def hanoi(disks, source, auxiliary, target): if disks == 1: print('Move disk 1 from peg {} to peg {}.'.format(source, target)) return hanoi(disks - 1, source, target, auxiliary) print('Move disk {} from peg {} to peg {}.'.format(disks, source, target)) hanoi(disks - 1, auxiliary, source, target) # Write a python program to implement a Stack using One Queue class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self, data): self.q.enqueue(data) def pop(self): for _ in range(self.q.get_size() - 1): dequeued = self.q.dequeue() self.q.enqueue(dequeued) return self.q.dequeue() class Queue: def __init__(self): self.items = [] self.size = 0 def is_empty(self): return self.items == [] def enqueue(self, data): self.size += 1 self.items.append(data) def dequeue(self): self.size -= 1 return self.items.pop(0) def get_size(self): return self.size s = Stack() print('Menu') print('push ') print('pop') print('quit') while True: do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': s.push(int(do[1])) elif operation == 'pop': if s.is_empty(): print('Stack is empty.') else: print('Popped value: ', s.pop()) elif operation == 'quit': break # Write a python program to implement Dequeue class Dequeue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def append(self, data): self.items.append(data) def append_left(self, data): self.items.insert(0, data) def pop(self): return self.items.pop() def pop_left(self): return self.items.pop(0) q = Dequeue() print('Menu') print('append ') print('appendleft ') print('pop') print('popleft') print('quit') while True: do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'append': q.append(int(do[1])) elif operation == 'appendleft': q.append_left(int(do[1])) elif operation == 'pop': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from right: ', q.pop()) elif operation == 'popleft': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from left: ', q.pop_left()) elif operation == 'quit': break # Write a python program to Check and print if string is palindrome using Stack class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() s = Stack() text = "ABA" for character in text: s.push(character) reversed_text = '' while not s.is_empty(): reversed_text = reversed_text + s.pop() if text == reversed_text: print('The string is a palindrome.') else: print('The string is not a palindrome.') # Write a python program to Check and print if Expression is Correctly Parenthesized using Stack class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() s = Stack() exp = "(x+y" for c in exp: if c == '(': s.push(1) elif c == ')': if s.is_empty(): is_balanced = False break s.pop() else: if s.is_empty(): is_balanced = True else: is_balanced = False if is_balanced: print('Expression is correctly parenthesized.') else: print('Expression is not correctly parenthesized.') # Write a python program to Implement Linear Search and print the key element if found def linear_search(alist, key): """Return index of key in alist. Return -1 if key not present.""" for i in range(len(alist)): if alist[i] == key: return i return -1 alist = [2, 3, 5, 6, 4, 5] key = 6 index = linear_search(alist, key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Binary Search without Recursion and print the key element if found def binary_search(alist, key): """Search key in alist[start... end - 1].""" start = 0 end = len(alist) while start < end: mid = (start + end)//2 if alist[mid] > key: end = mid elif alist[mid] < key: start = mid + 1 else: return mid return -1 alist = [2, 3, 5, 6, 4, 5] key = 6 index = binary_search(alist, key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Binary Search with Recursion and print the key element if found def binary_search_rec(alist, start, end, key): """Search key in alist[start... end - 1].""" if not start < end: return -1 mid = (start + end)//2 if alist[mid] < key: return binary_search_rec(alist, mid + 1, end, key) elif alist[mid] > key: return binary_search_rec(alist, start, mid, key) else: return mid alist = [2, 3, 5, 6, 4, 5] key = 6 index = binary_search_rec(alist, 0, len(alist), key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Bubble sort and print the sorted list for the below list def bubble_sort(alist): for i in range(len(alist) - 1, 0, -1): no_swap = True for j in range(0, i): if alist[j + 1] < alist[j]: alist[j], alist[j + 1] = alist[j + 1], alist[j] no_swap = False if no_swap: return alist = [2, 3, 5, 6, 4, 5] bubble_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Selection sort and print the sorted list for the below list def selection_sort(alist): for i in range(0, len(alist) - 1): smallest = i for j in range(i + 1, len(alist)): if alist[j] < alist[smallest]: smallest = j alist[i], alist[smallest] = alist[smallest], alist[i] alist = [2, 3, 5, 6, 4, 5] selection_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Insertion sort and print the sorted list for the below list def insertion_sort(alist): for i in range(1, len(alist)): temp = alist[i] j = i - 1 while (j >= 0 and temp < alist[j]): alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = temp alist = [2, 3, 5, 6, 4, 5] insertion_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Merge sort and print the sorted list for the below list def merge_sort(alist, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: mid = (start + end)//2 merge_sort(alist, start, mid) merge_sort(alist, mid, end) merge_list(alist, start, mid, end) def merge_list(alist, start, mid, end): left = alist[start:mid] right = alist[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): alist[k] = left[i] i = i + 1 else: alist[k] = right[j] j = j + 1 k = k + 1 if start + i < mid: while k < end: alist[k] = left[i] i = i + 1 k = k + 1 else: while k < end: alist[k] = right[j] j = j + 1 k = k + 1 alist = [2, 3, 5, 6, 4, 5] merge_sort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Quicksort and print the sorted list for the below list def quicksort(alist, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: p = partition(alist, start, end) quicksort(alist, start, p) quicksort(alist, p + 1, end) def partition(alist, start, end): pivot = alist[start] i = start + 1 j = end - 1 while True: while (i <= j and alist[i] <= pivot): i = i + 1 while (i <= j and alist[j] >= pivot): j = j - 1 if i <= j: alist[i], alist[j] = alist[j], alist[i] else: alist[start], alist[j] = alist[j], alist[start] return j alist = [2, 3, 5, 6, 4, 5] quicksort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Heapsort and print the sorted list for the below list def heapsort(alist): build_max_heap(alist) for i in range(len(alist) - 1, 0, -1): alist[0], alist[i] = alist[i], alist[0] max_heapify(alist, index=0, size=i) def parent(i): return (i - 1)//2 def left(i): return 2*i + 1 def right(i): return 2*i + 2 def build_max_heap(alist): length = len(alist) start = parent(length - 1) while start >= 0: max_heapify(alist, index=start, size=length) start = start - 1 def max_heapify(alist, index, size): l = left(index) r = right(index) if (l < size and alist[l] > alist[index]): largest = l else: largest = index if (r < size and alist[r] > alist[largest]): largest = r if (largest != index): alist[largest], alist[index] = alist[index], alist[largest] max_heapify(alist, largest, size) alist = [2, 3, 5, 6, 4, 5] heapsort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Counting sort and print the sorted list for the below list def counting_sort(alist, largest): c = [0]*(largest + 1) for i in range(len(alist)): c[alist[i]] = c[alist[i]] + 1 c[0] = c[0] - 1 for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for x in reversed(alist): result[c[x]] = x c[x] = c[x] - 1 return result alist = [2, 3, 5, 6, 4, 5] k = max(alist) sorted_list = counting_sort(alist, k) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Radix sort and print the sorted list for the below list def radix_sort(alist, base=10): if alist == []: return def key_factory(digit, base): def key(alist, index): return ((alist[index]//(base**digit)) % base) return key largest = max(alist) exp = 0 while base**exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist def counting_sort(alist, largest, key): c = [0]*(largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 c[0] = c[0] - 1 for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result alist = [2, 3, 5, 6, 4, 5] sorted_list = radix_sort(alist) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Bucket sort and print the sorted list for the below list def bucket_sort(alist): largest = max(alist) length = len(alist) size = largest/length buckets = [[] for _ in range(length)] for i in range(length): j = int(alist[i]/size) if j != length: buckets[j].append(alist[i]) else: buckets[length - 1].append(alist[i]) for i in range(length): insertion_sort(buckets[i]) result = [] for i in range(length): result = result + buckets[i] return result def insertion_sort(alist): for i in range(1, len(alist)): temp = alist[i] j = i - 1 while (j >= 0 and temp < alist[j]): alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = temp alist = [2, 3, 5, 6, 4, 5] sorted_list = bucket_sort(alist) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Gnome sort and print the sorted list for the below list def gnome_sort(alist): for pos in range(1, len(alist)): while (pos != 0 and alist[pos] < alist[pos - 1]): alist[pos], alist[pos - 1] = alist[pos - 1], alist[pos] pos = pos - 1 alist = [2, 3, 5, 6, 4, 5] gnome_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Cocktail Shaker sort and print the sorted list for the below list def cocktail_shaker_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i] upper = len(alist) - 1 lower = 0 no_swap = False while (not no_swap and upper - lower > 1): no_swap = True for j in range(lower, upper): if alist[j + 1] < alist[j]: swap(j + 1, j) no_swap = False upper = upper - 1 for j in range(upper, lower, -1): if alist[j - 1] > alist[j]: swap(j - 1, j) no_swap = False lower = lower + 1 alist = [2, 3, 5, 6, 4, 5] cocktail_shaker_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Comb sort and print the sorted list for the below list def comb_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i] gap = len(alist) shrink = 1.3 no_swap = False while not no_swap: gap = int(gap/shrink) if gap < 1: gap = 1 no_swap = True else: no_swap = False i = 0 while i + gap < len(alist): if alist[i] > alist[i + gap]: swap(i, i + gap) no_swap = False i = i + 1 alist = [2, 3, 5, 6, 4, 5] comb_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Shell sort and print the sorted list for the below list def gaps(size): length = size.bit_length() for k in range(length - 1, 0, -1): yield 2**k - 1 def shell_sort(alist): def insertion_sort_with_gap(gap): for i in range(gap, len(alist)): temp = alist[i] j = i - gap while (j >= 0 and temp < alist[j]): alist[j + gap] = alist[j] j = j - gap alist[j + gap] = temp for g in gaps(len(alist)): insertion_sort_with_gap(g) alist = [2, 3, 5, 6, 4, 5] shell_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python Class to calculate area of a rectangle and print the area class rectangle(): def __init__(self,breadth,length): self.breadth=breadth self.length=length def area(self): return self.breadth*self.length a=6 b=4 obj=rectangle(a,b) print("Area of rectangle:",obj.area()) # Write a python Class to calculate area of a circle and print the vale for a radius class CircleArea(): def __init__(self,radius): self.radius=radius def area(self): return 3.14 * self.radius * self.radius a=6 obj=CircleArea(a) print("Area of rectangle:",obj.area()) # Write a python Class to calculate Perimeter of a circle and print the vale for a radius class CirclePerimeter(): def __init__(self,radius): self.radius=radius def perimeter(self): return 2 * 3.14 * self.radius a=6 obj=CirclePerimeter(a) print("Perimeter of rectangle:",obj.perimeter()) # Write a python Class to print All Possible Subsets from a Set of Distinct Integers class sub: def f1(self, s1): return self.f2([], sorted(s1)) def f2(self, curr, s1): if s1: return self.f2(curr, s1[1:]) + self.f2(curr + [s1[0]], s1[1:]) return [curr] a=[2, 3, 5, 6, 4, 5] print("Subsets: ") print(sub().f1(a)) # Write a python program to Read and print the Contents of a File a=str(input("Enter file name .txt extension:")) file2=open(a,'r') line=file2.readline() while(line!=""): print(line) line=file2.readline() file2.close() # Write a python program to Count and print the Number of Words in a Text File fname = input("Enter file name: ") num_words = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print("Number of words:") print(num_words) # Write a python program to Count the Number of Lines in a Text File fname = input("Enter file name: ") num_lines = 0 with open(fname, 'r') as f: for line in f: num_lines += 1 print("Number of lines:") print(num_lines) # Write a python program to Count the Occurrences of a Word in a Text File fname = input("Enter file name: ") word='the' k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==word): k=k+1 print(f"Frequency of Occurrences of the word {a} is:") print(k) # Write a python function to Copy the Contents of One File into Another def copy(from_file, to_file): with open(from_file) as f: with open(to_file, "w") as f1: for line in f: f1.write(line) # Write a python function that Counts the Number of Times a Certain Letter Appears in the Text File def count_letter(fname, l): k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter==l): k=k+1 return k # Write a python function that Print all the Numbers Present in the Text File def print_number(fname): with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter.isdigit()): print(letter) # Write a python function that Counts the Number of Blank Spaces in a Text File def count_blank_space(fname): k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter.isspace): k=k+1 return k # Write a python function that Capitalize the First Letter of Every Word in the File def capitalize(fname): with open(fname, 'r') as f: for line in f: l=line.title() print(l) # Write a python function that prints the Contents of a File in Reverse Order def reverse_content(filename): for line in reversed(list(open(filename))): print(line.rstrip()) # Write a python Program to Flatten and print a List a=[[1,[[2]],[[[3]]]],[[4],5]] flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l] print(flatten(a)) # Write a Python Program to print the LCM of Two Numbers def lcm(a,b): lcm.multiple=lcm.multiple+b if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)): return lcm.multiple else: lcm(a, b) return lcm.multiple lcm.multiple=0 a=4 b=7 if(a>b): LCM=lcm(b,a) else: LCM=lcm(a,b) print(LCM) # Write a Python function to print the GSD of Two Numbers def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) # Write a Python function to Find if a Number is Prime or Not Prime def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print("Number not prime") return False else: return check(n, div-1) else: print("Number is prime") return 'True' # Write a Python function to Find the Power of a Number Using Recursion def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) # Write a Python function to Find the Total Sum of a Nested List Using Recursion def sum1(lst): total = 0 for element in lst: if (type(element) == type([])): total = total + sum1(element) else: total = total + element return total # Write a Python function to Count and print the Number of Vowels Present in a String using Sets def count_vowels(s): count = 0 vowels = set("aeiou") for letter in s: if letter in vowels: count += 1 return count # Write a Python Program to prints Common Letters in Two Input Strings s1='python' s2='schoolofai' a=list(set(s1)&set(s2)) print("The common letters are:") for i in a: print(i) # Write a Python Program that Prints which Letters are in the First String but not in the Second s1='python' s2='schoolofai' a=list(set(s1)-set(s2)) print("The letters are:") for i in a: print(i) # Write a Python Program to Concatenate Two Dictionaries Into One def concat_dic(d1, d2): return d1.update(d2) # Write a Python Program to Multiply All the Items in a Dictionary def mul_dict(d): tot=1 for i in d: tot=tot*d[i] return tot # Write a Python Program to Remove the Given Key from a Dictionary def remove_item_dict(d, key): if key in d: del d[key] else: print("Key not found!") exit(0) # Write a Python Program to Map Two Lists into a Dictionary def map_dict(keys, values): return dict(zip(keys,values)) # Write a Python Program to Remove the nth Index Character from a Non-Empty String def remove(string, n): first = string[:n] last = string[n+1:] return first + last # Write a Python Program to Detect if Two Strings are Anagrams def anagram_check(s1, s2): if(sorted(s1)==sorted(s2)): return True else: return False # Write a Python Program to Form a New String where the First Character and the Last Character have been Exchanged def change(string): return string[-1:] + string[1:-1] + string[:1] # Write a Python Program to Remove the Characters of Odd Index Values in a String def modify(string): final = "" for i in range(len(string)): if i % 2 == 0: final = final + string[i] return final # Write a Python Program to Take in Two Strings and Print the Larger String string1='python' string2='theschoolofai' count1=0 count2=0 for i in string1: count1=count1+1 for j in string2: count2=count2+1 if(count1a[j+1][1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp # Write a Python Program to Find the Second Largest Number in a List Using Bubble Sort a=[2, 3, 8, 9, 2, 4, 6] for i in range(0,len(a)): for j in range(0,len(a)-i-1): if(a[j]>a[j+1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp # Write a Python Program to Find the Intersection of Two Lists def main(alist, blist): def intersection(a, b): return list(set(a) & set(b)) return intersection(alist, blist) # Write a Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number using list comprehension l_range=2 u_range=5 a=[(x,x**2) for x in range(l_range,u_range+1)] # Write a Python Program to print all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10 l=6 u=9 a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10] print(a) # Write a Python Program to Swap the First and Last Value of a List a=[2, 3, 8, 9, 2, 4, 6] n = len(a) temp=a[0] a[0]=a[n-1] a[n-1]=temp print("New list is:") print(a) # Write a Python Program to Remove and print the Duplicate Items from a List a=[2, 3, 8, 9, 2, 4, 6] b = set() unique = [] for x in a: if x not in b: unique.append(x) b.add(x) print("Non-duplicate items:") print(unique) # Write a Python Program to Read a List of Words and Return the Length of the Longest One a=['the', 'tsai', 'python'] max1=len(a[0]) temp=a[0] for i in a: if(len(i)>max1): max1=len(i) temp=i print("The word with the longest length is:") print(temp) # Write a Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat a=['the', 'tsai', 'python' ,'a' ,'the', 'a'] c=[] count=0 b='a' n=3 for i in a: if(i==b): count=count+1 if(count!=n): c.append(i) else: c.append(i) if(count==0): print("Item not found ") else: print("The number of repetitions is: ",count) print("Updated list is: ",c) print("The distinct elements are: ",set(a)) # Write a Python function to Find Element Occurring Odd Number of Times in a List def find_odd_occurring(alist): """Return the element that occurs odd number of times in alist. alist is a list in which all elements except one element occurs an even number of times. """ ans = 0 for element in alist: ans ^= element return ans # Write a Python Program to Check if a Date is Valid and Print the Incremented Date if it is date="20/04/2021" dd,mm,yy=date.split('/') dd=int(dd) mm=int(mm) yy=int(yy) if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12): max1=31 elif(mm==4 or mm==6 or mm==9 or mm==11): max1=30 elif(yy%4==0 and yy%100!=0 or yy%400==0): max1=29 else: max1=28 if(mm<1 or mm>12): print("Date is invalid.") elif(dd<1 or dd>max1): print("Date is invalid.") elif(dd==max1 and mm!=12): dd=1 mm=mm+1 print("The incremented date is: ",dd,mm,yy) elif(dd==31 and mm==12): dd=1 mm=1 yy=yy+1 print("The incremented date is: ",dd,mm,yy) else: dd=dd+1 print("The incremented date is: ",dd,mm,yy) # Write a Python function to Check Whether a Given Year is a Leap Year def leapyear_check(year): if(year%4==0 and year%100!=0 or year%400==0): return True else: return False # Write a Python Program to print Prime Factors of an Integer n=24 print("Factors are:") i=1 while(i<=n): k=0 if(n%i==0): j=1 while(j<=i): if(i%j==0): k=k+1 j=j+1 if(k==2): print(i) i=i+1 # Write a Python Program to print all the Divisors of an Integer n=60 print("The divisors of the number are:") for i in range(1,n+1): if(n%i==0): print(i) # Write a Python Program to Check if a Number is an Armstrong Number def amstrong_check(n): a=list(map(int,str(n))) b=list(map(lambda x:x**3,a)) if(sum(b)==n): return True else: return False # Write a Python Program to Print the Pascalā€™s triangle for n number of rows given by the user n=10 a=[] for i in range(n): a.append([]) a[i].append(1) for j in range(1,i): a[i].append(a[i-1][j-1]+a[i-1][j]) if(n!=0): a[i].append(1) for i in range(n): print(" "*(n-i),end=" ",sep=" ") for j in range(0,i+1): print('{0:6}'.format(a[i][j]),end=" ",sep=" ") print() # Write a Python Program to Check if a Number is a Perfect Number def perfect_no_check(n): sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): return True else: return False # Write a Python Program to Check if a Number is a Strong Number def strong_no_check(num): sum1=0 temp=num while(num): i=1 f=1 r=num%10 while(i<=r): f=f*i i=i+1 sum1=sum1+f num=num//10 if(sum1==temp): return True else: return False # Write a Python Program to Check If Two Numbers are Amicable Numbers def amicable_no_check(x, y): sum1=0 sum2=0 for i in range(1,x): if x%i==0: sum1+=i for j in range(1,y): if y%j==0: sum2+=j if(sum1==y and sum2==x): return True else: return False # Write a Python Program to Check if a Number is a Prime Number def prime_no_check(a): k=0 for i in range(2,a//2+1): if(a%i==0): k=k+1 if(k<=0): return True else: return False # Write a Python Program to print the Sum of First N Natural Numbers n=7 sum1 = 0 while(n > 0): sum1=sum1+n n=n-1 print("The sum of first n natural numbers is",sum1) # Write a Python Program to Print all Pythagorean Triplets in the Range limit=10 c=0 m=2 while(climit): break if(a==0 or b==0 or c==0): break print(a,b,c) m=m+1 # Write a Python Program to print the Number of Times a Particular Number Occurs in a List a=[2, 3, 8, 9, 2, 4, 6] k=0 num=int(input("Enter the number to be counted:")) for j in a: if(j==num): k=k+1 print("Number of times",num,"appears is",k) # Write a Python Program to test and print Collatz Conjecture for a Given Number def collatz(n): while n > 1: print(n, end=' ') if (n % 2): # n is odd n = 3*n + 1 else: # n is even n = n//2 print(1, end='') # Write a Python function to Count Set Bits in a Number def count_set_bits(n): count = 0 while n: n &= n - 1 count += 1 return count # Write a Python Program to Generate Gray Codes using Recursion def get_gray_codes(n): """Return n-bit Gray code in a list.""" if n == 0: return [''] first_half = get_gray_codes(n - 1) second_half = first_half.copy() first_half = ['0' + code for code in first_half] second_half = ['1' + code for code in reversed(second_half)] return first_half + second_half # Write a Python Program to Convert Gray Code to Binary def gray_to_binary(n): """Convert Gray codeword to binary and return it.""" n = int(n, 2) mask = n while mask != 0: mask >>= 1 n ^= mask return bin(n)[2:] # Write a Python Program to Convert Binary to Gray Code def binary_to_gray(n): """Convert Binary to Gray codeword and return it.""" n = int(n, 2) n ^= (n >> 1) return bin(n)[2:] # Write a Python Program to print the Reverse a Given Number n=1023 rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 print("Reverse of the number:",rev) # Write a Python Program to Accept Three Digits and Print all Possible Combinations from the Digits a=2 b=9 c=5 d=[] d.append(a) d.append(b) d.append(c) for i in range(0,3): for j in range(0,3): for k in range(0,3): if(i!=j&j!=k&k!=i): print(d[i],d[j],d[k]) # Write a Python function to Print an Identity Matrix def print_identity_matrix(n): for i in range(0,n): for j in range(0,n): if(i==j): print("1",sep=" ",end=" ") else: print("0",sep=" ",end=" ") print() # Write a Python Program Print Restaurant Menu using Class given menu and cost as list class Food(object): def __init__(self, name, price): self.name = name self.price = price def getprice(self): return self.price def __str__(self): return self.name + ' : ' + str(self.getprice()) def buildmenu(names, costs): menu = [] for i in range(len(names)): menu.append(Food(names[i], costs[i])) return menu names = ['Coffee', 'Tea', 'Pizza', 'Burger', 'Fries', 'Apple', 'Donut', 'Cake'] costs = [250, 150, 180, 70, 65, 55, 120, 350] Foods = buildmenu(names, costs) n = 1 for el in Foods: print(n,'. ', el) n = n + 1 # Write a Python Program to print a list of fibonacci series for a given no using closer def fib(): cache = {1:1, 2:1} def calc_fib(n): if n not in cache: print(f'Calculating fib({n})') cache[n] = calc_fib(n - 1) + calc_fib(n - 2) return cache[n] return calc_fib # Write a Python Program to print a list of fibonacci series for a given no using class class Fib: def __init__(self): self.cache = {1:1, 2:1} def fib(self, n): if n not in self.cache: print(f'Calculating fib({n})') self.cache[n] = self.fib(n-1) + self.fib(n-2) return self.cache[n] # Write a Python function to calculate factorial of a given no using closer def fact(): cache = {0:1, 1:1} def calc_fib(n): if n not in cache: print(f'Calculating fact({n})') cache[n] = calc_fib(n - 1) * n return cache[n] return calc_fib # Write a Python function to calculate factorial of a given no using class class Fact: def __init__(self): self.cache = {0:1, 1:1} def fact(self, n): if n not in self.cache: self.cache[n] = self.fact(n-1) * n return self.cache[n] # Write a Python function to calculate dot product of two given sequence def dot_product(a, b): return sum( e[0]*e[1] for e in zip(a, b)) # Write a Python function to Find the Sum of Sine Series import math def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i pi=22/7 y=x*(pi/180) sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine # Write a Python function to Find the Sum of Cosine Series def cosine(x,n): cosx = 1 sign = -1 for i in range(2, n, 2): pi=22/7 y=x*(pi/180) cosx = cosx + (sign*(y**i))/math.factorial(i) sign = -sign return cosx # Write a Python function to strip vowels from a string def vowel_stripping(string): '''This function takes a string as an input strips out vowels and returns stripted out string''' return "".join([x for x in string if x not in('a','e','i','o','u')]) # Write a Python function that shifts the character of strings def char_shift(string, shift_count): '''This function takes a string as an input and shifts each character by 5 and returns shifted string''' return "".join([chr(ord(x)+shift_count) if (ord(x)+shift_count) <= 122 else chr(96 + (ord(x)+shift_count) - 122) for x in string]) # Write a Python function that returns biggest character in a string from functools import reduce def biggest_char(string): '''This function takes an input as a string and returns the biggest output character in the string''' biggest_chr = lambda x, y: x if ord(x) > ord(y) else y return reduce(biggest_chr, string) # Write a Python function that calculate interior angle of a equilateral polygon def interior_angle(no_of_sides): return (no_of_sides - 2) * 180 / no_of_sides # Write a Python function that calculate side length of a equilateral polygon import math def side_length(no_of_sides, circumradius): return 2 * circumradius * math.sin(math.pi / no_of_sides) # Write a Python function that calculate area of a equilateral polygon import math def area(no_of_sides, circumradius): side_length = 2 * circumradius * math.sin(math.pi / no_of_sides) apothem = circumradius * math.cos(math.pi / no_of_sides) return no_of_sides / 2 * side_length * apothem # sample.py from datetime import datetime from time import perf_counter import random val = 10 counter_67 = dict() #1 Write a function to print given interger to binary def int_to_binary(num: int): """ function to print number to binary """ if isinstance(num, int): print(f'The binary of {num} is {bin(num).replace("0b","")}') else: raise ValueError('Invalid Input') #2 write a function to check given string is palindrome or not ( case insensitive ) def palindrome_str_check(value: str): """ function to print whether string is palindrome or not """ if isinstance(value, str) : print( value.lower() == value[::-1].lower() ) else: raise ValueError('Invalid Input') #3 write a function to check whether a given date in DD/MM/YYYY format is valid or not def date_validation(inputdate: str): """ function take input date in DD/MM/YYYY format and check its validation. """ import datetime dd, mm, year = inputdate.split('/') isValidDate = True try : datetime.datetime(int(year),int(mm), int(dd)) except ValueError : isValidDate = False if(isValidDate): print ("Input Date is Valid") else: print ("Input Date is invalid") #4 write a function to print the count of divisor. def divisor_count(num: int): """ function to count the number of divisor of interger. """ if isinstance(num, int): count = 0 for i in range(1, num+1): if num%i == 0: count = count+1 print(f'Number of divisor is {count}') else: raise ValueError('Invalid Input') #5 write a function to print the count of divisor using list comprehension def divisor_using_list(num: int): """ function to count the number of divisor using list comprehension. """ if isinstance(num, int): count = [i for i in range(1,num+1) if not num%i] print(f'Number of divisor is {count}') else: raise ValueError('Invalid Input') #6 write a function to print merger of two dictionary def merge_dict(dict1: dict, dict2: dict): """ function to print merger of two dictionary """ final_dict = {**dict1, **dict2} print(final_dict) #7 write a function to print second largest number in a list. def second_large_num(num: list): if isinstance(num, list): num.sort() print (num[-2]) else: raise ValueError('Invalid Input') #8 write a function to remove empty list from a list and print. def remove_empty_list(num1: list): if isinstance(num1, list): modified = list(filter(None, num1)) print(modified) #9 write a function to remove empty tuples from a list and print def remove_empty_tuple(num1: list): if isinstance(num1, list): modified = list(filter(None, num1)) print(modified) #10 write a python function to remove duplicate from a list. def remove_duplicates(dup_list: list): print(list(set(dup_list))) #11 write a function to reverse every word in a string def reverse_word(sen: str): words = sen.split(' ') rever_word = [ i[::-1] for i in words ] final_sen = ' '.join(rever_word) print(final_sen) #12 function to check leap year def check_leap_year(year: int): if not year%4: print('Leap Year') else: print('Not a leap year') #13 function to print the multiplication table def maths_tables( no_ : int): for i in range(1, 11): print(f'{no_}x{i}={no_*i}') #14 function to check armstrong number or not def check_armstrong(no_: int): sum_ = 0 temp = no_ while temp > 0: digit = temp % 10 sum_ += digit ** 3 temp //= 10 if no_ == sum_: print(f"{no_} is an Armstrong number") else: print(f"{no_} is not an Armstrong number") #15 function to print all armstrong in a range def print_all_armstrong(lower: int, upper: int): for num in range(lower,upper + 1): sum_ = 0 temp = num while temp > 0: digit = temp % 10 sum_ += digit ** 3 temp //= 10 if num == sum_: print(num) #17 function to print the lcm of two number def ret_lcm(x: int, y: int): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm #18 function to print the hcf of two number def ret_hcf(x: int, y: int): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return int(x*y/lcm) #19 function to print ascii value of a character. def show_ascii(a: str): print(ord(a)) #20 function to print calendar def show_mm_calendar(mm: int, yyyy: int): import calendar print(calendar.month(yyyy, mm) #21 Create a function that takes a list of numbers between 1 and 10 (excluding one number) and returns the missing number. def print_miss_num(l: list): print(f'Missing number is {55-sum(l)}') #22 function to print marsh code equivalent from string. def encode_marsh(sen : str): char_to_dots = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.', ':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-', '-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.' } for i in sen: print(char_to_dots[i.upper()]) #23 function to intern a sentence. def check_intern(a , b): if a is b: print(f'{a} and {b} is interned by Python') else: print(f'{a} and {b} is not interned by Python') #24 convert string to intern string def str_to_intern_str(a): import sys b = sys.intern(a) if a is b: print('Sentence is interned') else: raise ValueError('This should not happen') #25 write a function to print the time taken by a calc function to ferform a simple multiplication 10 Million time def time_calc(n: int): import time start = time.perf_counter() for i in range(10000000): n*2 end = time.perf_counter() return end-start #26 write a function to print other value with given base to int. def other_int(value, b): return int(value, b) #27 write a function to convert any number to its equivalent fractions. def no_to_fraction(no_): from fractions import Fractions return Fractions(no_) #28 function to check two number ( floating also ) are close or not def check_isclose(x, y) from math import isclose return isclose(x, y) #29 function to convert temperature as per user mention. def temp_converter(temp , temp_given_in= 'F'): if temp < 0: raise ValueError("Input Temperature is Negative") else: if temp_given_in.upper() == 'F': t = (temp-32)*5/9 return t elif temp_given_in.upper() == 'C': t = 9/5 * (temp) + 32 return t elif temp_given_in.upper() not in ('C' , 'F'): raise NotImplementedError("Invalid Temperature Coneversion") #30 function to print the regular polygon area def polygon_area(side_length=1, side=3): from math import tan if side_length <= 0: raise ValueError("How come Side is zero.") else: if side <= 0 or side >=7: raise NotImplementedError elif side in ( 2 , 1 ): raise ValueError("No Polygon of Side 1 & 2 Exists") elif side == 3: return side_length*side_length*side/4*tan(180/side) elif side == 4: return side_length*side_length elif side == 5: return side_length*side_length*side/4*tan(180/side) elif side == 6: return side_length*side_length*side/4*tan(180/side) #31 function to return speed converer as per user mention data def speed_converter(speed , dist = 'KM', time = 'HR'): if speed < 0 or type(dist) == str or type(time) == str: raise ValueError("Invalid Input Format") else: if dist.upper == 'KM': if time.upper() == 'S': return True elif time.upper == 'MS': return True elif time.upper() == 'M': return True elif time.upper() == 'HR': return True elif time.upper() == 'DAY': return True else: raise ValueError("Valid Distance Invalid Time") elif dist.upper == 'M': if time.upper() == 'S': return True elif time.upper == 'MS': return True elif time.upper() == 'M': return True elif time.upper() == 'HR': return True elif time.upper() == 'DAY': return True else: raise ValueError("Valid Distance Invalid Time") elif dist.upper == 'FT': if time.upper() == 'S': return True elif time.upper == 'MS': return True elif time.upper() == 'M': return True elif time.upper() == 'HR': return True elif time.upper() == 'DAY': return True else: raise ValueError("Valid Distance Invalid Time") elif dist.upper == 'YRD': if time.upper() == 'S': return True elif time.upper == 'MS': return True elif time.upper() == 'M': return True elif time.upper() == 'HR': return True elif time.upper() == 'DAY': return True else: raise ValueError("Valid Distance Invalid Time") else: raise ValueError("Invalid User Distance Input") #32 function to remove values from dictionary def remove_dic_value(a: dict, key) a.pop(key) return a #33 function insert at the begining of dictionary def dict_in_at_begin(orgin: dict, new_: dict): final = {**new_, **origin} return final #34 function to convert a list of tuples into dictionary # Input : [ ('a',1), ('b', 2), ('c', 3)] # Output : { 'a':1, 'b':2, 'c':3 } def list_to_dict(l: list): final_dict = {} for i in l: final_dict[i[0]] = i[1] return final_dict #35 function to sort the dictionary with respect to key. def dict_sort_with_key(test_dict: dict): final dict = {} temp = sorted(test_dict) for i in temp: final_dict[i] = test_dict[a] return final_dict #36 function to return mirir charcters of a letter. # Input : paradox after N = 3 # Output : paizwlc def mirror_character(word: str, value: int): import string letters = string.ascii_lowercase rev_letter = letters[::-1] dict_char = dict(zip(letters, rev_letter)) final_1 = word[0:value] final_2 = [] for i in range(value, len(word)): final_2.append(dict_char[word[i]]) print(final_1+''.join(final_2)) #37 function to add two tuple def add_tuple(tup1, tup2): return tup1+tup2 #38 function to create a list of tuples from a given list having number and its cube in each tuple # Input : [1,2,3] # Output : [(1,1),(2,8),(3,9)] def list_of_tuple( l: list): final = [ (i, pow(i,3)) for i in l] return final #39 function to create a dictionary of mirror of letter. def letter_mirror(): import string letter = string.ascii_lowercase rvr_letter = letter[::-1] dict_char = dict(zip(letter, rvr_letter)) return dict_char #40 function to print the ascii value of letter def show_ascii(): import string letter = string.ascii_letters for i in letter: print(i+":"+str(ord(i))) #41 function to get the current time at GMT def current_time(): import datetime print(datetime.datetime.now()) #42 function to print the India Time def get_India_time(): import datetime, pytz print(datetime.datetime.now( pytz.timezone('Asia/kolkata') )) #43 function to print yesterday and tomorrow date def tmrw_yest_time() import datetime yesterday = datetime.datetime.now() - datetime.timedelta(1) tmrw = datetime.datetime.now() + datetime.timedelta(1) print( yesterday, tmrw ) #44 universal function def universal_func(*args, **kwargs): print(args) print(**kwargs) #45 logging message def logging(msg, *, dt = datetime.utcnow()): print(f'message at {dt} was {msg}') #46 factorial of number using recursion def factorial(n: int): if n<1: return 1 else: return n * factorial(n-1) #47 first class function def call_func(x, func): return fn(x) #48 function to show documentation def doc_func(*args, **kwargs): """ function to show how to do do documentation of function First line after function wriiten inside triple quotes. Don't forget to close when job is done. """ pass #49 function to show annotation def anno_func(a: "Mandatory", b: "Optional"=2, c: "Optional"=10, *args: "Extra Position variable", **kwargs: "Provide extra to unpack dictionary") -> 'Documentation to show how to do do annotation': """ function to show how to do do documentation of function First line after function wriiten inside triple quotes. Don't forget to close when job is done. """ pass #50 function to check whether a given name is function or method def inspect_func(fn): from inspect import isfunction, ismethod print(f'{fn} is method {ismethod(func)}') print(f'{fn} is function {isfunction(func)}') #51 function to print the source code of a function def print_so(f: "Function name/class name/module"): from inspect import getsource print(getsource(f)) #52 callable_check def collable_check(x: "Leterally can be anything"): return callable(x) #52 zip two tuple def zip_to_tuple( tup1, tup2): return zip(tup1, tup2) #53 factorial using pythonish def fact_one_line(n): return 1 if n < 2 else n*fact_one_line(n-1) #54 str to list def str_to_list(sen): return list(sen) #55 string to tuple def sen_to_tuple(sen): return tuple(sen) #56 function to all implementation def all_imp(a): return all(a) #57 function to any implementation def any_imp(a): return any(a) #58 function to show boolean true / false is a number def bool_show(a=5): return True*a #59 function to show boolean true / false is a number def bool_show(a=5): return False*a #60 function to use global varibale implementation def gloabl_use(n): global val return val * n #61 implementation of local cooncept def inner_show(): x = 'Hola' def inner(): nonlocal x x = 'Hola World' print(f'Inner function x is {x}') inner() print(f'outer function x is {x}') #62 custom counter function def custom_counter(): """ An implementation of closures """ x = 0 def inner(): nonlocal x x += 1 print(f' Switch or button is called {x} times') return inner #63 custom logging along with counter def custom_counter_log(): """ An implementation of closures """ x = 0 dt = datetime.now() def inner(): nonlocal x x += 1 print(f' Switch or button is called {x} at {dt}') return inner #64 function to build a time elapsed closures def time_elsaped() start = perf_counter() def inner() nonlocal perf_counter return perf_counter() - start return inner #65 function to attach counter to function def attach_counter(fn: "Function"): count = 0 def inner(*args, **kwargs): nonlocal count count += 1 return fn(*args, **kwargs) return inner #66 attach function closure with logs details to another function def attach_log(fn: "function"): def inner(*args, **kwargs): dt = datetime.now() print(f'{fn.__name__} is called at {dt} with {args} {kwargs} ') return fn(*args, **kwargs) return inner #67 function counter to store the number of times multiples function called in a dictionary def count_func_dict(fn: "Function Name"): count = 0 def inner(*args, **kwargs): nonlocal count count =+= 1 counter_67[fn.__name__] = count return fn(*args, **kwargs) return inner #68 write a function to unpack tuple of minimum 2 value to unlimited length int first two and rest def unpack_tuple(tup): a, b , *c = tup return a , b, c #69 write a function which take unlimited number and add it # Note : Number can be anything def add_unlimited(*args): return sum(args) #70 class to print user defined message whenever object of class is called is called. class User: def __init__(self, msg="Demo of custom message by repr and str in class"): self.msg = msg def __repr__(self): return f"Object of User class is called with parameter {self.msg}" def __str__(self): return f"Object of User class is called with parameter {self.msg}" #71 class to show implementation of equality and less than implementation in an class class GqLt: def __init__(self, msg="Demo of lt and eq in class"): self.msg = msg def __eq__(self, other): """ Equality check between two object of same class. It is mandatory to implement __eq__ in class to do equality check. """ if isinstance(other, GqLt): return "Code to be written here to match equality check between two object of same class" else: raise ValueError('Invalid comparison') def __lt__(self, other): """ Less than or greater than check between two objects of same class. It is mandatory to implement __eq__ in class to do equality check. """ if isinstance(other, GqLt): return "Code to be written here to match equality check between two object of same class" else: raise ValueError('Invalid comparison') #72 class to show as how to make the class as callable class CallShow: """ This is the space to do documentation related to class. """ def __init__(self, msg = 'Demo class to show how to make class object as callable'): self.msg = msg def __call__(self): """ to make object as callable the class should have __call__ in it """ return f"Code to be writen here above to act as per accling object of call" #73 function to store the data of IPL match in Namedtuple def store_ipl_date(tuple1): from collections import namedtuple IplData = namedtuple('IplData', 'match toss choice session1 session2 winner') return IplData(*tuple1) #74 function to show namedtuple is instance of tuple def show_ins_tup(): from collections import namedtuple IplData = namedtuple('IplData', 'match toss choice session1 session2 winner') match1 = IplData('RCBvsKKR', 'KKR', 'bat', '229/9', '85/8', 'KKR') return isinstance(match1, tuple) #75 return dot product of two vectors def dot_product(a: "Vector1", b: "Vector2"): return sum( e[0]*e[1] for e in zip(a,b) ) #76 function to showcast documemtation of namedtuple def show_doc_named(): from collections import namedtuple IplData = namedtuple('IplData', 'match toss choice session1 session2 winner') IplData.__doc__ = 'Namedtuple class to store the IPL match data' IplData.match.__doc__ = 'Team name' IplData.toss.__doc__ = 'Who won the toss' IplData.choice.__doc__ = 'Decision taken by wiinng team toss' IplData.session1.__doc__ = 'Run scored by Team1' IplData.session2.__doc__ = 'Run scored by Team2' IplData.winner.__doc__ = 'Winning Team' return help(IplData) #77 show all local values while one function is running def show_local(): import math a = 10 b = 'Hello There' print(locals()) #78 class to show implementation of static method class Mathematics: """ This is the space to do documentation related to class. """ def __init__(self, msg="Demo class of Mathematics"): self.msg = msg def __str__(self): return f' String representation of an object' def __repr__(self): return f' repr representation of an object with parameter {self.msg}' @staticmethod def addition(a: "Variable1", b: 'Variable2'): """ @staticmethod makes the mtethod of class as static method. It is always recommended to metion it via decorator. """ return a+b #79 class to show implementation of custom sequence of list class CustomList: """ This is the space to do documentation related to class. """ def __init__(self): self.list_ = [1,2,3,4] def __len__(self): return len(self.list_) def __getitem__(self, i): if isinstance(i, int): if i<0: i = len(self.list_) + i if i<0 or i>=len(self.list_): raise IndexError('Invalid Input') else: return self.list_[i] #80 class to show implementation of custom sequence of tuple class CustomTuple: """ This is the space to do documentation related to class. """ def __init__(self): self.list_ = (1,2,3,4) def __len__(self): return len(self.list_) def __getitem__(self, i): if isinstance(i, int): if i<0: i = len(self.list_) + i if i<0 or i>=len(self.list_): raise IndexError('Invalid Input') else: return self.list_[i] #81 generate intereger random number between user choice def gen_ran_int_number(lower, upper): import random final = [ random.randint(lower, upper) for _ in range(10) ] return final #82 function to show how to use f string def f_string(msg: "user message"): print(f'This is an f string with user paramter {msg}') #83 function to show reading values from list is expensive in camparison to tuple def compare_list_tuple(): from timeit import timeit import random l = [ random.randint(1,100) for _ in range(100) ] tu = tuple(l) list_time = timeit(stmt = 'max(l)', globals = locals(), number = 1) tup_time = timeit(stmt = 'max(tu)', globals = locals(), number = 1) if list_time > tup_time: print('Hence proved') else: raise ValueError('You did something Wrong') #84 generate random number using the concept of iterators class RandomInt: """ This is the space to do documentation related to class. """ def __init__(self): self.n = 10 def __next__(self): if self.n > 0: print(random.randint(0,10)) self.n -= 1 else: raise StopIteration def __iter__(self): return self #85 distinguish iter , iterables and iterator using example to print 10 random integers number class RandomInt: """ This is the space to do documentation related to class. """ def __init__(self): pass def __iter__(self): return self.RandomIntIterator(self) class RandomIntIterator: def __init__(self): self.count = 10 def __iter__(self): return self def __next__(self): if self.count > 0: print(random.randint(0,10)) self.count -= 1 else: raise StopIteration #86 show class of custom sequence type ,iter , iterables and iterator using example of tuple class CustomTupleIter: """ This is the space to do documentation related to class. """ def __init__(self): self.list_ = (1,2,3,4) def __len__(self): return len(self.list_) def __getitem__(self, i): if isinstance(i, int): if i<0: i = len(self.list_) + i if i<0 or i>=len(self.list_): raise IndexError('Invalid Input') else: return self.list_[i] def __iter__(self): return self.CustomTupleIterator(self) class CustomTupleIterator: def __init__(self, other): self.count = 0 self.other = other def __iter__(self): return self def __next__(self): if self.count < len(self.other.list_): self.count += 1 return self.other.list_[self.count] else: raise StopIteration #87 clone of orginal list with two functionality i. iterating and sequence class CustomListIter: """ This is the space to do documentation related to class. """ def __init__(self): self.list_ = [1,2,3,4] def __len__(self): return len(self.list_) def __getitem__(self, i): if isinstance(i, int): if i<0: i = len(self.list_) + i if i<0 or i>=len(self.list_): raise IndexError('Invalid Input') else: return self.list_[i] def __iter__(self): return self.CustomListIterator(self) class CustomListIterator: def __init__(self, other): self.count = 0 self.other = other def __iter__(self): return self def __next__(self): if self.count < len(self.other.list_): self.count += 1 return self.other.list_[self.count] else: raise StopIteration #88 write a class that act like squares and should print the squares of values and and cuustom sequence type. class Square: def __init__(self, n): self.n = n def __iter__(self): return self.show_sq(self.n) @staticmethod def show_sq(n): for i in range(n): yield i**2 def __getitem__(self, i): if isinstance(i, int): if i < = self.n: print(i**2) else: raise ValueError('Index out of bound') #89 fibonaaci using generator def fibo(n): x = 0 yield x y = 1 yield y for i in range(n-1): x, y = y, x+y yield y #90 show generator is faster than list def show_gen_fast(): from timeit import timeit dt = timeit("[num for num in fib(100) ]", globals = globals(), number=1) return dt # Add two strings def add_str(str1,str2): return str1 + str2 # we are dealing with multiple inheritance class A(object): def foo(self): print("class A") class B(object): def foo(self): print("class B") class C(A, B): pass # This is how pass works in case of multiple inheritance class A1(object): def foo(self): print("class A1") class B1(A1): pass class C1(A1): def foo(self): print("class C1") class D1(B1,C1): pass # List are mutable a_list = [] print('ID:', id(a_list)) a_list += [1] print('ID (+=):', id(a_list)) a_list = a_list + [2] print('ID (list = list + ...):', id(a_list)) # All blank lists are not the same a_list = [] print(a_list, '\nID (initial):',id(a_list), '\n') a_list.append(1) print(a_list, '\nID (append):',id(a_list), '\n') a_list.extend([2]) print(a_list, '\nID (extend):',id(a_list)) # True and False in the datetime module from platform import python_version import datetime print("Current python version: ", python_version()) print('"datetime.time(0,0,0)" (Midnight) ->', bool(datetime.time(0,0,0))) # Python version <= 3.4.5 evaluates this statement to False # Python reuses objects for small integers - use "==" for equality, "is" for identity a = 1 b = 1 print('a is b', bool(a is b)) c = 999 d = 999 print('c is d', bool(c is d)) # equality operator works this way print('256 is 257-1', 256 is 257-1) print('257 is 258-1', 257 is 258 - 1) print('-5 is -6+1', -5 is -6+1) print('-7 is -6-1', -7 is -6-1) # illustrate the test for equality (==) vs. identity (is) a = 'hello world!' b = 'hello world!' print('a is b,', a is b) print('a == b,', a == b) # We would think that identity would always imply equality, but this is not always true, as we can see in the next example: a = float('nan') print('a is a,', a is a) print('a == a,', a == a) # Shallow copy in python list1 = [1,2] list2 = list1 # reference list3 = list1[:] # shallow copy list4 = list1.copy() # shallow copy print('IDs:\nlist1: {}\nlist2: {}\nlist3: {}\nlist4: {}\n' .format(id(list1), id(list2), id(list3), id(list4))) # Deepcopy in python list1 = [[1],[2]] list2 = list1.copy() # shallow copy list3 = deepcopy(list1) # deep copy print('IDs:\nlist1: {}\nlist2: {}\nlist3: {}\n' .format(id(list1), id(list2), id(list3))) #logical or logical and result = (2 or 3) * (5 and 7) print('2 * 7 =', result) #Don't use mutable objects as default arguments for functions! def append_to_list(value, def_list=[]): def_list.append(value) return def_list my_list = append_to_list(1) print(my_list) my_other_list = append_to_list(2) print(my_other_list) # args and sleep import time def report_arg(my_default=time.time()): print(my_default) report_arg() time.sleep(5) report_arg() # Generators are consumed gen = (i for i in range(5)) print('2 in gen,', 2 in gen) print('3 in gen,', 3 in gen) print('1 in gen,', 1 in gen) # Convert generator to a list gen = (i for i in range(5)) a_list = list(gen) # Usage of bool class print('isinstance(True, int):', isinstance(True, int)) # Create list of numbers using lambda function but not the right way my_list = [lambda: i for i in range(5)] for l in my_list: print(l()) # print the numbers properly by creating a list my_list = [lambda x=i: x for i in range(5)] for l in my_list: print(l()) # local scope representation x = 0 def in_func(): x = 1 print('in_func:', x) # Global Scope Representation x = 0 def in_func1(): x = 1 print('in_func1:', x) print('global:', x) # Usage of global keyword x = 0 def in_func2(): global x x = 1 print('in_func2:', x) in_func2() print('global:', x) # local vs. enclosed def outer(): x = 1 print('outer before:', x) def inner(): x = 2 print("inner:", x) inner() print("outer after:", x) outer() # nonlocal keyword comes in handy def outer(): x = 1 print('outer before:', x) def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer after:", x) outer() # tuples are immutable tup = (1,) tup[0] += 1 # what if we put a mutable object into the immutable tuple tup1 = ([],) print('tup before: ', tup1) tup1[0] += [1] # there are ways to modify the mutable contents of the tuple without raising the TypeError tup = ([],) print('tup before: ', tup) tup[0].extend([1]) print('tup after: ', tup) # another way to append data to tuple tup = ([],) print('tup before: ', tup) tup[0].append(1) print('tup after: ', tup) # Add tuples like numerics my_tup = (1,) my_tup += (4,) my_tup = my_tup + (5,) print(my_tup) # What happens "behind" the curtains is that the tuple is not modified, but a new object is generated every time, which will inherit the old "name tag": my_tup = (1,) print(id(my_tup)) my_tup += (4,) print(id(my_tup)) my_tup = my_tup + (5,) print(id(my_tup)) # Create a plain list def plainlist(n=100000): my_list = [] for i in range(n): if i % 5 == 0: my_list.append(i) return my_list # Create a list comprehension def listcompr(n=100000): my_list = [i for i in range(n) if i % 5 == 0] return my_list # Create a Generator def generator(n=100000): my_gen = (i for i in range(n) if i % 5 == 0) return my_gen # Generator using yield function def generator_yield(n=100000): for i in range(n): if i % 5 == 0: yield i # Generators are faster than list comprehension import timeit def test_plainlist(plain_list): for i in plain_list(): pass def test_listcompr(listcompr): for i in listcompr(): pass def test_generator(generator): for i in generator(): pass def test_generator_yield(generator_yield): for i in generator_yield(): pass print('plain_list: ', end='') %timeit test_plainlist(plainlist) print('\nlistcompr: ', end='') %timeit test_listcompr(listcompr) print('\ngenerator: ', end='') %timeit test_generator(generator) print('\ngenerator_yield: ', end='') %timeit test_generator_yield(generator_yield) # Public vs. private class methods and name mangling def public_method(self): print('Hello public world!') def __private_method(self): print('Hello private world!') def call_private_method_in_class(self): self.__private_method() my_instance = my_class() my_instance.public_method() my_instance._my_class__private_method() my_instance.call_private_method_in_class() # The consequences of modifying a list when looping through it a = [1, 2, 3, 4, 5] for i in a: if not i % 2: a.remove(i) print(a) b = [2, 4, 5, 6] for i in b: if not i % 2: b.remove(i) print(b) # iterating through the list index by index b = [2, 4, 5, 6] for index, item in enumerate(b): print(index, item) if not item % 2: b.remove(item) print(b) # Dynamic binding and typos in variable names print('first list:') for i in range(3): print(i) print('\nsecond list:') for j in range(3): print(i) # I (intentionally) made typo here! # List slicing using indexes that are "out of range" my_list = [1, 2, 3, 4, 5] print(my_list[5]) # Reusing global variable names and UnboundLocalErrors def my_func(): print(var) var = 'global' my_func() # No problem to use the same variable name in the local scope without affecting the local counterpart: def my_func(): var = 'locally changed' var = 'global' my_func() print(var) # we have to be careful if we use a variable name that occurs in the global scope, and we want to access it in the local function scope if we want to reuse this name: def my_func(): print(var) # want to access global variable var = 'locally changed' # but Python thinks we forgot to define the local variable! var = 'global' my_func() # We have to use the global keyword! def my_func(): global var print(var) # want to access global variable var = 'locally changed' # changes the gobal variable var = 'global' my_func() print(var) # Creating copies of mutable objects my_list1 = [[1, 2, 3]] * 2 print('initially ---> ', my_list1) # modify the 1st element of the 2nd sublist my_list1[1][0] = 'a' print("after my_list1[1][0] = 'a' ---> ", my_list1) # we should better create "new" objects: my_list2 = [[1, 2, 3] for i in range(2)] print('initially: ---> ', my_list2) # modify the 1st element of the 2nd sublist my_list2[1][0] = 'a' print("after my_list2[1][0] = 'a': ---> ", my_list2) for a, b in zip(my_list1, my_list2): print('id my_list1: {}, id my_list2: {}'.format(id(a), id(b))) # Abortive statements in finally blocks def try_finally1(): try: print('in try:') print('do some stuff') float('abc') except ValueError: print('an error occurred') else: print('no error occurred') finally: print('always execute finally') try_finally1() # Assigning types to variables as values a_var = str a_var(123) #random choice from random import choice a, b, c = float, int, str for i in range(5): j = choice([a,b,c])(i) print(j, type(j)) # Only the first clause of generators is evaluated immediately gen_fails = (i for i in 1/0) # lazy evaluation gen_succeeds = (i for i in range(5) for j in 1/0) print('But obviously fails when we iterate ...') for i in gen_succeeds: print(i) # Usge of *args def a_func(*args): print('type of args:', type(args)) print('args contents:', args) print('1st argument:', args[0]) a_func(0, 1, 'a', 'b', 'c') # usage of kwargs def b_func(**kwargs): print('type of kwargs:', type(kwargs)) print('kwargs contents: ', kwargs) print('value of argument a:', kwargs['a']) b_func(a=1, b=2, c=3, d=4) # Unpacking of iterables val1, *vals = [1, 2, 3, 4, 5] print('val1:', val1) print('vals:', vals) # if else for for i in range(5): if i == 1: print('in for') else: print('in else') print('after for-loop') # usage of break for i in range(5): if i == 1: break else: print('in else') print('after for-loop') # conditional usecase a_list = [1,2] if a_list[0] == 1: print('Hello, World!') else: print('Bye, World!') # Usage of while i = 0 while i < 2: print(i) i += 1 else: print('in else') # Interning of string hello1 = 'Hello' hello2 = 'Hell' + 'o' hello3 = 'Hell' hello3 = hello3 + 'o' print('hello1 is hello2:', hello1 is hello2) print('hello1 is hello3:', hello1 is hello3) # Disassembler import dis def hello1_func(): s = 'Hello' return s dis.dis(hello1_func) # example to demonstrate usage of docstring def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") # Absolute function def absolute_value(num): """This function returns the absolute value of the entered number""" if num >= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4)) #usage of dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'] # accept user input str = input("Enter your input: ") print ("Received input is : ", str) # A recursive function to find nth catalan number def catalan(n): # Base Case if n <= 1: return 1 # Catalan(n) is the sum # of catalan(i)*catalan(n-i-1) res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # Driver Code for i in range(10): print (catalan(i)) # A naive recursive Python implementation def binomialCoeff(n , k): if k > n : return 0 if k==0 or k ==n : return 1 # Recursive Call return binomialCoeff(n-1 , k-1) + binomialCoeff(n-1 , k) # Driver Program to test ht above function n = 5 k = 2 print ("Value of C(%d,%d) is (%d)" %(n , k , binomialCoeff(n , k)) ) # A naive Python implementation of LIS problem """ To make use of recursive calls, this function must return two things: 1) Length of LIS ending with element arr[n-1]. We use max_ending_here for this purpose 2) Overall maximum as the LIS may end with an element before arr[n-1] max_ref is used this purpose. The value of LIS of full array of size n is stored in *max_ref which is our final result """ # global variable to store the maximum global maximum def _lis(arr , n ): # to allow the access of global variable global maximum # Base Case if n == 1 : return 1 # maxEndingHere is the length of LIS ending with arr[n-1] maxEndingHere = 1 """Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] IF arr[n-1] is maller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it""" for i in range(1, n): res = _lis(arr , i) if arr[i-1] < arr[n-1] and res+1 > maxEndingHere: maxEndingHere = res +1 # Compare maxEndingHere with overall maximum. And # update the overall maximum if needed maximum = max(maximum , maxEndingHere) return maxEndingHere def lis(arr): # to allow the access of global variable global maximum # lenght of arr n = len(arr) # maximum variable holds the result maximum = 1 # The function _lis() stores its result in maximum _lis(arr , n) return maximum # Driver program to test the above function arr = [10 , 22 , 9 , 33 , 21 , 50 , 41 , 60] n = len(arr) print ("Length of lis is ", lis(arr) ) # Function for nth Fibonacci number def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==0: return 0 # Second Fibonacci number is 1 elif n==1: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(9)) # write a python program to add two list of same length. def add_two_list_items(): num1 = [1,2,3] num2 = [4,5,6] sum = num1 + num2 print(f'Sum: {sum}') # write a python program to add numbers from two list if first list item is even and second list item is odd. def add_two_lists_even_odd(l1, l2): new = [] for x, y in zip(l1, l2): if l1%2 == 0 and l2%2 != 0: new.append(x+y) return new # write a python program Convert KM/H to MPH kmh = 50 mph = 0.6214 * kmh print("Speed:", kmh, "KM/H = ", mph, "MPH") # write a program to find and print the smallest among three numbers num1 = 100 num2 = 200 num3 = 300 if (num1 <= num2) and (num1 <= num3): smallest = num1 elif (num2 <= num1) and (num2 <= num3): smallest = num2 else: smallest = num3 print(f'smallest:{smallest}') # write a function to sort a list raw_list = [-5, -23, 5, 0, 23, -6, 23, 67] sorted_list = [] while raw_list: minimum = raw_list[0] for x in raw_list: if x < minimum: minimum = x sorted_list.append(minimum) raw_list.remove(minimum) print(soreted_list) # write a function to print the time it takes to run a function import time def time_it(fn, *args, repetitons= 1, **kwargs): start = time.perf_counter() if (repetitons <= 0): raise ValueError("repetitions should be greater that 0") if (not(isinstance(repetitons,int))): raise ValueError("Repetions must be of type Integer") for _ in range(repetitons): fn(*args, **kwargs) stop = time.perf_counter() return ((stop - start)/repetitons) # write a python function to calculate simple Interest def simple_interest(p,t,r): si = (p * t * r)/100 return si # write a python program to print all Prime numbers in an Interval start = 11 end = 25 for i in range(start,end): if i>1: for j in range(2,i): if(i % j==0): break else: print(i) # write a python funtion to implement a counter to record how many time the word has been repeated using closure concept def word_counter(): counter = {} def count(word): counter[word] = counter.get(word, 0) + 1 return counter[word] return count # write a python program to check and print if a string is palindrome or not st = 'malayalam' j = -1 flag = 0 for i in st: if i != st[j]: j = j - 1 flag = 1 break j = j - 1 if flag == 1: print("Not a palindrome") else: print("It is a palindrome") # write a python function to find the URL from an input string using the regular expression import re def Find(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # write a python program to find N largest elements from a list l = [1000,298,3579,100,200,-45,900] n = 4 l.sort() print(l[-n:]) # write a python program to add two lists using map and lambda nums1 = [1, 2, 3] nums2 = [4, 5, 6] result = map(lambda x, y: x + y, nums1, nums2) print(list(result)) # write a python functionto test the equality of the float numbers def float_equality_testing(a, b): rel_tol = 1e-12 abs_tol = 1e-05 return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) # write a python function to caclucate the polygon_area def polygon_area( side_length, sides = 3): if(sides < 3 or sides > 6 ): raise ValueError("number of sides must be greater than 2 and less than 7") if(side_length < 0 ): raise ValueError("side length must be positive") return sides * (side_length ** 2) / (4 * tan(pi / sides)) # write a python program to get positive elements from given list of lists Input = [[10, -11, 222], [42, -222, -412, 99, -87]] temp = map(lambda elem: filter(lambda a: a>0, elem), Input) Output = [[a for a in elem if a>0] for elem in temp] # write the program to remove empty tuples from a list def Remove(tuples): tuples = filter(None, tuples) return tuples # write a python program to find Cumulative sum of a list list=[10,20,30,40,50] new_list=[] j=0 for i in range(0,len(list)): j+=list[i] new_list.append(j) print(new_list) # write a python function to convert a list to string s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] listToStr = ' '.join(map(str, s)) print(listToStr) # write a python program to merge 2 dictionaries x = {'a' : 1, 'b' : 2, 'c' : 3} y = {'x' : 10, 'y' : 20, 'z' : 30 } z = {**x , **y} # write a python code to implement Sigmoid function import math def sigmoid(x): return 1 / (1 + math.exp(-x)) # write a python code to implement RELU function def relu(array): return [max(0,i) for i in array if(isinstance(i, int) or isinstance(i, float))] # write a python function to check whether the given number is fibonacci or not def fiboacci_number_check(n): if(isinstance(n,int)): result = list(filter(lambda num : int(math.sqrt(num)) * int(math.sqrt(num)) == num, [5*n*n + 4,5*n*n - 4] )) return bool(result) else: raise TypeError("Input should be of type Int") # write a python program to strip all the vowels in a string string = "Remove Vowel" vowel = ['a', 'e', 'i', 'o', 'u'] "".join([i for i in string if i not in vowel] # write a python program to give the next fibonacci number num_1, num_2,count = 0, 1,0 def next_fibbonacci_number() : nonlocal num_1, num_2, count if(count == 0): count+=1 return 0 elif(count==1): count+=1 return num_2 else: num_1, num_2 = num_2, num_1+num_2 return num_2 return next_fibbonacci_number # write a python function to calculate factorial of a given number def factorial(n): fact = 1 for num in range(2, n + 1): fact = fact * num return(fact) # write a python program which will find all such numbers which are divisible by 7 but are not a multiple of 5 ;between 2000 and 3200 (both included) l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print(','.join(l)) # write the python program to generate a random number between 0 and 9 import csv def read_csv(input_file): with open(input_file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: print(f'{row}') break # write a python program to Generate a Random Number import random print(random.randint(0,9)) # write a python program to Check Leap Year year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") # write a python function to Compute LCM def compute_lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # write a python function to compute gcd def compute_gcd(x, y): while(y): x, y = y, x % y return x # write a python program to Remove Punctuations From a String punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) # write a python function to Find Hash of File import hashlib def hash_file(filename): h = hashlib.sha1() with open(filename,'rb') as file: chunk = 0 while chunk != b'': chunk = file.read(1024) h.update(chunk) return h.hexdigest() # write a python Program to Find the Size (Resolution) of a JPEG Image and print it def jpeg_res(filename): with open(filename,'rb') as img_file: img_file.seek(163) a = img_file.read(2) # calculate height height = (a[0] << 8) + a[1] # next 2 bytes is width a = img_file.read(2) # calculate width width = (a[0] << 8) + a[1] print("The resolution of the image is",width,"x",height) # write a python program to count the number of each vowels ip_str = 'Hello, have you tried our tutorial section yet?' ip_str = ip_str.casefold() count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'} print(count) # write a python Program to Find ASCII Value of Character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) # write a python Program to Solve Quadratic Equation import cmath a = 1 b = 5 c = 6 d = (b**2) - (4*a*c) sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) # write a python program to Convert Celsius To Fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print(f'{celsius} degree Celsius is equal to {fahrenheit} degree Fahrenheit') # write a python program to check Armstrong number of n digits num = 1634 order = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") # write a Python Program to Find the Sum of Natural Numbers num = 16 if num < 0: print("Enter a positive number") else: sum = 0 while(num > 0): sum += num num -= 1 print("The sum is", sum) # write a python program to Shuffle Deck of Cards import itertools, random deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) random.shuffle(deck) print(deck) # write a Python function to Convert Decimal to Binary def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2,end = '') # wrtie a python function to solve Tower Of Hanoi and print necessary statements def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print("Move disk 1 from source",source,"to destination",destination) return TowerOfHanoi(n-1, source, auxiliary, destination) print("Move disk",n,"from source",source,"to destination",destination) TowerOfHanoi(n-1, auxiliary, destination, source) # write a python function to find the number of times every day occurs in a Year and print them import datetime import calendar def day_occur_time(year): days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] L = [52 for i in range(7)] pos = -1 day = datetime.datetime(year, month = 1, day = 1).strftime("%A") for i in range(7): if day == days[i]: pos = i if calendar.isleap(year): L[pos] += 1 L[(pos+1)%7] += 1 else: L[pos] += 1 for i in range(7): print(days[i], L[i]) # write a python Program to Determine all Pythagorean Triplets in the Range limit= 50 c=0 m=2 while(climit): break if(a==0 or b==0 or c==0): break print(a,b,c) m=m+1 # function to Convert Binary to Gray Code def binary_to_gray(n): n = int(n, 2) n ^= (n >> 1) return bin(n)[2:] # write a Python function to Find the Intersection of Two Lists def intersection(a, b): return list(set(a) & set(b)) # write a python program to Remove the Given Key from a Dictionary d = {'a':1,'b':2,'c':3,'d':4} key= 'd' if key in d: del d[key] else: print("Key not found!") exit(0) # write a python function to Count the Number of Words in a Text File and print it def word_count(fname) : num_words = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print(num_words) # write a python function to Count Set Bits in a Number def count_set_bits(n): count = 0 while n: n &= n - 1 count += 1 return count # wrie a python Program to Flatten a List without using Recursion a=[[1,[[2]],[[[3]]]],[[4],5]] flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l] print(flatten(a)) # import os import nltk import string from collections import Counter from itertools import permutations, combinations, combinations_with_replacement letters = string.ascii_lowercase # write a python function to print pyramid pattern def pyramid_pattern(symbol='*', count=4): for i in range(1, count + 1): print(' ' * (count - i) + symbol * i, end='') print(symbol * (i - 1) + ' ' * (count - i)) # write a python function to count the occurrence of a given word in a given file def check_word_count(word, file): if not os.path.isfile(file): raise FileNotFoundError if not isinstance(word, str): raise TypeError with open(file, 'r') as f: lines = f.readlines() words = [l.strip().split(' ') for l in lines] words = [word for sublist in words for word in sublist] c = Counter(words) return c.get(word, 0) # write a python function to make permutations from a list with given length def get_permutations(data_list, l=2): return list(permutations(data_list, r=l)) # write a python program to get all possible permutations of size of the string in lexicographic sorted order. def get_ordered_permutations(word, k): [print(''.join(x)) for x in sorted(list(permutations(word, int(k))))] # write a python program to get all possible combinations, up to size of the string in lexicographic sorted order. def get_ordered_combinations(string, k): [print(''.join(x)) for i in range(1, int(k) + 1) for x in combinations(sorted(string), i)] # write a python function to get all possible size replacement combinations of the string in lexicographic sorted order. def get_ordered_combinations_with_replacement(string, k): [print(''.join(x)) for x in combinations_with_replacement(sorted(string), int(k))] # write a python function for Caesar Cipher, with given shift value and return the modified text def caesar_cipher(text, shift=1): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[shift:] + alphabet[:shift] table = str.maketrans(alphabet, shifted_alphabet) return text.translate(table) # write a python function for a string to swap the case of all letters. def swap_case(s): return ''.join(x for x in (i.lower() if i.isupper() else i.upper() for i in s)) # write a python function to get symmetric difference between two sets from user. def symmetric_diff_sets(): M, m = input(), set(list(map(int, input().split()))) N, n = input(), set(list(map(int, input().split()))) s = sorted(list(m.difference(n)) + list(n.difference(m))) for i in s: print(i) # write a python function to check if given set is subset or not def check_subset(): for _ in range(int(input())): x, a, z, b = input(), set(input().split()), input(), set(input().split()) print(a.issubset(b)) # write a python program for basic HTML parser from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for attr in attrs: print("->", attr[0], ">", attr[1]) parser = MyHTMLParser() for i in range(int(input())): parser.feed(input()) # write a python function for Named Entity Recognizer using NLTK def ner_checker(texts): all_set = set() def nltk_ner_check(texts): for i, text in texts: for entity in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(text))): if isinstance(entity, nltk.tree.Tree): etext = " ".join([word for word, tag in entity.leaves()]) # label = entity.label() all_set.add(etext) nltk_ner_check(texts=texts) return all_set #write a function to compress a given string. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X, c) in the string. def compress(text): from itertools import groupby for k, g in groupby(text): print("({}, {})".format(len(list(g)), k), end=" ") # write a python function to count 'a's in the repetition of a given string 'n' times. def repeated_string(s, n): return s.count('a') * (n // len(s)) + s[:n % len(s)].count('a') # write a python function to find all the substrings of given string that contains 2 or more vowels. Also, these substrings must lie in between 2 consonants and should contain vowels only. def find_substr(): import re v = "aeiou" c = "qwrtypsdfghjklzxcvbnm" m = re.findall(r"(?<=[%s])([%s]{2,})[%s]" % (c, v, c), input(), flags=re.I) print('\n'.join(m or ['-1'])) # write a python function that given five positive integers and find the minimum and maximum values that can be calculated by summing exactly four of the five integers. def min_max(): nums = [int(x) for x in input().strip().split(' ')] print(sum(nums) - max(nums), sum(nums) - min(nums)) # write a python function to find the number of (i, j) pairs where i 1: data.pop(item) count -= 1 return data # write a python function to get the most common word in text def most_common(text): c = Counter(text) return c.most_common(1) # write a python function to do bitwise multiplication on a given bin number by given shifts def bit_mul(n, shift): return n << shift # write a python function for bitwise division with given number of shifts def bit_div(n, shift): return n >> shift # write a python program to implement Queue from collections import deque class Queue(): ''' Thread-safe, memory-efficient, maximally-sized queue supporting queueing and dequeueing in worst-case O(1) time. ''' def __init__(self, max_size = 10): ''' Initialize this queue to the empty queue. Parameters ---------- max_size : int Maximum number of items contained in this queue. Defaults to 10. ''' self._queue = deque(maxlen=max_size) def enqueue(self, item): ''' Queues the passed item (i.e., pushes this item onto the tail of this queue). If this queue is already full, the item at the head of this queue is silently removed from this queue *before* the passed item is queued. ''' self._queue.append(item) def dequeue(self): ''' Dequeues (i.e., removes) the item at the head of this queue *and* returns this item. Raises ---------- IndexError If this queue is empty. ''' return self._queue.pop() # write a python function to get dot product between two lists of numbers def dot_product(a, b): return sum(e[0] * e[1] for e in zip(a, b)) # write a python function to strip punctuations from a given string def strip_punctuations(s): return s.translate(str.maketrans('', '', string.punctuation)) # write a python function that returns biggest character in a string from functools import reduce def biggest_char(string): if not isinstance(string, str): raise TypeError return reduce(lambda x, y: x if ord(x) > ord(y) else y, string) # write a python function to Count the Number of Digits in a Number def count_digits(): n = int(input("Enter number:")) count = 0 while n > 0: count = count + 1 n = n // 10 return count # write a python function to count number of vowels in a string def count_vowels(text): v = set('aeiou') for i in v: print(f'\n {i} occurs {text.count(i)} times') # write a python function to check external IP address def check_ip(): import re import urllib.request as ur url = "http://checkip.dyndns.org" with ur.urlopen(url) as u: s = str(u.read()) ip = re.findall(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", s) print("IP Address: ", ip[0]) return ip[0] # write a python function for some weird hypnosis text. def weird(): import random def getlength(script): return sum((i['length'] for i in script)) def truncate(target_length, script): if getlength(script) > target_length: script = sorted(script, key=lambda k: (k['priority'], -k['length']))[:-1] return truncate(target_length, script) return sorted(script, key=lambda k: k['index']) def as_text(script): return "\n".join([i['text'] for i in script]) priorities_and_sentences = [ (1, "...now... sitting comfortably in the chair"), (2, "...with your feet still flat on the ground"), (3, "...back straight and head up right"), (2, "...make these adjustments now if you need to"), (3, "... pause.............................."), (1, "...your eyes ...still ...comfortably closed"), (2, "...nice and relaxed...comfortable and relaxed..."), (3, "... pause......................................."), (1, "...now...I want you to notice...how heavy your head is starting to feel..."), (1, "how heavy your head feels..."), (3, "... pause......................................."), (2, "really noticing the weight... of your head..."), (3, "and how much more ...comfortable...it will feel when you let your neck relaxes ...and your head begins to fall forward ...into a much more comfortable"), ] scriptlist = [{'priority': j[0], 'text': j[1], 'length': len(j[1]), 'index': i} for i, j in enumerate(priorities_and_sentences)] print(as_text(truncate(500, scriptlist))) print(as_text(truncate(300, scriptlist))) print(as_text(truncate(200, scriptlist))) # write a python function for dice roll asking user for input to continue and randomly give an output. def dice(): import random min = 1 max = 6 roll_again = 'y' while roll_again == "yes" or roll_again == "y": print("Rolling the dice...") print(random.randint(min, max)) roll_again = input("Roll the dices again?") from cryptography.fernet import Fernet # write a python program to Encrypt and Decrypt features within 'Secure' class with key generation, using cryptography module class Secure: def __init__(self): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("secret.key", "wb") as key_file: key_file.write(key) @staticmethod def load_key(): """ Load the previously generated key """ return open("secret.key", "rb").read() def encrypt_message(self, message): """ Encrypts a message """ key = self.load_key() encoded_message = message.encode() f = Fernet(key) encrypted_message = f.encrypt(encoded_message) print("\nMessage has been encrypted: ", encrypted_message) return encrypted_message def decrypt_message(self, encrypted_message): """ Decrypts an encrypted message """ key = self.load_key() f = Fernet(key) decrypted_message = f.decrypt(encrypted_message) print("\nDecrypted message:", decrypted_message.decode()) s = Secure() encrypted = s.encrypt_message("My deepest secret!") s.decrypt_message(encrypted) # write a python function to generate SHA256 for given text def get_sha256(text): import hashlib return hashlib.sha256(text).hexdigest() # write a python function to check if SHA256 hashed value is valid for given data or not def check_sha256_hash(hashed, data): import hashlib return True if hashed == hashlib.sha256(data.encode()).hexdigest() else False # write a python function to get HTML code for a given URL def get_html(url="http://www.python.org"): import urllib.request fp = urllib.request.urlopen(url) mybytes = fp.read() mystr = mybytes.decode("utf8") fp.close() print(mystr) # write a python function to get Bitcoin prices after every given 'interval' seconds def get_btc_price(interval=5): import requests import json from time import sleep def getBitcoinPrice(): URL = "https://www.bitstamp.net/api/ticker/" try: r = requests.get(URL) priceFloat = float(json.loads(r.text)["last"]) return priceFloat except requests.ConnectionError: print("Error querying Bitstamp API") while True: print("Bitstamp last price: US $ " + str(getBitcoinPrice()) + "/BTC") sleep(interval) # write a python function to get stock prices for a company from 2015 to 2020-12 def get_stock_prices(tickerSymbol='TSLA'): import yfinance as yf # get data on this ticker tickerData = yf.Ticker(tickerSymbol) # get the historical prices for this ticker tickerDf = tickerData.history(period='1d', start='2015-1-1', end='2020-12-20') # see your data print(tickerDf) # write a python function to get 10 best Artists playing on Apple iTunes def get_artists(): import requests url = 'https://itunes.apple.com/us/rss/topsongs/limit=10/json' response = requests.get(url) data = response.json() for artist_dict in data['feed']['entry']: artist_name = artist_dict['im:artist']['label'] print(artist_name) # write a python function to get prominent words from user test corpus using TFIDF vectorizer def get_words(corpus, new_doc, top=2): import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(stop_words='english') if not corpus: corpus = [ 'I would like to check this document', 'How about one more document', 'Aim is to capture the key words from the corpus', 'frequency of words in a document is called term frequency' ] X = tfidf.fit_transform(corpus) feature_names = np.array(tfidf.get_feature_names()) if not new_doc: new_doc = ['can key words in this new document be identified?', 'idf is the inverse document frequency calculated for each of the words'] responses = tfidf.transform(new_doc) def get_top_tf_idf_words(response, top_n=top): sorted_nzs = np.argsort(response.data)[:-(top_n + 1):-1] return feature_names[response.indices[sorted_nzs]] print([get_top_tf_idf_words(response, 2) for response in responses]) # write a python function to generate wordcloud on given text or file import os def get_word(data): if not (isinstance(data, str) or os.path.isfile(data)): raise TypeError("Text must be string or a File object.") from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt stopwords = set(STOPWORDS) if os.path.isfile(data): with open(data, 'r') as f: data = f.read() data = ' '.join(data.lower().split(' ')) wordcloud = WordCloud(width=400, height=400, background_color='white', stopwords=stopwords, min_font_size=15).generate(data) # plot the WordCloud image plt.figure(figsize=(8, 8), facecolor=None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad=0) plt.show() # get_word(data="./christmas_carol.txt") # write a python function to sort each item in a data structure on one of the keys def sort_list_with_key(): animals = [ {'type': 'lion', 'name': 'Mr. T', 'age': 7}, {'type': 'tiger', 'name': 'scarface', 'age': 3}, {'type': 'puma', 'name': 'Joe', 'age': 4}] print(sorted(animals, key=lambda animal: -animal['age'])) # write a python function with generator for an infinite sequence def infinite_sequence(): n = 0 while True: yield n n += 1 import uuid # write a python function to generate a Unique identifier across space and time in this cosmos. def get_uuid(): return uuid.uuid4() import secrets # write a python function to generate cryptographically strong pseudo-random data def get_cryptographically_secure_data(n=101): return secrets.token_bytes(n), secrets.token_hex(n) # write a python function to convert byte to UTF-8 def byte_to_utf8(data): return data.decode("utf-8") print(byte_to_utf8(data=b'r\xc3\xa9sum\xc3\xa9')) # write a python function which takes length , breadth as user input and returns the area of rectangle. def rectangle_area(length, breadth): area = length * breadth return area # write a python function which takes a number as user input and print square, and cube of the number def square_cube(number): print(number ** 2) print(number ** 3) # write a python program that takes height in centimeters as user input and return height in feet and inches cm=int(input("Enter the height in centimeters:")) inches=0.394*cm feet=0.0328*cm print("The length in inches",round(inches,2)) print("The length in feet",round(feet,2)) # write a python program to remove duplicates from the list and print the result l = [1,2,3,4,5,5,5,5,5,5,5,7,8,8,0] result = set(l) print("Result : ",result) #write a python function which takes length of sides as user input to calculate and return the area of a triangle def triangle_area(a,b,c): s = (a+b+c)/2 area = (s(s-a)*(s-b)*(s-c)) ** 0.5 return(area) # write a python program to swap two numbers num1 = 130 num2 = 34 num1,num2 = num2,num1 # Write a python program to obtain principal amount, rate of interest and time from user to print simple interest. principal = float(input("Enter principal : ")) rate= float(input("Enter rate : ")) time = float(input("Enter time : ")) simple_interest = print(f"Simple Interest : {(principal*rate*time/100)}") # write a python program using while loop to reverse a number and print the reversed number Number = int(input("Please Enter any Number: ")) Reverse = 0 while(Number > 0): Reminder = Number %10 Reverse = (Reverse *10) + Reminder Number = Number //10 print("\n Reverse of entered number is = %d" %Reverse) # write a python program to take year as input and check if it is a leap year or not year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") # write a python program to input a number to test and print if it is a prime number num = int(input("Enter number :")) lim = int(num/2) + 1 for i in range(2,lim): rem = num % i if rem == 0 : print(num,"is not a prime number") break else: print(num,"is a prime number") # write a python program to input a string from user and convert input string into all upper case and print the result string = input("Please Enter your Own String : ") string1 = string.upper() print("\nOriginal String in Lowercase = ", string) print("The Given String in Uppercase = ", string1) # write a python program to input a string from user and count vowels in a string and print the output str1 = input("Please Enter Your Own String : ") vowels = 0 for i in str1: if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'): vowels = vowels + 1 print("Total Number of Vowels in this String = ", vowels) # write a python program to input a Number N from user and print Odd Numbers from 1 to N maximum = int(input(" Please Enter any Maximum Value : ")) for number in range(1, maximum + 1): if(number % 2 != 0): print("{0}".format(number)) # write a python program to input a Number N from user and print Even Numbers from 1 to N maximum = int(input(" Please Enter the Maximum Value : ")) for number in range(1, maximum+1): if(number % 2 == 0): print("{0}".format(number)) # write a python program to input two numbers from user and add two Numbers and print the result number1 = input(" Please Enter the First Number: ") number2 = input(" Please Enter the second number: ") sum = float(number1) + float(number2) print('The sum of {0} and {1} is {2}'.format(number1, number2, sum)) # write a python program that takes two integers as input and check if the first number is divisible by other num1 = int(input("Enter first number :")) num2 = int(input("Enter second number :")) remainder = num1 % num2 if remainder == 0: print(num1 ," is divisible by ",num2) else : print(num1 ," is not divisible by ",num2) # write a python program to print the table of input integer num = int(input("Please enter a number ")) for a in range(1,11): print(num , 'x' , a , '=' ,num*a) # write a python program to print the factorial of number num = int(input("Please enter a number ")) fact = 1 a = 1 while a <= num : fact *= a a += 1 print("The factorial of ",num, " is ",fact) # write a python program which takes 3 numbers as input and to print largest of three numbers using elif statement a = float(input("Please Enter the First value: ")) b = float(input("Please Enter the First value: ")) c = float(input("Please Enter the First value: ")) if (a > b and a > c): print("{0} is Greater Than both {1} and {2}". format(a, b, c)) elif (b > a and b > c): print("{0} is Greater Than both {1} and {2}". format(b, a, c)) elif (c > a and c > b): print("{0} is Greater Than both {1} and {2}". format(c, a, b)) else: print("Either any two values or all the three values are equal") # write a python program which takes input a number N and print first N elements of fibonacci series N = int(input("Please enter a number ")) first = 0 second = 1 print(first) print(second) for a in range(1,N-1): third = first + second print(third) first,second = second , third # write a python program to print the divisors of a integer num = int(input("Please enter a integer ")) mid = int(num / 2) print("The divisiors of ",num," are :" ) for a in range(2,mid + 1): if num % a == 0: print(a, end = ' ') else : print() print("-End-") # write a python program to find the average of list of numbers provided as input by user n=int(input("Enter the number of elements to be inserted: ")) a=[] for i in range(0,n): elem=int(input("Enter element: ")) a.append(elem) avg=sum(a)/n print("Average of elements in the list",round(avg,2)) # write a python program which takes an integer N as input and add the odd numbers up to N and print the result N = int(input("Enter Number : ")) sum = 0 i = 1 while i <= N: sum = sum + i i = i + 2 print(sum) # write a python function which takes input a string and returns whether is is a palindrome or not def isPalindrome(s): return s == s[::-1] # write a python program which takes list as an input and calculate mean of given list of numbers lst = eval(input("Enter list : ")) mean = 0 sum = 0 for i in lst: sum = sum + i mean = sum / len(lst) print(" The mean of given list is :", mean) # write a python program which takes list as an input and calculate sum of given list of numbers lst = eval(input("Enter list : ")) mean = 0 sum = 0 for i in lst: sum = sum + i print(" The mean of given list is :", sum) # write a python program which takes list as an input and find frequency of all elements in list lst = eval(input("Enter list : ")) mean = 0 sum = 0 for i in lst: sum = sum + i print(" The mean of given list is :", sum) # write a python function that takes two lists as an input an print out common elements in two lists def common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): print(a_set & b_set) else: print("No common elements") # write a python function that takes two lists and append second list after the first list lst1 = eval(input("Enter list : ")) lst2 = eval(input("Enter list : ")) print(lst1 + lst2) # write a python program to calculate and print square root of numbers 0 to 100 i = 0 while i<= 100: print(i, "\t\t" , i**0.5) i = i + 1 #write a python program greets the user with "Hello", after user inputs his name: name = input ("Input your name: ") print("HELLO ", name) # write a python program which takes input a string and print reverse string name = input("Enter String") print(name[::-1]) # write a python program which takes input a list and print reverse output lst = eval(input("Enter list")) print(lst[::-1]) # write a python function which takes sentence as input and remove vowels from a sentence sentence = input("Enter a sentence : ") def fn(sentence): vowels = 'aeiou' return ''.join([ l for l in sentence if l not in vowels]) # write a python function which takes two list of same length as input and return a dictionary with one as keys and other as values. keys = eval(input("Enter key list : ")) values = eval(input("Enter value list : ")) def fn(keys, values): return { keys[i] : values[i] for i in range(len(keys)) } # write a python function that takes an integer as input and returns the factorial of that number def factorial(n): # single line to find factorial return 1 if (n==1 or n==0) else n * factorial(n - 1); # write a python function that takes input radius and return area of circle def findArea(r): PI = 3.142 return PI * (r*r); # write a python funtion that takes input principle, rate, time and calculate compound intrest def compound_interest(principle, rate, time): # Calculates compound interest Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle print("Compound interest is", CI) # write a python program to print the ascii value of input character character = input(" Enter Character :") print(f"Ascii value of character {character} is : " , ord(character)) # write a python program that takes input an integer and find sum of series with cubes of first n natural numbers using list comprehension which ta N = int(input("Enter Integer ")) lst = [i**3 for i in range(1, N + 1)] print(sum(lst)) # write a python function that takes list as an input and converts it into tuple def convert(list): return tuple(list) # Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. def last(n): return n[-1] def sort_list_last(tuples): return sorted(tuples, key=last) print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])) # write a python program to concatenate two dictionaries d1 = {'a' : 1 ,'b' : 2} d2 = {'c' : 1 ,'d' : 2} d3 = {**d1,**d2} print(d3) # Write a Python program to print the length of a set. #Create a set seta = set([5, 10, 3, 15, 2, 20]) #Find the length use len() print(len(seta)) # write a python program that takes two sets as input and print the common elements s1 = eval(input("Enter set 1 ")) s2 = eval(input("Enter set 2 ")) print(s1.intersection(s2)) # write a python program which takes input a list and prints the mean of elements within the list s1 = eval(input("Enter list ")) mean = sum(s1) / len(s1) print("Mean of sample is : " + str(mean)) # write a python program which takes input a list and prints the standard deviation of elements within the list mean = sum(s1) / len(s1) variance = sum([((x - mean) ** 2) for x in s1]) / len(s1) res = variance ** 0.5 print("Standard deviation of sample is : " + str(res)) # write a python program which prints a random number import random n = random.random() print(n) # write a python function that takes input a string and removes duplicates from the same foo = input("Enter String : ") print("Duplicates Removed","".join(set(foo))) # Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. def add_string(str1): length = len(str1) if length > 2: if str1[-3:] == 'ing': str1 += 'ly' else: str1 += 'ing' return str1 # Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. def not_poor(str1): snot = str1.find('not') spoor = str1.find('poor') if spoor > snot and snot>0 and spoor>0: str1 = str1.replace(str1[snot:(spoor+4)], 'good') return str1 else: return str1 # Write a Python program to count the occurrences of each word in a given sentence. def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts # Write a Python function to create the HTML string with tags around the word(s). def add_tags(tag, word): return "<%s>%s" % (tag, word, tag) # Write a Python program to count the number of even and odd numbers from a series of numbers. numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 #Write a Python program that prints each item and its corresponding type from the following list. datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}] for item in datalist: print ("Type of ",item, " is ", type(item)) # Write a Python program to sort (ascending) a dictionary by value. d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print({k :v for k,v in sorted(d.items(),key = lambda x : x[1])}) # Write a Python program to sort (Descending) a dictionary by value. d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print({k :v for k,v in sorted(d.items(),key = lambda x : x[1],reverse = True)}) # Write a Python program to sort list. numbers = [1, 3, 4, 2] numbers.sort() print(numbers) # Write a Python program to sort a list of tuples by second Item def Sort_Tuple(tup): return(sorted(tup, key = lambda x: x[1])) tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] print(Sort_Tuple(tup)) # write a python program that tke two inputs from user and check whether they are equal or not. print("Enter first number") first = input() print("Enter second number") second = input() print(first == second) # write a python program that takes input a list and squares every term using list comprehension s1 = eval(input("Enter list ")) print([i**2 for i in s1]) # write a python program that takes input a list and cube every term using list comprehension s1 = eval(input("Enter list ")) print([i**3 for i in s1]) # write a python program that takes input a list and square root every term using list comprehension s1 = eval(input("Enter list ")) print([i**0.5 for i in s1]) # write a python function that takes input a list of string and print the largest string def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][0], word_len[-1][1] # write a python program that takes input a string and prints the count of words s1 = input("Enter string ") print("Count of words",len(s1.split())) # write a Python function that takes list of tuples as input and sort those alphabetically def SortTuple(tup): n = len(tup) for i in range(n): for j in range(n-i-1): if tup[j][0] > tup[j + 1][0]: tup[j], tup[j + 1] = tup[j + 1], tup[j] return tup # write a python program which takes a list and swaps the first and last value of the list. a=[] n= int(input("Enter the number of elements in list:")) for x in range(0,n): element=int(input("Enter element" + str(x+1) + ":")) a.append(element) temp=a[0] a[0]=a[n-1] a[n-1]=temp print("New list is:") print(a) # write a python program that print today's date from datetime import date print(date.today()) # write a python program that takes input number of lines and finds the possible number of intersection def countMaxIntersect(n): return int(n*(n - 1)/2) # write a python program to input a number n and print an inverted star pattern of the desired size. n=int(input("Enter number of rows: ")) for i in range (n,0,-1): print((n-i) * ' ' + i * '*') # write a python program to input a number and check whether a given number is a palindrome. n=int(input("Enter number:")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print("The number is a palindrome!") else: print("The number isn't a palindrome!") # write a python program to input a number and find the smallest divisor of an integer. n=int(input("Enter an integer:")) a=[] for i in range(2,n+1): if(n%i==0): a.append(i) a.sort() print("Smallest divisor is:",a[0]) # write a python program to accept three distinct digits and prints all possible combinations from the digits. a=int(input("Enter first number:")) b=int(input("Enter second number:")) c=int(input("Enter third number:")) d=[] d.append(a) d.append(b) d.append(c) for i in range(0,3): for j in range(0,3): for k in range(0,3): if(i!=j&j!=k&k!=i): print(d[i],d[j],d[k]) # write a python function to insert an element into sorted python list def insert(list, n): for i in range(len(list)): if list[i] > n: index = i break list = list[:i] + [n] + list[i:] return list # write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') # write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum # write a program to find and print the largest among three number snum1 = 10 num2 = 12 num3 = 14 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}') # write a python function to subtract two user provided numbers and return the result def sub_two_numbers(num1, num2): sub = num1 - num2 return sub # write a python function to multiply two user provided numbers and return the result def mul_two_numbers(num1, num2): mul = num1 * num2 return mul # write a python program to pop element form dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} print(squares.pop(4)) #write a python program that prints the length of tuple thistuple = ("apple", "banana", "cherry") print(len(thistuple)) #1 write a program to get numbers = 1,3,11,42,12,4001 from collections import Iterable highestnumber = -999 for i in numbers: if i > highestnumber: highestnumber = i print(numbers.index(highestnumber)) #2 write a program to get numbers = 1,3,11,42,12,4001 highestnumber = -999 for i in numbers: if i > highestnumber: highestnumber = i print(numbers.index(highestnumber)) #3 add 1 to all elements in list python lst = [1,2,3] list(map(lambda x:x+1, lst)) #4 add a string to each element of a list python my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' list2 = list(map(lambda orig_string: orig_string + string, my_list)) #5 add a third dimension matrix dataset python x = [2D_matrix] # To convert from a 2-D to 3-D # or x = [[[value1]]] # To convert from a 1-D to 3-D #6 python add all values of another list a = [1, 2, 3] b = [4, 5, 6] a += b #7 add a value to the start of a list python var=7 array = [1,2,3,4,5,6] array.insert(0,var) #8 print into lowersase an uppercase sentence in python s = "Kilometer" print(s.lower()) #9 sort a dictionary mydictionary : {1: 1, 7: 2, 4: 2, 3: 1, 8: 1} sortedDictionary = sorted(mydictionary.keys()) #10 limit decimals to only two decimals in python answer = str(round(answer, 2)) #11 print how many keys are in a dictionary python a = {'foo':42, 'bar':69} print(len(a)) #11 access index of a character in a string python foo = 'Hello' foo.find('lo') #12 python print last element of list mylist = [0, 1, 2] print(myList[-1]) #13 how to add a blank line in python print("") #14 how to add element at first position in array python x = [1,3,4] a = 2 x.insert(1,a) #15 how to add extra zeros after decimal in python format(2.0, '.6f') '2.000000' #16 how to add list numbers in python numbers = [1,2,3,4,5,1,4,5] Sum = sum(numbers) #17 split list into lists of equal length python [lst[i:i + n] for i in range(0, len(lst), n)] #18 how to break out of nested loops python x_loop_must_break = False for x in [1, 2, 3]: print(f"x is {x}") for y in [1, 2, 3]: print(f"y is {y}") if y == 2: x_loop_must_break = True break if x_loop_must_break: break #19 capitalize first letter in python in list my_list = ['apple pie', 'orange jam'] my_list[0].capitalize() #20 how to check if a list is a subset of another list if(all(x in test_list for x in sub_list)): flag = True #21 write a function to check if string is camelcase pythonpython by Breakable Buffalo on Aug 09 2020 Donate def is_camel_case(s): return s != s.lower() and s != s.upper() and "_" not in s #22 how to check if string is in byte formate pythin isinstance(string, bytes) #23 how to check nth prime in python x=int(input()) n,c=1,0 while(c 1: mid = len(myList) // 2 left = myList[:mid] right = myList[mid:] # Recursive call on each half mergeSort(left) mergeSort(right) # Two iterators for traversing the two halves i = 0 j = 0 # Iterator for the main list k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: # The value from the left half has been used myList[k] = left[i] # Move the iterator forward i += 1 else: myList[k] = right[j] j += 1 # Move to the next slot k += 1 # For all the remaining values while i < len(left): myList[k] = left[i] i += 1 k += 1 while j < len(right): myList[k]=right[j] j += 1 k += 1 myList = [54,26,93,17,77,31,44,55,20] mergeSort(myList) #50 write a python function to find the median on an array of numbers def median(arr): if len(arr) == 1: return arr[0] else: arr = sorted(arr) a = arr[0:round(len(arr)/2)] b = arr[len(a):len(arr)] if len(arr)%2 == 0: return (a[len(a)-1]+b[0])/2 else: return a[len(a)-1] #51 write a python function to find a missing number in a list of consecutive natural numbers def getMissingNo(A): n = len(A) total = (n + 1)*(n + 2)/2 sum_of_A = sum(A) return total - sum_of_A #52 write a python program to normalize a list of numbers and print the result a = [2,4,10,6,8,4] amin, amax = min(a), max(a) for i, val in enumerate(a): a[i] = (val-amin) / (amax-amin) print(a) #53 write a python program to permutations of a given string in python and print the result from itertools import permutations import string s = "GEEK" a = string.ascii_letters p = permutations(s) d = [] for i in list(p): if (i not in d): d.append(i) print(''.join(i)) #54 Write a Python function to check if a number is a perfect square def is_perfect_square(n): x = n // 2 y = set([x]) while x * x != n: x = (x + (n // x)) // 2 if x in y: return False y.add(x) return True #55 Write a Python function to check if a number is a power of a given base. import math def isPower (n, base): if base == 1 and n != 1: return False if base == 1 and n == 1: return True if base == 0 and n != 1: return False power = int (math.log(n, base) + 0.5) return base ** power == n #56 Write a Python function to find three numbers from an array such that the sum of three numbers equal to zero. def three_Sum(num): if len(num)<3: return [] num.sort() result=[] for i in range(len(num)-2): left=i+1 right=len(num)-1 if i!=0 and num[i]==num[i-1]:continue while left 0 else 0 #60 Write a function program to reverse the digits of an integer. def reverse_integer(x): sign = -1 if x < 0 else 1 x *= sign # Remove leading zero in the reversed integer while x: if x % 10 == 0: x /= 10 else: break # string manipulation x = str(x) lst = list(x) # list('234') returns ['2', '3', '4'] lst.reverse() x = "".join(lst) x = int(x) return sign*x #61 Write a Python function to reverse the bits of an integer (32 bits unsigned). def reverse_Bits(n): result = 0 for i in range(32): result <<= 1 result |= n & 1 n >>= 1 return result #62 Write a Python function to check a sequence of numbers is an arithmetic progression or not. def is_arithmetic(l): delta = l[1] - l[0] for index in range(len(l) - 1): if not (l[index + 1] - l[index] == delta): return False return True #63 Python Challenges: Check a sequence of numbers is a geometric progression or not def is_geometric(li): if len(li) <= 1: return True # Calculate ratio ratio = li[1]/float(li[0]) # Check the ratio of the remaining for i in range(1, len(li)): if li[i]/float(li[i-1]) != ratio: return False return True #64 Write a Python function to compute the sum of the two reversed numbers and display the sum in reversed form. def reverse_sum(n1, n2): return int(str(int(str(n1)[::-1]) + int(str(n2)[::-1]))[::-1]) #65 Write a Python function where you take any positive integer n, if n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach 1. def collatz_sequence(x): num_seq = [x] if x < 1: return [] while x > 1: if x % 2 == 0: x = x / 2 else: x = 3 * x + 1 num_seq.append(x) return num_seq #65 Write a Python function to check if a given string is an anagram of another given string. def is_anagram(str1, str2): list_str1 = list(str1) list_str1.sort() list_str2 = list(str2) list_str2.sort() return (list_str1 == list_str2) #66 Write a Python function to push all zeros to the end of a list. def move_zero(num_list): a = [0 for i in range(num_list.count(0))] x = [ i for i in num_list if i != 0] x.extend(a) return(x) #67 Write a Python function to the push the first number to the end of a list. def move_last(num_list): a = [num_list[0] for i in range(num_list.count(num_list[0]))] x = [ i for i in num_list if i != num_list[0]] x.extend(a) return(x) #68 Write a Python function to find the length of the last word. def length_of_last_word(s): words = s.split() if len(words) == 0: return 0 return len(words[-1]) #69 Write a Python function to add two binary numbers. def add_binary_nums(x,y): max_len = max(len(x), len(y)) x = x.zfill(max_len) y = y.zfill(max_len) result = '' carry = 0 for i in range(max_len-1, -1, -1): r = carry r += 1 if x[i] == '1' else 0 r += 1 if y[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 if carry !=0 : result = '1' + result return result.zfill(max_len) #70 Write a Python function to find the single number which occurs odd numbers and other numbers occur even number. def odd_occurrence(arr): # Initialize result result = 0 # Traverse the array for element in arr: # XOR result = result ^ element return result #71 Write a Python function that takes a string and encode it that the amount of symbols would be represented by integer and the symbol. For example, the string "AAAABBBCCDAAA" would be encoded as "4A3B2C1D3A" def encode_string(str1): encoded = "" ctr = 1 last_char = str1[0] for i in range(1, len(str1)): if last_char == str1[i]: ctr += 1 else: encoded += str(ctr) + last_char ctr = 0 last_char = str1[i] ctr += 1 encoded += str(ctr) + last_char return encoded #72 Write a Python function to create a new array such that each element at index i of the new array is the product of all the numbers of a given array of integers except the one at i. def product(nums): new_nums = [] for i in nums: nums_product = 1 for j in nums: if j != i: nums_product = nums_product * j new_nums.append(nums_product) return new_nums #73 Write a python function to find the difference between the sum of the squares of the first two hundred natural numbers and the square of the sum. r = range(1, 201) a = sum(r) print (a * a - sum(i*i for i in r)) #74 Write a Python function to compute s the sum of the digits of the number 2 to the power 20. def digits_sum(): n = 2**20 ans = sum(int(c) for c in str(n)) return str(ans) #75 Write a Python program to compute the sum of all the multiples of 3 or 5 below 500. n = 0 for i in range(1,500): if not i % 5 or not i % 3: n = n + i print(n) #76 Write a Python function to converting an integer to a string in any base. def to_string(n,base): conver_tString = "0123456789ABCDEF" if n < base: return conver_tString[n] else: return to_string(n//base,base) + conver_tString[n % base #77 Write a Python function to calculate the geometric sum of n-1. def geometric_sum(n): if n < 0: return 0 else: return 1 / (pow(2, n)) + geometric_sum(n - 1) #78 Write a Python function 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) #79 Write a program to print which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) #80 write a Python program to print the roots of a quadratic equation import math a = float(input("Enter the first coefficient: ")) b = float(input("Enter the second coefficient: ")) c = float(input("Enter the third coefficient: ")) if (a!=0.0): d = (bb)-(4ac) if (d==0.0): print("The roots are real and equal.") r = -b/(2a) print("The roots are ", r,"and", r) elif(d>0.0): print("The roots are real and distinct.") r1 = (-b+(math.sqrt(d)))/(2a) r2 = (-b-(math.sqrt(d)))/(2a) print("The root1 is: ", r1) print("The root2 is: ", r2) else: print("The roots are imaginary.") rp = -b/(2a) ip = math.sqrt(-d)/(2a) print("The root1 is: ", rp, "+ i",ip) print("The root2 is: ", rp, "- i",ip) else: print("Not a quadratic equation." #81 Write a Python program to convert a given Bytearray to Hexadecimal string. def bytearray_to_hexadecimal(list_val): result = ''.join('{:02x}'.format(x) for x in list_val) return(result) #82 Write a Python program to count number of substrings with same first and last characters of a given string. def no_of_substring_with_equalEnds(str1): result = 0; n = len(str1); for i in range(n): for j in range(i, n): if (str1[i] == str1[j]): result = result + 1 return result #83 Write a Python program to move all spaces to the front of a given string in single traversal. def moveSpaces(str1): no_spaces = [char for char in str1 if char!=' '] space= len(str1) - len(no_spaces) result = ' '*space return result + ''.join(no_spaces) #84 Write a Python program to find maximum length of consecutive 0ā€™s in a given binary string. def max_consecutive_0(input_str): return max(map(len,input_str.split('1'))) str1 = '111000010000110' print("Original string:" + str1) print("Maximum length of consecutive 0ā€™s:") #85 Write a Python program that iterate over elements repeating each as many times as its count. from collections import Counter c = Counter(p=4, q=2, r=0, s=-2) print(list(c.elements())) #86 Write a Python program to find the second smallest number in a list. def second_smallest(numbers): if (len(numbers)<2): return if ((len(numbers)==2) and (numbers[0] == numbers[1]) ): return dup_items = set() uniq_items = [] for x in numbers: if x not in dup_items: uniq_items.append(x) dup_items.add(x) uniq_items.sort() return uniq_items[1] #87 Write a Python function to check whether a list contains a sublist. def is_Sublist(l, s): sub_set = False if s == []: sub_set = True elif s == l: sub_set = True elif len(s) > len(l): sub_set = False else: for i in range(len(l)): if l[i] == s[0]: n = 1 while (n < len(s)) and (l[i+n] == s[n]): n += 1 if n == len(s): sub_set = True return sub_set #86 Write a Python program to generate groups of five consecutive numbers in a list l = [[5*i + j for j in range(1,6)] for i in range(5)] print(l) #87 Write a Python program to print the list in a list of lists whose sum of elements is the highest. print(max(num, key=sum)) #88 Write a Python fuction to print the depth of a dictionary. def dict_depth(d): if isinstance(d, dict): return 1 + (max(map(dict_depth, d.values())) if d else 0) return 0 dic = {'a':1, 'b': {'c': {'d': {}}}} print(dict_depth(dic)) #89 Write a Python function to pack consecutive duplicates of a given list elements into sublists and print the output. from itertools import groupby def pack_consecutive_duplicates(l_nums): return [list(group) for key, group in groupby(l_nums)] n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ] print("Original list:") print(n_list) print("\nAfter packing consecutive duplicates of the said list elements into sublists:") print(pack_consecutive_duplicates(n_list)) #90 Write a Python function to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters and print the output. from itertools import groupby def modified_encode(alist): def ctr_ele(el): if len(el)>1: return [len(el), el[0]] else: return el[0] return [ctr_ele(list(group)) for key, group in groupby(alist)] n_list = [1,1,2,3,4,4,5, 1] print("Original list:") print(n_list) print("\nList reflecting the modified run-length encoding from the said list:") print(modified_encode(n_list)) #91 Write a Python function to create a multidimensional list (lists of lists) with zeros and print the output. nums = [] for i in range(3): nums.append([]) for j in range(2): nums[i].append(0) print("Multidimensional list:") print(nums) #92 Write a Python function to read a square matrix from console and print the sum of matrix primary diagonal.Accept the size of the square matrix and elements for each column separated with a space (for every row) as input from the user and print the output. size = int(input("Input the size of the matrix: ")) matrix = [[0] * size for row in range(0, size)] for x in range(0, size): line = list(map(int, input().split())) for y in range(0, size): matrix[x][y] = line[y] matrix_sum_diagonal = sum(matrix[size - i - 1][size - i - 1] for i in range(size)) #93 Write a Python function to check if a nested list is a subset of another nested list and print the output. def checkSubset(input_list1, input_list2): return all(map(input_list1.__contains__, input_list2)) list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]] list2 = [[1, 3],[13,15,17]] print("Original list:") print(list1) print(list2) print("\nIf the one of the said list is a subset of another.:") print(checkSubset(list1, list2)) #94 Write a Python function to print all permutations with given repetition number of characters of a given string and print the output. from itertools import product def all_repeat(str1, rno): chars = list(str1) results = [] for c in product(chars, repeat = rno): results.append(c) return results print(all_repeat('xyz', 3)) #95 Write a Python function to find the index of a given string at which a given substring starts. If the substring is not found in the given string return 'Not found' and print the output. def find_Index(str1, pos): if len(pos) > len(str1): return 'Not found' for i in range(len(str1)): for j in range(len(pos)): if str1[i + j] == pos[j] and j == len(pos) - 1: return i elif str1[i + j] != pos[j]: break return 'Not found #96 Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors. def smallest_multiple(n): if (n<=2): return n i = n * 2 factors = [number for number in range(n, 1, -1) if number * 2 > n] print(factors) while True: for a in factors: if i % a != 0: i += n break if (a == factors[-1] and i % a == 0): return i #97 Write a Python program to print all permutations of a given string (including duplicates). def permute_string(str): if len(str) == 0: return [''] prev_list = permute_string(str[1:len(str)]) next_list = [] for i in range(0,len(prev_list)): for j in range(0,len(str)): new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1] if new_str not in next_list: next_list.append(new_str) return next_lis #98 Write a Python program to multiply two integers without using the '*' operator in python. def multiply(x, y): if y < 0: return -multiply(x, -y) elif y == 0: return 0 elif y == 1: return x else: return x + multiply(x, y - 1) #99 Write a Python program to calculate distance between two points using latitude and longitude. from math import radians, sin, cos, acos print("Input coordinates of two points:") slat = radians(float(input("Starting latitude: "))) slon = radians(float(input("Ending longitude: "))) elat = radians(float(input("Starting latitude: "))) elon = radians(float(input("Ending longitude: "))) dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon)) print("The distance is %.2fkm." % dist) #99 Write a Python class to convert a roman numeral to an integer. class Solution: def roman_to_int(self, s): rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} int_val = 0 for i in range(len(s)): if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]: int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]] else: int_val += rom_val[s[i]] return int_val #100 Write a Python class to convert an integer to a roman numeral. class Solution: def int_to_Roman(self, num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in range(num // val[i]): roman_num += syb[i] num -= val[i] i += 1 return roman_num # Write a program to merge two python dictionaries and print merged dictionary d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(d) # write a python function to concatenate two integers like string concatenation and return concatenated number as integer def concat_two_numbers(num1, num2): combined_num = str(num1) + str(num2) return int(combined_num) # With a given integral number n, write a program to generate a dictionary that contains (i, i*i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. n = 8 d = dict() for i in range(1,n+1): d[i] = i*i*i print(d) # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. values=input() l=values.split(",") t=tuple(l) print(l) print(t) # Write a Python function that takes a sequence of numbers and determines whether all the numbers are different from each other def test_distinct(data): if len(data) == len(set(data)): return True else: return False # Write a Python function to find the number of notes (Sample of notes: 10, 20, 50, 100, 200 and 500 ) against a given amount. def no_notes(a): Q = [500, 200, 100, 50, 20, 10, 5, 2, 1] x = 0 for i in range(9): q = Q[i] x += int(a / q) a = int(a % q) if a > 0: x = -1 return x # Write a Python function to find the number of zeros at the end of a factorial of a given positive number. def factendzero(n): x = n // 5 y = x while x > 0: x /= 5 y += int(x) return y # Write a Python function for Binary Search def binary_search(l, num_find): ''' This function is used to search any number. Whether the given number is present in the list or not. If the number is present in list the list it will return TRUE and FALSE otherwise. ''' start = 0 end = len(l) - 1 mid = (start + end) // 2 found = False position = -1 while start <= end: if l[mid] == num_find: found = True position = mid break if num_find > l[mid]: start = mid + 1 mid = (start + end) // 2 else: end = mid - 1 mid = (start + end) // 2 return (found, position) # Write a Python function to remove leading zeros from an IP address import re regex = '\.[0]*' def remove_leading_zeros(ip): modified_ip = re.sub(regex, '.', ip) return modified_ip # Write a Python function to return binary value of a given integer def int_to_bin(a): return bin(a) # Write a Python function to return octal value of a given integer def int_to_oct(a): return oct(a) # Write a Python function to return hexadecimal value of a given integer def int_to_hex(a): return hex(a) # Write a Python program to typecast given input to integer num = int(input("Input a value: ")) print(num) # Write a Python program to typecast given input to float num = float(input("Input a value: ")) print(num) # Write a Python program to check/test multiple variables against a value a = 10 b = 20 c = 30 if 10 in {a, b, c}: print("True") else: print("False") # Write a Python class that will initiate a number, input a number and print the number class Number: def __init__(self, num): self.num = num def inputNum(self): self.num = int(input("Enter an integer number: ")) def printNum(self): print(self.num) # Write a Python function to find the simple interest in Python when principle amount, rate of interest and time is given def simple_interest(p,r,t): si = (p*r*t)/100 return si # Write a Python function to find the compound interest in Python when principle amount, rate of interest and time is given def compound_interest(p,r,t): ci = p * (pow((1 + r / 100), t)) return ci # Write a Python function to check whether a person is eligible for voting or not based on their age def vote_eligibility(age): if age>=18: status="Eligible" else: status="Not Eligible" return status # Write a Python function to find the BMI for given weight and height of a person def bmi_calculator(height, weight): bmi = weight/(height**2) return bmi # Write a Python function to check whether a given number is perfect number or not def perfect_number_checker(num): i = 2 sum = 1 while(i <= num//2 ) : if (num % i == 0) : sum += i i += 1 if sum == num : return f'{num} is a perfect number' else : return f'{num} is not a perfect number' # Write a Python function to find the maximum ODD number from a given list def odd_max_checker(list1): maxnum = 0 for num in list1: if num%2 != 0: if num > maxnum: maxnum = num return maxnum # Write a Python function to find the maximum EVEN number from a given list def even_max_checker(list1): maxnum = 0 for num in list1: if num%2 == 0: if num > maxnum: maxnum = num return maxnum # Write a Python function to print the root of the quadratic equation def quadratic_root(A,B,C): import math d=((B**2)-4*A*C) if d>=0: s=(-B+(d)**0.5)/(2*A) p=(-B-(d)**0.5)/(2*A) print(math.floor(s),math.floor(p)) else: print('The roots are imaginary') # Write a Python program to print the calendar of any given year import calendar year=2020 print(calendar.calendar(year)) # Write a Python function to print whether the given Date is valid or not def date_validator(d,m,y): import datetime try: s=datetime.date(y,m,d) print("Date is valid.") except ValueError: print("Date is invalid.") # Write a Python function to find the N-th number which is both square and cube def nth_sq_and_cube(N): R = N**6 return R # Write a Python function to check whether a number is a power of another number or not def power_checker(a,b): import math s=math.log(a,b) p=round(s) if (b**p)==a: return f'{a} is the power of {b}.' else: return f'{a} is NOT the power of {b}.' # Write a Python function to def binary_palindrome(n): s=int(bin(n)[2:]) r=str(s)[::-1] if int(r)==s: return "The binary representation of the number is a palindrome." else: return "The binary representation of the number is NOT a palindrome." # Write a Python program to print the list of all keywords import keyword print("Python keywords are...") print(keyword.kwlist) # Write a Python function to find the intersection of two arrays def array_intersection(A,B): inter=list(set(A)&set(B)) return inter # Write a Python function to find the union of two arrays def array_union(A,B): union=list(set(A)|set(B)) return union # Write a Python program that prints a new set with all items from both sets by removing duplicates # --------------------------------------------------------- set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.union(set2)) # Write a Python program that Given two Python sets, update first set with items that exist only in the first set and not in the second set # --------------------------------------------------------- set1 = {10, 20, 30} set2 = {20, 40, 50} print(set1.difference_update(set2)) # Write a Python program that prints a set of all elements in either A or B, but not both # --------------------------------------------------------- set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.symmetric_difference(set2)) # Write a Python program that determines whether or not the following two sets have any elements in common. If yes display the common elements # --------------------------------------------------------- set1 = {10, 20, 30, 40, 50} set2 = {60, 70, 80, 90, 10} if set1.isdisjoint(set2): print("Two sets have no items in common") else: print("Two sets have items in common") print(set1.intersection(set2)) # Write a Python function to print number with commas as thousands separators def formattedNumber(n): return ("{:,}".format(n)) # Write a Python program to find the total number of uppercase and lowercase letters in a given string str1='TestStringInCamelCase' no_of_ucase, no_of_lcase = 0,0 for c in str1: if c>='A' and c<='Z': no_of_ucase += 1 if c>='a' and c<='z': no_of_lcase += 1 print(no_of_lcase) print(no_of_ucase) # Write a Python program to find the total number of letters and digits in a given string str1='TestStringwith123456789' no_of_letters, no_of_digits = 0,0 for c in str1: no_of_letters += c.isalpha() no_of_digits += c.isnumeric() print(no_of_letters) print(no_of_digits) # Write a Python function to count occurrence of a word in the given text def text_searcher(text, word): count = 0 for w in text.split(): if w == word: count = count + 1 return count # Write a Python function to capitalizes the first letter of each word in a string def capitalize(text): return text.title() # Write a Python function to remove falsy values from a list def newlist(lst): return list(filter(None, lst)) # Write a Python function to to find the sum of all digits of a given integer def sum_of_digits(num): if num == 0: return 0 else: return num % 10 + sum_of_digits(int(num / 10)) # Write a Python function to check all elements of a list are the same or not def check_equal(a): return a[1:] == a[:-1] # Write a Python program to convert string into a datetime object from datetime import datetime date_string = "Mar 26 2021 4:20PM" datetime_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p') print(datetime_object) # Write a Python function that returns the integer obtained by reversing the digits of the given integer def reverse(n): s=str(n) p=s[::-1] return p # Write a Python program that updates set1 by adding items from set2, except common items set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} set1.symmetric_difference_update(set2) print(set1) # Write a Python program that removes items from set1 that are not common to both set1 and set2 set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} set1.intersection_update(set2) print(set1) # Write a Python program to reverse a tuple aTuple = (10, 20, 30, 40, 50) aTuple = aTuple[::-1] print(aTuple) # Write a Python program to swap two tuples tuple1 = (11, 22) tuple2 = (99, 88) tuple1, tuple2 = tuple2, tuple1 print(tuple2) print(tuple1) # Write a Python program to modify the second item (33) of a list inside a following tuple to 333 tuple1 = (11, [22, 33], 44, 55) tuple1[1][1] = 333 print(tuple1) # Write a Python program to sort a tuple of tuples by 2nd item tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29)) tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1])) print(tuple1) # Write a Python function to check if all items in the following tuple are the same def check_tuple_same(sampleTuple): return all(i == sampleTuple[0] for i in sampleTuple) # Write a Python program to print current time in milliseconds import time milliseconds = int(round(time.time() * 1000)) print(milliseconds) # Write a Python function func1() such that it can accept a variable length of argument and print all arguments value def func1(*args): for i in args: print(i) # Write a Python program that Given a two Python list. Iterate both lists simultaneously such that list1 should display item in original order and list2 in reverse order list1 = [10, 20, 30, 40] list2 = [100, 200, 300, 400] for x, y in zip(list1, list2[::-1]): print(x, y) # Write a Python function that Given a string, display only those characters which are present at an even index number def printEveIndexChar(str): for i in range(0, len(str)-1, 2): print("index[",i,"]", str[i] ) # Write a Python function that Given a string and an integer number n, remove characters from a string starting from zero up to n and return a new string def removeChars(str, n): return str[n:] # Write a Python function that Given a list of numbers, return True if first and last number of a list is same def isFirst_And_Last_Same(numberList): firstElement = numberList[0] lastElement = numberList[-1] if (firstElement == lastElement): return True else: return False # Write a Python function that Given a list of numbers, Iterate it and print only those numbers which are divisible of 5 def findDivisible(numberList): for num in numberList: if (num % 5 == 0): print(num) # Write a Python function that Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list def mergeList(list1, list2): thirdList = [] for num in list1: if (num % 2 != 0): thirdList.append(num) for num in list2: if (num % 2 == 0): thirdList.append(num) return thirdList # Write a Python program to return a set of all elements in either A or B, but not both set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.symmetric_difference(set2)) # Write a Python program to Subtract a week ( 7 days) from a given date in Python from datetime import datetime, timedelta given_date = datetime(2020, 2, 25) days_to_subtract = 7 res_date = given_date - timedelta(days=days_to_subtract) print(res_date) # Write a Python program to Find the day of week of a given date from datetime import datetime given_date = datetime(2020, 7, 26) print(given_date.strftime('%A')) # Write a Python program to Convert following datetime instance into string format from datetime import datetime given_date = datetime(2020, 2, 25) string_date = given_date.strftime("%Y-%m-%d %H:%M:%S") print(string_date) # Write a Python program to convert two equal length sets to dictionary keys = {'Ten', 'Twenty', 'Thirty'} values = {10, 20, 30} sampleDict = dict(zip(keys, values)) print(sampleDict) # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5 between 2000 and 3200 (both included). l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) # Write a program that will determine the object type def typeIdentifier(object): return f'object type : {type(object)}' # Write a Python class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. class IOString(object): def __init__(self): self.s = "" def getString(self): self.s = input() def printString(self): print(self.s.upper()) strObj = IOString() strObj.getString() strObj.printString() # Write a program that will determine the memory usage by python process import os, psutil print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2) # Write a function that will provide the ascii value of a character def charToASCII(chr): return f'ASCII value of {chr} is: {ord(chr)}' # Write a function to reverse a string def revStr(inp): inp = inp[::-1] return inp # Write a function to determine the bits used by any number def totalBits(n): return f'total number of bits used in {n} is : {len(bin(n)[2: ])}' # write a function to find the sum of Sine series import math def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i pi=22/7 y=x*(pi/180) sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine # Write a function to determine whether a given number is even or odd recursively def check(n): if (n < 2): return (n % 2 == 0) return (check(n - 2)) n=int(input("Enter number:")) if(check(n)==True): print("Number is even!") else: print("Number is odd!") # Write a program to swap two variables inplace a,b = b,a # Write a program that prints the words in a comma-separated sequence after sorting them alphabetically. items=[x for x in input().split(',')] items.sort() print(','.join(items)) # Write a function that takes a base and a power and finds the power of the base using recursion. def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) base=int(input("Enter base: ")) exp=int(input("Enter exponential value: ")) print("Result:",power(base,exp)) # Write a function to repeat M characters of a string N times def multTimes(str, m, n): front_len = m if front_len > len(str): front_len = len(str) front = str[:front_len] result = '' for i in range(n): result = result + front return result print (multTimes('Hello', 3, 7)) # Write a function that will convert a string into camelCase from re import sub def camelCase(string): string = sub(r"(_|-)+", " ", string).title().replace(" ", "") return string[0].lower() + string[1:] # Write a function to remove empty list from a list using list comprehension def removeEmptyList(li): res = [ele for ele in li if ele != []] return res # Write a function to Find the size of a Tuple in Python without garbage values Tuple = (10,20) def sizeOfTuple(tup): return f'Size of Tuple: {str(Tuple.__sizeof__())} bytes' # Write a function, which will find all such numbers between 1000 to 9999 that each digit of the number is an even number. values = [] for i in range(1000, 9999): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) # Write a function that finds a list is homogeneous def homoList(li): res = True for i in li: if not isinstance(i, type(li[0])): res = False break return res # Write a function to remove a given date type elements from a list. def removeDataType(li,dType): res = [] for i in li: if not isinstance(i, dType): res.append(i) return res # Write a python function to find out the occurence of "i" element before first "j" in the list def firstOccurence(arr, i,j): res = 0 for k in arr: if k == j: break if k == i: res += 1 return res # Write a program to check whether a file/path/direcory exists or not file_path = "path/here" import os.path os.path.exists(file_path) # Write a program to merge two python dictionaries x={'key1':'val1','key2':'val2'} y={'key3':'val3','key4':'val4'} z = {**x, **y} # z = x | y # Write a program to convert dictionary into JSON import json data = {"key1" : "value1", "key2" : "value2"} jsonData = json.dumps(data) print(jsonData) # Write a program to find common divisors between two numbers in a given pair def ngcd(x, y): i=1 while(i<=x and i<=y): if(x%i==0 and y%i == 0): gcd=i i+=1 return gcd def num_comm_div(x, y): n = ngcd(x, y) result = 0 z = int(n**0.5) i = 1 while( i <= z ): if(n % i == 0): result += 2 if(i == n/i): result-=1 i+=1 return result # Write a function to Check whether following json is valid or invalid import json def validateJSON(jsonData): try: json.loads(jsonData) except ValueError as err: return False return True # Write a function to remove and print every third number from a list of numbers until the list becomes empty def remove_nums(int_list): position = 3 - 1 idx = 0 len_list = (len(int_list)) while len_list>0: idx = (position+idx)%len_list print(int_list.pop(idx)) len_list -= 1 # Write a program to take a string and print all the words and their frequencies string_words = '''This assignment is of 900 marks. Each example if 9 marks. If your example is similar to someone else, then you score less. The formula we will use is 9/(repeated example). That means if 9 people write same example, then you get only 1. So think different! (if examples are mentioned here and in the sample file, you will score less)''' word_list = string_words.split() word_freq = [word_list.count(n) for n in word_list] print("Pairs (Words and Frequencies:\n {}".format(str(list(zip(word_list, word_freq))))) # Write a program to get a list of locally installed Python modules import pkg_resources installed_packages = pkg_resources.working_set installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) for m in installed_packages_list: print(m) # Write a function to create all possible permutations from a given collection of distinct numbers def permute(nums): result_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) result_perms = new_perms return result_perms # Write a function to add two positive integers without using the '+' operator def add_without_plus_operator(a, b): while b != 0: data = a & b a = a ^ b b = data << 1 return a # Write a program to find the median among three given number x=10 y=20 z=30 if y < x and x < z: print(x) elif z < x and x < y: print(x) elif z < y and y < x: print(y) elif x < y and y < z: print(y) elif y < z and z < x: print(z) elif x < z and z < y: print(z) # Write a function to count the number of carry operations for each of a set of addition problems def carry_number(x, y): ctr = 0 if(x == 0 and y == 0): return 0 z = 0 for i in reversed(range(10)): z = x%10 + y%10 + z if z > 9: z = 1 else: z = 0 ctr += z x //= 10 y //= 10 if ctr == 0: return "No carry operation." elif ctr == 1: return ctr else: return ctr # Write a program to compute the number of digits in multiplication of two given integers a,b = 312, 410 print(len(str(a*b))) # Write a function to return the area of a rhombus def area(d1, a): d2 = (4*(a**2) - d1**2)**0.5 area = 0.5 * d1 * d2 return(area) # Write a function that Given a number, find the most significant bit number which is set bit and which is in power of two def setBitNumber(n): if (n == 0): return 0 msb = 0 n = int(n / 2) while (n > 0): n = int(n / 2) msb += 1 return (1 << msb) # Write a function to calculate volume of Triangular Pyramid def volumeTriangular(a, b, h): return (0.1666) * a * b * h # Write a function to calculate volume of Square Pyramid def volumeSquare(b, h): return (0.33) * b * b * h # Write a function to calculate Volume of Pentagonal Pyramid def volumePentagonal(a, b, h): return (0.83) * a * b * h # Write a function to calculate Volume of Hexagonal Pyramid def volumeHexagonal(a, b, h): return a * b * h # Write a python program to find and print if a number given is disarium or not num = 135 num_len = len(str(num)) n = num sum = 0 exp = num_len while n != 0: i = int(n % 10) n = int(n / 10) sum += i ** exp exp -= 1 if sum == num: print("disarium") else: print("not disarium") # Write a python program to find and print second largest number from list of numbers num_array = [8, 6, 15, 23, 14, 28, 5, 1, 99] largest = second_largest = num_array[0] for i in range(1,len(num_array)): if num_array[i] > largest: second_largest = largest largest = num_array[i] elif num_array[i] > second_largest: second_largest = num_array[i] print(second_largest) # Write a python program to find and print volume of a sphere for which diameter d is given import math diameter = 12. radius = diameter/2. # Calculate volume V V = 4./3. * math.pi * radius ** 3 print(f"Volume={V}") # Write a python program using list comprehension to produce and print the list ['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz'] input_string_list = ['x', 'y', 'z'] repeat_count = 4 list2 = [input_string_list[i] * (j+1) for i in range(len(input_string_list)) for j in range(repeat_count) ] print(list2) # Write a python program using list comprehension to produce and print the list ['x', 'y', 'z', 'xx', 'yy', 'zz', 'xxx', 'yyy', 'zzz', 'xxxx', 'yyyy', 'zzzz'] input_string_list = ['x', 'y', 'z'] repeat_count = 4 list3 = [input_string_list[i] * (j+1) for j in range(repeat_count) for i in range(len(input_string_list)) ] print(list3) # Write a python program using list comprehension to produce and print the list [[2],[3],[4],[3],[4],[5],[4],[5],[6]] start_num = 2 repeat_count = 3 max_offset = 3 list4 = [[start_num + i + j ] for j in range(max_offset) for i in range(repeat_count) ] print(list4) # Write a python program using list comprehension to produce and print the list [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]] start_num = 2 repeat_count = 4 max_offset =4 list5 = [[start_num + i + j for j in range(max_offset)] for i in range(repeat_count) ] print(list5) # Write a python program using list comprehension to produce and print the list [(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)] max_count = 3 list6 = [(j+1,i+1) for i in range(max_count) for j in range(max_count) ] print(list6) # Implement a python function longestWord which take input as list of words and return the longest word import functools def longestWord(word_list): if word_list is None or isinstance(word_list, list) == False or len(word_list) == 0: raise ValueError("Input word_list to function longestWord must be list of words of size at least 1") if len(word_list) == 1: return word_list[0] else: return functools.reduce(lambda x,y: x if len(x) >= len(y) else y, word_list) # Write a python program that maps list of words into a list of integers representing the lengths of the corresponding words lst = ["ab","cde","erty"] length_list = list(map((lambda element: len(element)), lst)) print(str(length_list)) # Write a python program to generate and print all sentences where subject is in["Americans", "Indians"] and verb is in ["Play", "watch"] and the object is in ["Baseball","cricket"] subjects=["Americans","Indians"] verbs=["play","watch"] objects=["Baseball","Cricket"] sentence_list = [subject + " " + verb + " " + object + "." for subject in subjects for verb in verbs for object in objects] for sentence in sentence_list: print(sentence) # Write a python program which accepts users first name and last name and print in reverse order with a space first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") print(last_name.strip() + " " + first_name.strip()) # Write a python function to find minimum edit distance between words given def minDistance(word1, word2): m = len(word1) n = len(word2) if m*n == 0: return m + n d = [ [0] * (n + 1) for _ in range(m+1)] for i in range(m+1): d[i][0] = i for j in range(n+1): d[0][j] = j for i in range(m+1): for j in range(n+1): left = d[i-1][j] + 1 down = d[i][j-1] + 1 left_down = d[i-1][j-1] if word1[i-1] != word2[j-1]: left_down += 1 d[i][j] = min(left, down, left_down) return d[m][n] # Write a python function to return list of all the possible gray code for a number given def grayCode(n): if n == 0: return [0] if n == 1: return [0,1] res = [] start = '0'*n visited = set() stk = [start] while stk: node = stk.pop() if node not in visited: res.append(int(node,2)) visited.add(node) if len(visited) == 2**n: break for i in range(n): newCh = '0' if node[i] == '1' else '1' newNode = node[:i] + newCh + node[i+1:] if newNode not in visited: stk.append(newNode) return res # Write a python function which takes a list of non negative numbers and target sum S, two operations (+, -) how many different ways target sum is achived re def findTargetSumWays(nums, S): count = 0 def calculate(nums, i, sum, S): nonlocal count if i == len(nums): if sum == S: count += 1 else: calculate(nums, i+1, sum+ nums[i], S) calculate(nums, i+1, sum- nums[i], S) calculate(nums, 0, 0, S) return count # Write a python function which wil return True if list parenthesis used in a input expression is valid, False otherwise def isValid(s): stack = [] mapping = {')': '(', '}' : '{', ']':'['} for char in s: if char in mapping: if not stack: return False top = stack.pop() if mapping[char] != top: return False else: stack.append(char) return not stack # Write a python function to solve and print Towers of Hanoi problem def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print("Move disk 1 from source",source,"to destination",destination) return TowerOfHanoi(n-1, source, auxiliary, destination) print("Move disk",n,"from source",source,"to destination",destination) TowerOfHanoi(n-1, auxiliary, destination, source) # Write a python function to check if a number given is a Armstrong number def isArmstrong(x): n = 0 while (x != 0): n = n + 1 x = x // 10 temp = x sum1 = 0 while (temp != 0): r = temp % 10 sum1 = sum1 + r ** n temp = temp // 10 return (sum1 == x) # Write a python program to find and print sum of series with cubes of first n natural numbers n = 10 sum = 0 for i in range(1, n+1): sum += i**3 print(f"{sum}") # Write a python function which returns True elements in a given list is monotonically increasing or decreasing, return False otherwise def isMonotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1))) # Write a python program to find and print product of two matrices A = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] B = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for r in result: print(r) # Write a python program to find and print K th column of a matrix test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]] K = 2 res = [sub[K] for sub in test_list] print("The Kth column of matrix is : " + str(res)) # Write a python program to Convert and print Snake case to Pascal case test_str = 'go_east_or_west_india_is_the_best' res = test_str.replace("_", " ").title().replace(" ", "") print(res) # Write a python program to print only even length words in a sentence def printEvenLengthWords(s): s = s.split(' ') for word in s: if len(word)%2==0: print(word) # Write a python function to find uncommon words between two sentences given def UncommonWords(A, B): count = {} for word in A.split(): count[word] = count.get(word, 0) + 1 for word in B.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] == 1] # Write a python function which determines if binary representation of a number is palindrome def binaryPallindrome(num): binary = bin(num) binary = binary[2:] return binary == binary[-1::-1] # Write a python program to extract and print words that starts with vowel test_list = ["all", "love", "and", "get", "educated", "by", "gfg"] res = [] vow = "aeiou" for sub in test_list: flag = False for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) print("The extracted words : " + str(res)) # Write a python function to extract URLs from a sentence import re def FindUrls(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # Write a python function to Check and print if binary representations of two numbers are anagram from collections import Counter def checkAnagram(num1,num2): bin1 = bin(num1)[2:] bin2 = bin(num2)[2:] zeros = abs(len(bin1)-len(bin2)) if (len(bin1)>len(bin2)): bin2 = zeros * '0' + bin2 else: bin1 = zeros * '0' + bin1 dict1 = Counter(bin1) dict2 = Counter(bin2) if dict1 == dict2: print('Yes') else: print('No') # Write a program to print inverted star pattern for the given number n=11 for i in range (n, 0, -1): print((n-i) * ' ' + i * '*') # Write a python function to find and print if IP address given is a valid IP address or not import re def Validate_IP(IP): regex = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|"\ "2[0-4][0-9]|25[0-5])\\.){3}"\ "([0-9]|[1-9][0-9]|1[0-9][0-9]|"\ "2[0-4][0-9]|25[0-5])" regex1 = "((([0-9a-fA-F]){1,4})\\:){7}"\ "([0-9a-fA-F]){1,4}" p = re.compile(regex) p1 = re.compile(regex1) if (re.search(p, IP)): return "Valid IPv4" elif (re.search(p1, IP)): return "Valid IPv6" return "Invalid IP" # Write a python function to find and print if a email address given is valid or not import re regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' def check(email): if(re.search(regex,email)): print("Valid Email") else: print("Invalid Email") # Write a python program to check and print if the password is valid or not not with given rules 1. Minimum 8 characters.2. The alphabets must be between [a-z] 3. At least one alphabet should be of Upper Case [A-Z] 4. At least 1 number or digit between [0-9]. 5. At least 1 character from [ _ or @ or $ ]. import re password = "R@m@_f0rtu9e$" flag = 0 while True: if (len(password)<8): flag = -1 break elif not re.search("[a-z]", password): flag = -1 break elif not re.search("[A-Z]", password): flag = -1 break elif not re.search("[0-9]", password): flag = -1 break elif not re.search("[_@$]", password): flag = -1 break elif re.search("\s", password): flag = -1 break else: flag = 0 print("Valid Password") break if flag ==-1: print("Not a Valid Password") # Write a python function to find and print the largest prime factor of a given number import math def maxPrimeFactors (n): maxPrime = -1 while n % 2 == 0: maxPrime = 2 n >>= 1 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i if n > 2: maxPrime = n return int(maxPrime) # Write a python function to determine if a year is leap year or not def is_leap(year): leap = False # Write your logic here if year % 4 == 0: if year % 400 == 0: leap = True elif year % 100 == 0: leap = False else: leap = True return leap # Write a python function to generate permuations of a list of given numbers def permute(nums): def backtrack(first = 0): if first == n: output.append(nums[:]) for i in range(first, n): nums[first], nums[i] = nums[i], nums[first] backtrack(first + 1) nums[first], nums[i] = nums[i], nums[first] n = len(nums) output = [] backtrack() return output # Write a python function to print staircase pattern def pattern(n): for i in range(1,n+1): # conditional operator k =i + 1 if(i % 2 != 0) else i for g in range(k,n): if g>=k: print(end=" ") for j in range(0,k): if j == k - 1: print(" * ") else: print(" * ", end = " ") # Write a python function to find gcd using eucliean algorithm def gcd(a, b): if a == 0 : return b return gcd(b%a, a) # Write a python function to check if number is divisible by all the digits def allDigitsDivide( n) : temp = n while (temp > 0) : digit = temp % 10 if not (digit != 0 and n % digit == 0) : return False temp = temp // 10 return True # Write a python program to flatten a multidimensional list my_list = [[10,20,30],[40,50,60],[70,80,90]] flattened = [x for temp in my_list for x in temp] print(flattened) # Write Python Program to Print Table of a Given Number n=int(input("Enter the number to print the tables for:")) for i in range(1,11): print(n,"x",i,"=",n*i) # Write a python program to check and print if the number is a perfect number n = int(input("Enter any number: ")) sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): print("The number is a Perfect number!") else: print("The number is not a Perfect number!") # Write a python function to find and print longest continous odd sequence of a list of numbers given def longest_continuous_odd_subsequence(array): final_list = [] temp_list = [] for i in array: if i%2 == 0: if temp_list != []: final_list.append(temp_list) temp_list = [] else: temp_list.append(i) if temp_list != []: final_list.append(temp_list) result = max(final_list, key=len) print(result) # Write a function to determine longest increasing subsequence of a list of numbers given def longest_increaing_subsequence(myList): lis = [1] * len(myList) elements = [0] * len(myList) for i in range (1 , len(myList)): for j in range(0 , i): if myList[i] > myList[j] and lis[i]< lis[j] + 1: lis[i] = lis[j]+1 elements[i] = j idx = 0 maximum = max(lis) idx = lis.index(maximum) seq = [myList[idx]] while idx != elements[idx]: idx = elements[idx] seq.append(myList[idx]) return (maximum, reversed(seq)) # Write function for performing heapsort on a list of numbers given def heapify(nums, heap_size, root_index): largest = root_index left_child = (2 * root_index) + 1 right_child = (2 * root_index) + 2 if left_child < heap_size and nums[left_child] > nums[largest]: largest = left_child if right_child < heap_size and nums[right_child] > nums[largest]: largest = right_child if largest != root_index: nums[root_index], nums[largest] = nums[largest], nums[root_index] heapify(nums, heap_size, largest) def heap_sort(nums): n = len(nums) for i in range(n, -1, -1): heapify(nums, n, i) # Move the root of the max heap to the end of for i in range(n - 1, 0, -1): nums[i], nums[0] = nums[0], nums[i] heapify(nums, i, 0) # Write a python function to perform quicksort sort on a list of numbers given def partition(array, low, high): i = low - 1 # index of smaller element pivot = array[high] # pivot for j in range(low, high): if array[j] < pivot: i += 1 array[i], array[j] = array[j], array[i] array[i + 1], array[high] = array[high], array[i + 1] return i + 1 def quick_sort(array, low, high): if low < high: temp = partition(array, low, high) quick_sort(array, low, temp - 1) quick_sort(array, temp + 1, high) # Given a decimal number N, write python functions check and print if a number has consecutive zeroes or not after converting the number to its K-based notation. def hasConsecutiveZeroes(N, K): z = toK(N, K) if (check(z)): print("Yes") else: print("No") def toK(N, K): w = 1 s = 0 while (N != 0): r = N % K N = N//K s = r * w + s w *= 10 return s def check(N): fl = False while (N != 0): r = N % 10 N = N//10 if (fl == True and r == 0): return False if (r > 0): fl = False continue fl = True return True # Write a python class to implement circular queue with methods enqueue, dequeue class CircularQueue(object): def __init__(self, limit = 10): self.limit = limit self.queue = [None for i in range(limit)] self.front = self.rear = -1 def __str__(self): if (self.rear >= self.front): return ' '.join([str(self.queue[i]) for i in range(self.front, self.rear + 1)]) else: q1 = ' '.join([str(self.queue[i]) for i in range(self.front, self.limit)]) q2 = ' '.join([str(self.queue[i]) for i in range(0, self.rear + 1)]) return q1 + ' ' + q2 def isEmpty(self): return self.front == -1 def isFull(self): return (self.rear + 1) % self.limit == self.front def enqueue(self, data): if self.isFull(): print('Queue is Full!') elif self.isEmpty(): self.front = 0 self.rear = 0 self.queue[self.rear] = data else: self.rear = (self.rear + 1) % self.limit self.queue[self.rear] = data def dequeue(self): if self.isEmpty(): print('Queue is Empty!') elif (self.front == self.rear): self.front = -1 self.rear = -1 else: self.front = (self.front + 1) % self.limit # Write a python class to implement Deque where elements can be added and deleted both ends class Deque(object): def __init__(self, limit = 10): self.queue = [] self.limit = limit def __str__(self): return ' '.join([str(i) for i in self.queue]) def isEmpty(self): return len(self.queue) <= 0 def isFull(self): return len(self.queue) >= self.limit def insertRear(self, data): if self.isFull(): return else: self.queue.insert(0, data) def insertFront(self, data): if self.isFull(): return else: self.queue.append(data) def deleteRear(self): if self.isEmpty(): return else: return self.queue.pop(0) def deleteFront(self): if self.isFull(): return else: return self.queue.pop() # Write a python class to implement PriorityQueue class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) def isEmpty(self): return len(self.queue) == [] def insert(self, data): self.queue.append(data) def delete(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() # Write a python function to return minimum sum of factors of a number def findMinSum(num): sum = 0 i = 2 while(i * i <= num): while(num % i == 0): sum += i num /= i i += 1 sum += num return sum # Write a function to check and print if a string starts with a substring using regex in Python import re def find(string, sample) : if (sample in string): y = "^" + sample x = re.search(y, string) if x : print("string starts with the given substring") else : print("string doesn't start with the given substring") else : print("entered string isn't a substring") # Write a python program to print square matrix in Z form arr = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]] n = len(arr[0]) i=0 for j in range(0, n-1): print(arr[i][j], end =" ") k = 1 for i in range(0, n): for j in range(n, 0, -1): if(j==n-k): print(arr[i][j], end = " ") break; k+=1 i=n-1; for j in range(0, n): print(arr[i][j], end = " ") # Write a python function to calculate number of ways of selecting p non consecutive stations out of n stations def stopping_station( p, n): num = 1 dem = 1 s = p while p != 1: dem *= p p-=1 t = n - s + 1 while t != (n-2 * s + 1): num *= t t-=1 if (n - s + 1) >= s: return int(num/dem) else: return -1 # Write a python program to solve and print the solution for the quadratic equation ax**2 + bx + c = 0 import cmath a = 1 b = 5 c = 6 d = (b**2) - (4*a*c) sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) # Write a program to print the powers of 2 using anonymous function terms = 10 result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) # Write a python function to find the L.C.M. of two input number def compute_lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # Write a Python program to shuffle and print a deck of card import itertools, random deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) random.shuffle(deck) print("You got:") for i in range(5): print(deck[i][0], "of", deck[i][1]) # Write a python program to sort alphabetically the words form a string provided by the user my_str = "Hello this Is an Example With cased letters" words = [word.lower() for word in my_str.split()] words.sort() print("The sorted words are:") for word in words: print(word) # Write a python program to remove punctuations from a sentence punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) # Write a python program to check and print Yes/No if a triangle of positive area is possible with the given angles def isTriangleExists(a, b, c): if(a != 0 and b != 0 and c != 0 and (a + b + c)== 180): if((a + b)>= c or (b + c)>= a or (a + c)>= b): return "YES" else: return "NO" else: return "NO" # Write a program to rotate and print elements of a list arr = [1, 2, 3, 4, 5]; n = 3; for i in range(0, n): #Stores the last element of array last = arr[len(arr)-1]; for j in range(len(arr)-1, -1, -1): #Shift element of array by one arr[j] = arr[j-1]; arr[0] = last; print(arr) # Write a program to find and print if a number is a Harshad number num = 156; rem = sum = 0; n = num; while(num > 0): rem = num%10; sum = sum + rem; num = num//10; if(n%sum == 0): print(str(n) + " is a harshad number") else: print(str(n) + " is not a harshad number") # Write a program to left rotate and print a list given arr = [1, 2, 3, 4, 5]; n = 3; for i in range(0, n): first = arr[0]; for j in range(0, len(arr)-1): arr[j] = arr[j+1]; arr[len(arr)-1] = first; print("Array after left rotation: "); for i in range(0, len(arr)): print(arr[i]), # Write a python function to implement 0/1 Knapsack problem def knapSack(W, wt, val, n): # Base Case if n == 0 or W == 0 : return 0 if (wt[n-1] > W): return knapSack(W, wt, val, n-1) else: return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) # Write a function to find out if permutations of a given string is a palindrome def has_palindrome_permutation(the_string): unpaired_characters = set() for char in the_string: if char in unpaired_characters: unpaired_characters.remove(char) else: unpaired_characters.add(char) return len(unpaired_characters) <= 1 # Write a python function to determine optimal buy and sell time of stocks given stocks for yesterday def get_max_profit(stock_prices): max_profit = 0 for outer_time in range(len(stock_prices)): for inner_time in range(len(stock_prices)): earlier_time = min(outer_time, inner_time) later_time = max(outer_time, inner_time) earlier_price = stock_prices[earlier_time] later_price = stock_prices[later_time] potential_profit = later_price - earlier_price max_profit = max(max_profit, potential_profit) return max_profit # Write a python function to check if cafe orders are served in the same order they are paid for def is_first_come_first_served(take_out_orders, dine_in_orders, served_orders): # Base case if len(served_orders) == 0: return True if len(take_out_orders) and take_out_orders[0] == served_orders[0]: return is_first_come_first_served(take_out_orders[1:], dine_in_orders, served_orders[1:]) elif len(dine_in_orders) and dine_in_orders[0] == served_orders[0]: return is_first_come_first_served(take_out_orders, dine_in_orders[1:], served_orders[1:]) else: return False # Write a function to merge meeting times given everyone's schedules def merge_ranges(meetings): sorted_meetings = sorted(meetings) merged_meetings = [sorted_meetings[0]] for current_meeting_start, current_meeting_end in sorted_meetings[1:]: last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1] if (current_meeting_start <= last_merged_meeting_end): merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) else: merged_meetings.append((current_meeting_start, current_meeting_end)) return merged_meetings # Write a python function which accepts or discard only string ending with alphanumeric character import re regex = '[a-zA-z0-9]$' def check(string): if(re.search(regex, string)): print("Accept") else: print("Discard") # Write a python program to accept a number n and calculate n+nn+nn n=int(input("Enter a number n: ")) temp=str(n) t1=temp+temp t2=temp+temp+temp comp=n+int(t1)+int(t2) print("The value is:",comp) # Write a program to accept a number and print inverted star pattern n=int(input("Enter number of rows: ")) for i in range (n,0,-1): print((n-i) * ' ' + i * '*') # Write a program to print prime numbers in a range using Sieve of Eratosthenes. n=int(input("Enter upper limit of range: ")) sieve=set(range(2,n+1)) while sieve: prime=min(sieve) print(prime,end="\t") sieve-=set(range(prime,n+1,prime)) print() # Write python function to generate valid parenthesis, number of parenthesis is given as input def generateParenthesis(n): def backtrack(S='', left=0, right=0): if len(S) == 2*n: output.append(S) return if left < n: backtrack(S+'(', left+1, right) if right < left: backtrack(S+')', left, right+1) output = [] backtrack() return output # Write python function which Given an list distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. def combinationSum(candidates, target): results = [] def helper(i, path): if sum(path) == target: results.append(path[:]) return if sum(path) > target: return for x in range(i, len(candidates)): path.append(candidates[x]) helper(x, path) path.pop() helper(0, []) return results # Write a function Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. def dailyTemperatures(T): stack = [] res = [0 for _ in range(len(T))] for i, t1 in enumerate(T): while stack and t1 > stack[-1][1]: j, t2 = stack.pop() res[j] = i - j stack.append((i, t1)) return res # Write a function which Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers Return True if its possible otherwise return False import collections def isPossibleDivide(nums, k): d = collections.Counter(nums) for num in sorted(d.keys()): if num in d: for i in range(k - 1, -1, -1): d[num + i] -= d[num] if d[num + i] == 0: del d[num + i] if d[num + i] < 0: return False return (True if not d else False) # Write a function pow(x, n), which calculates x raised to the power n def myPow(x, n): def pow(y, n): if n == 0: return 1.0 else: partial = pow(x, n//2) result = partial * partial if n%2 == 1: result *= x return result if n >= 0: return pow(x, n) else: return 1/ pow(x, -n) # Write a python class to implement LRU Cache class DLinkedNode: def __init__(self): self.key = 0 self.value = 0 self.prev = None self.next = None class LRUCache(object): def __init__(self, capacity): self.capacity = capacity self.head = DLinkedNode() self.tail = DLinkedNode() self.cache = {} self.size = 0 self.head.next = self.tail self.tail.prev = self.head def add_node(self, node): node.next = self.head.next node.prev = self.head self.head.next.prev = node self.head.next = node def remove_node(self, node): next = node.next prev = node.prev prev.next = next next.prev = prev def move_to_head(self, node ): self.remove_node(node) self.add_node(node) def tail_off(self ): res = self.tail.prev self.remove_node(res) return res def get(self, key): node = self.cache.get(key, None) if not node: return -1 self.move_to_head(node ) return node.value def put(self, key, value): node = self.cache.get(key, None) if not node: node = DLinkedNode() node.key = key node.value = value self.cache[key] = node self.add_node(node ) self.size += 1 if self.size > self.capacity: last_node = self.tail_off() del self.cache[last_node.key] self.size -= 1 else: node.value = value self.move_to_head(node ) # Write functions which given Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. def cross_sum(nums, left, right, p): if left == right: return nums[left] left_subsum=float('-Inf') current_sum = 0 for i in range(p, left-1, -1): current_sum += nums[i] left_subsum = max(left_subsum, current_sum) right_subsum=float('-Inf') current_sum = 0 for i in range(p+1, right+1): current_sum += nums[i] right_subsum = max(right_subsum, current_sum) return left_subsum + right_subsum def helper(nums, left, right): if left == right: return nums[left] p = (left + right) // 2 left_sum = helper(nums, left, p) right_sum = helper(nums, p+1, right) cross_sum1 = cross_sum(nums, left, right, p) return max(left_sum, right_sum, cross_sum1) def maxSubArray(nums): return helper(nums, 0, len(nums) -1) # Write a function which Given an list of integers arr and an integer target, find two non-overlapping sub-arrays of arr each with sum equal target from collections import defaultdict def minSumOfLengths(arr, target): hashTable = defaultdict(int) hashTable[0] = -1 summation = 0 for i in range(len(arr)): summation = summation + arr[i] hashTable[summation] = i summation = 0 minimumLeft = float('inf') result = float('inf') for i in range(len(arr)): summation = summation + arr[i] if summation - target in hashTable: leftLength = i-hashTable[summation-target] minimumLeft = min(minimumLeft,leftLength) if summation + target in hashTable and minimumLeft < float('inf'): rightLength = hashTable[summation+target]-i result = min(result,hashTable[summation+target]-i+minimumLeft) if result == float('inf'): return -1 return result # Write a function which Given a keyboard layout in XY plane, where each English uppercase letter is located at some coordinate, say (0,0) for A, return the minimum total distance to type such string using only two fingers. The distance distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|. from functools import lru_cache def minimumDistance(word): def getDist(a, b): if a==-1 or b==-1: return 0 else: i = ord(a) - ord('a') j = ord(b) - ord('b') dist = abs(i//6 - j//6) + abs(i%6 - j%6) return dist @lru_cache(maxsize=None) def getMinDist(l, r, k): if k==len(word): return 0 next = word[k].lower() ret = min(getMinDist(next,r,k+1)+getDist(l,next), getMinDist(l,next,k+1)+getDist(r,next)) return ret return(getMinDist(-1,-1,0)) # Write a function to generate permutation of list of numbers def permute(nums): def backtrack(first = 0): if first == n: output.append(nums[:]) for i in range(first, n): nums[first], nums[i] = nums[i], nums[first] backtrack(first + 1) nums[first], nums[i] = nums[i], nums[first] n = len(nums) output = [] backtrack() return output # Write a python class to implement a Bank which which supports basic operations like depoist, withdrwa, overdrawn class BankAccount(object): def __init__(self, account_no, name, initial_balance=0): self.account_no = account_no self.name = name self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def overdrawn(self): return self.balance < 0 # Write a function to calculate median of a list of numbers given def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 # Write a program to guess a number between 1 and 20 and greet if succesfully guessed and print the results import random guesses_made = 0 name = input('Hello! What is your name?\n') number = random.randint(1, 20) print ('Well, {0}, I am thinking of a number between 1 and 20.'.format(name)) while guesses_made < 6: guess = int(input('Take a guess: ')) guesses_made += 1 if guess < number: print ('Your guess is too low.') if guess > number: print ('Your guess is too high.') if guess == number: break if guess == number: print ('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)) else: print ('Nope. The number I was thinking of was {0}'.format(number)) # Write a python program to implement Rock, paper, scissor game and print the results import random import os import re os.system('cls' if os.name=='nt' else 'clear') while (1 < 2): print("\n") print("Rock, Paper, Scissors - Shoot!") userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ") if not re.match("[SsRrPp]", userChoice): print("Please choose a letter:") print("[R]ock, [S]cissors or [P]aper.") continue print("You chose: " + userChoice) choices = ['R', 'P', 'S'] opponenetChoice = random.choice(choices) print("I chose: " + opponenetChoice) if opponenetChoice == str.upper(userChoice): print("Tie! ") #if opponenetChoice == str("R") and str.upper(userChoice) == "P" elif opponenetChoice == 'R' and userChoice.upper() == 'S': print("Scissors beats rock, I win! ") continue elif opponenetChoice == 'S' and userChoice.upper() == 'P': print("Scissors beats paper! I win! ") continue elif opponenetChoice == 'P' and userChoice.upper() == 'R': print("Paper beat rock, I win! ") continue else: print("You win!") # Write a python program to implement Tic Tac Toe game and print the results import random import sys board=[i for i in range(0,9)] player, computer = '','' moves=((1,7,3,9),(5,),(2,4,6,8)) winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) tab=range(1,10) def print_board(): x=1 for i in board: end = ' | ' if x%3 == 0: end = ' \n' if i != 1: end+='---------\n'; char=' ' if i in ('X','O'): char=i; x+=1 print(char,end=end) def select_char(): chars=('X','O') if random.randint(0,1) == 0: return chars[::-1] return chars def can_move(brd, player, move): if move in tab and brd[move-1] == move-1: return True return False def can_win(brd, player, move): places=[] x=0 for i in brd: if i == player: places.append(x); x+=1 win=True for tup in winners: win=True for ix in tup: if brd[ix] != player: win=False break if win == True: break return win def make_move(brd, player, move, undo=False): if can_move(brd, player, move): brd[move-1] = player win=can_win(brd, player, move) if undo: brd[move-1] = move-1 return (True, win) return (False, False) def computer_move(): move=-1 for i in range(1,10): if make_move(board, computer, i, True)[1]: move=i break if move == -1: for i in range(1,10): if make_move(board, player, i, True)[1]: move=i break if move == -1: for tup in moves: for mv in tup: if move == -1 and can_move(board, computer, mv): move=mv break return make_move(board, computer, move) def space_exist(): return board.count('X') + board.count('O') != 9 player, computer = select_char() print('Player is [%s] and computer is [%s]' % (player, computer)) result='%%% Deuce ! %%%' while space_exist(): print_board() print('#Make your move ! [1-9] : ', end='') move = int(input()) moved, won = make_move(board, player, move) if not moved: print(' >> Invalid number ! Try again !') continue if won: result='*** Congratulations ! You won ! ***' break elif computer_move()[1]: result='=== You lose ! ==' break; print_board() print(result) # Write a python function to return zodiac sign given day and month of date of birth def zodiac_sign(day, month): if month == 'december': astro_sign = 'Sagittarius' if (day < 22) else 'capricorn' elif month == 'january': astro_sign = 'Capricorn' if (day < 20) else 'aquarius' elif month == 'february': astro_sign = 'Aquarius' if (day < 19) else 'pisces' elif month == 'march': astro_sign = 'Pisces' if (day < 21) else 'aries' elif month == 'april': astro_sign = 'Aries' if (day < 20) else 'taurus' elif month == 'may': astro_sign = 'Taurus' if (day < 21) else 'gemini' elif month == 'june': astro_sign = 'Gemini' if (day < 21) else 'cancer' elif month == 'july': astro_sign = 'Cancer' if (day < 23) else 'leo' elif month == 'august': astro_sign = 'Leo' if (day < 23) else 'virgo' elif month == 'september': astro_sign = 'Virgo' if (day < 23) else 'libra' elif month == 'october': astro_sign = 'Libra' if (day < 23) else 'scorpio' elif month == 'november': astro_sign = 'scorpio' if (day < 22) else 'sagittarius' print(astro_sign) # Write a function to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Write a python program to perform Vertical Concatenation in Matrix test_list = [["India", "good"], ["is", "for"], ["Best"]] print("The original list : " + str(test_list)) res = [] N = 0 while N != len(test_list): temp = '' for idx in test_list: try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] print("List after column Concatenation : " + str(res)) # Write a python program code to perform Triple quote String concatenation Using splitlines() + join() + strip() test_str1 = """India is""" test_str2 = """best for everybody """ print("The original string 1 is : " + test_str1) print("The original string 2 is : " + test_str2) test_str1 = test_str1.splitlines() test_str2 = test_str2.splitlines() res = [] for i, j in zip(test_str1, test_str2): res.append(" " + i.strip() + " " + j.strip()) res = '\n'.join(res) print("String after concatenation : " + str(res)) # Write a program to perform Consecutive prefix overlap concatenation Using endswith() + join() + list comprehension + zip() + loop def help_fnc(i, j): for ele in range(len(j), -1, -1): if i.endswith(j[:ele]): return j[ele:] test_list = ["India", "gone", "new", "best"] print("The original list is : " + str(test_list)) res = ''.join(help_fnc(i, j) for i, j in zip([''] + test_list, test_list)) print("The resultant joined string : " + str(res)) # Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row/column/subbox must contain the digits 1-9 without repetition. def isValidSudoku(board): rows = [{} for i in range(9)] columns = [{} for i in range(9)] boxes = [{} for i in range(9)] for i in range(9): for j in range(9): num = board[i][j] if num != '.': num = int(num) box_index = (i//3)*3 + (j//3) rows[i][num] = rows[i].get(num, 0) + 1 columns[j][num] = columns[j].get(num, 0) + 1 boxes[box_index][num] = boxes[box_index].get(num, 0) + 1 if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1: print(" i= {0} j = {1} box_index ={2}".format(i,j,box_index)) print("rows[i]: ", rows[i]) print("columnns[j]: ", columns[j]) print("boxes[box_index]: ", boxes[box_index]) return False return True # Write a python function to generate unique file names in a folder for a given list of file names from collections import Counter def getFolderNames(names): seen, res = Counter(), [] for name in names: if name in seen: while True: c = f'({seen[name]})' if name + c not in seen: name += c break else: seen[name] += 1 seen[name] += 1 res.append(name) return res # Write a python program to convert complex number to polar coordinates import cmath # using cmath.polar() method num = cmath.polar(1) print(num) # Write a python program to print calendar of a given year import calendar year = 2019 print(calendar.calendar(year)) # Write a python function to perform Matrix Chain multiplication i.e. Given a sequence of matrices, find the most efficient way to multiply these matrices together import sys def MatrixChainOrder(p, i, j): if i == j: return 0 _min = sys.maxsize for k in range(i, j): count = (MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i-1] * p[k] * p[j]) if count < _min: _min = count; return _min; #write a python program to print even numbers in a list list1 = [2,7,5,64,14] for i in list1: if i%2==0: print(i,end=" ") #write a python program to print positive numbers in a list list1 = [2,4,-5,3,8,-10,-11] for i in list1: if i>0: print(i,end=" ") #write a python program to remove empty list from list and print it list1 = [2,5,6,[],8,[],[],0] list2=[] for i in list1: if not isinstance(i,list): list2.append(i) print(list2) #write a python program to print the list having sum of digits list1 = [12, 67, 98, 34] list2=[] for i in list1: sum = 0 for digit in str(i): sum += int(digit) list2.append(sum) print(list2) # write a python program to find string in a list and print it list1 = [1, 2.0, 'have', 'a', 'nice', 'day'] s = 'nice' for i in list1: if i == s: print(f'{s} is present in the list') #write a python function to swap two numbers in a list and return the list def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list # Driver function List1 = [23, 65, 19, 90] pos1, pos2 = 1, 3 print(swapPositions(List1, pos1-1, pos2-1)) # write a python function tp print the occurences of i before first j in list list1 = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9] # initializing i, j i, j = 4, 8 count=0 for k in list1: if k==i and k!=j: count=count+1 elif k==j: break; print(count) # write a python program to print element with maximum values from a list list1 = ["gfg", "best", "for", "geeks"] s=[] for i in list1: count=0 for j in i: if j in ('a','e','i','o','u'): count=count+1 s.append(count) print(s) if count== max(s): print(list1[s.index(max(s))]) #9 write a python program to omit K length rows and print the list list1 = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]] # initializing K K = 2 for i in test_list: if len(i)==K: list1.remove(i) print(list1) #10 write a python program to construct equidigit tuple and print them list1 = [5654, 223, 982143, 34, 1021] list2 = [] for sub in list1: # getting mid element mid_idx = len(str(sub)) // 2 # slicing Equidigits el1 = str(sub)[:mid_idx] el2 = str(sub)[mid_idx:] list2.append((int(el1), int(el2))) # printing result print("Equidigit tuples List : " + str(list2)) #11 write a python function to filter Rows with a specific pair sum and return boolean value def pair_sum(x, k): # checking pair sum for idx in range(len(x)): for ix in range(idx + 1, len(x)): if x[idx] + x[ix] == k: return True return False # initializing list test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] # printing original list print("The original list is : " + str(test_list)) # initializing K k = 8 # checking for pair sum res = [ele for ele in test_list if pair_sum(ele, k)] # printing result print("Filtered Rows : " + str(res)) #12 write a python program to find decreasing point in a list and print them test_list = [3, 6, 8, 9, 12, 5, 18, 1] res = -1 for idx in range(0, len(test_list) - 1): # checking for 1st decreasing element if test_list[idx + 1] < test_list[idx]: res = idx break # printing result print("Decreasing Point : " + str(res)) #13 Write a python program to test if all elements are unique in columns in matrix and print them test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]] res = True for idx in range(len(test_list[0])): # getting column col = [ele[idx] for ele in test_list] # checking for all Unique elements if len(list(set(col))) != len(col): res = False break # printing result print("Are all columns Unique : " + str(res)) #14 Write a python program to find elements with the same index and print them list1 = [3, 1, 2, 5, 4, 10, 6, 9] list2 = [] for idx, ele in enumerate(list1): if idx == ele: list2.append(ele) # printing result print("Filtered elements : " + str(list2)) #15 Write a python program to check if two list are reverse equal and print boolean value list1 = [5, 6, 7, 8] list2 = [8, 7, 6, 5] # Check if two lists are reverse equal # Using reversed() + == operator res = list1 == list(reversed(list2)) # printing result print("Are both list reverse of each other ? : " + str(res)) #16 write a python program to extract priority elements in tuple list test_list = [(5, 1), (3, 4), (9, 7), (10, 6)] # initializing Priority list prior_list = [6, 4, 7, 1] # Extracting Priority Elements in Tuple List and print the list # loop res = [] for sub in test_list: for val in prior_list: if val in sub: res.append(val) print(res) #17 Write a python program to check if any string is empty in list and print true or False list1 = ['the', 'sun', 'rises', '', 'the', 'east'] # Check if any String is empty in list # using len() + any() res = any(len(ele) == 0 for ele in list1) # printing result print("Is any string empty in list? : " + str(res)) #18 write a python program to increment numeric string by K list = ["gfg", "234", "is", "98", "123", "best", "4"] # initializing K K = 6 res = [] for ele in test_list: # incrementing on testing for digit. if ele.isdigit(): res.append(str(int(ele) + K)) else: res.append(ele) # printing result print("Incremented Numeric Strings : " + str(res)) #19 Write a python function to remove i'th character from a string def remove(string, i): # Characters before the i-th indexed # is stored in a variable a a = string[ : i] # Characters after the nth indexed # is stored in a variable b b = string[i + 1: ] # Returning string after removing # nth indexed character. return a + b #20 Write a python program to move number to end of string and print them test_str = 'the2sun4rises5sinthe6east9' # printing original string print("The original string is : " + str(test_str)) s='' r='' for i in test_str: if i.isdigit(): s=s+i else: r=r+i print(r+s) #21 Write a python program to count the number of spaces in a string and print it count=0 string = "Welcome to schoolofAI" for i in string: if i==" ": count=count+1 print(f'number of spaces {count}') #22 Write a python program to Concatenate all elements of a list into a string and print it l = ['hello', 'guys', 'have', 'a', 'nice', 'day'] # this will join all the # elements of the list with ' ' l = ' '.join(l) print(l) #23 Write a python program to filter similar case strings and print it x=[] for i in test_list: if i.islower() or i.isupper(): print(x.append(i)) print(x) #24 Write a python program to increment Suffix number in string and print it test_str = 'hello006' x='' r='' for i in test_str: if i.isdigit() and int(i)>0: x=x+str(int(i)+1) else: r=r+i print(r+x) #25 Write a python program to add phrase in the middle of string and print it test_str = 'The sun in the east' mid_str = "rises" s="" l=test_str.split(" ") for i in range(0,len(l)): if i==len(l)//2: l.insert(i,mid_str) break s=" ".join(i for i in l) print(s) #26 Write a program to split a string by custom length and print it test_str = 'geeksforgeeks' # printing original string print("The original string is : " + str(test_str)) # initializing length list cus_lens = [5, 3, 2, 3] res = [] strt = 0 for size in cus_lens: # slicing for particular length res.append(test_str[strt : strt + size]) strt += size # printing result print("Strings after splitting : " + str(res)) #27 Write a python program to extract strings with successive alphabets in alphabetical order and print the list list1 = ['gfg', 'is', 'best', 'for', 'geeks'] res = [] for i in range(0,len(list1)): for j in range(0,len(list1[i])-1): if ord(list1[i][j+1])- ord(list1[i][j])==1: res.append(list1[i]) print(res) #28 Write a python program to compute arithmetic operation from String and print it test_str = '5x6, 9x10, 7x8' # using replace() to create eval friendly string temp = test_str.replace(',', '+').replace('x', '*') # using eval() to get the required result res = eval(temp) # printing result print("The computed summation of products : " + str(res)) #29 write a python program to Extract string till first Non-Alphanumeric character and print it test_str = 'geeks4g!!!eeks' s='' for i in test_str: if i.isalnum()==False: break else: s+=i print(s) #30 write a python program to extract domain name from Email address and print it test_str = 'md.shakiluzzaman@gmail.com' # printing original string print("The original string is : " + str(test_str)) s=test_str.split('@') print(s[1]) #31 write a python program to check if string starts with any element in list test_string = "GfG is best" # initializing prefix list pref_list = ['best', 'GfG', 'good'] # using filter() + startswith() # Prefix tests in Strings res = list(filter(test_string.startswith, pref_list)) != [] # print result print("Does string start with any prefix list sublist ? : " + str(res)) #32 write a python function to find all permutations of a string and print the result ini_str = "abc" # Printing initial string print("Initial string", ini_str) # Finding all permuatation result = [] def permute(data, i, length): if i == length: result.append(''.join(data) ) else: for j in range(i, length): # swap data[i], data[j] = data[j], data[i] permute(data, i + 1, length) data[i], data[j] = data[j], data[i] permute(list(ini_str), 0, len(ini_str)) # Printing result print("Resultant permutations", str(result)) #33 write a python program to delete all occurences of character and print it test_str = "TheSchoolofAI" # initializing removal character rem_char = "e" # Using replace() # Deleting all occurrences of character res = test_str.replace(rem_char, "") # printing result print("The string after character deletion : " + str(res)) #34 Write a python program for printing alternate Strings Concatenation test_list = ["Early", "morning", "is", "good", "for", "health"] # printing original list print("The original list : " + str(test_list)) s=[] k=test_list[::2] a=["".join(i for i in k)] print(a) l=test_list[1::2] b=["".join(i for i in l)] print(b) print(a+b) #35 Write a python program to remove duplicate word from sentence and print it str1 = "Good bye bye world world" l=str1.split(" ") #s=[] s=list(set(l)) print(" ".join(i for i in s)) #36 Write a python program to trim tuples by k and print it test_list = [(5, 3, 2, 1, 4), (3, 4, 9, 2, 1), (9, 1, 2, 3, 5), (4, 8, 2, 1, 7)] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 2 l=[] for i in test_list: #for j in i: s=tuple() s+=i[K:len(i)-K] l.append((s)) print(l) #37 write a python program to sort Tuples by their maximum element and print it def get_max(sub): return max(sub) # initializing list test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] # printing original list print("The original list is : " + str(test_list)) # sort() is used to get sorted result # reverse for sorting by max - first element's tuples test_list.sort(key = get_max, reverse = True) # printing result print("Sorted Tuples : " + str(test_list)) #38 write a python program to extract digits from Tuple list and print it test_list = [(15, 3), (3, 9), (1, 10), (99, 2)] # printing original list print("The original list is : " + str(test_list)) s=[] k='' for i in test_list: for j in i: k+=str(j) print(list(set(k))) #39 write a python program to print all pair combinations of two tuples test_tuple1 = (4, 5) test_tuple2 = (7, 8) # printing original tuples print("The original tuple 1 : " + str(test_tuple1)) print("The original tuple 2 : " + str(test_tuple2)) # All pair combinations of 2 tuples # Using list comprehension res = [(a, b) for a in test_tuple1 for b in test_tuple2] res = res + [(a, b) for a in test_tuple2 for b in test_tuple1] # printing result print("The filtered tuple : " + str(res)) #40 write a python program to find minimum k records from tuple list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing K K = 2 # printing original list print("The original list is : " + str(test_list)) # Minimum K records # Using sorted() + lambda res = sorted(test_list, key = lambda x: x[1])[:K] # printing result print("The lowest K records are : " + str(res)) #41 write a python program to check if one tuple is subset of other and print it test_tup1 = (10, 4, 5, 6) test_tup2 = (5, 10) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Check if one tuple is subset of other # using issubset() res = set(test_tup2).issubset(test_tup1) # printing result print("Is 2nd tuple subset of 1st ? : " + str(res)) #42 write a python program to display keys with same values in a dictionary List # initializing Matrix test_list = [{"Gfg": 5, "is": 8, "best": 0}, {"Gfg": 5, "is": 1, "best": 0}, {"Gfg": 5, "is": 0, "best": 0}] # getting keys keys = list(test_list[0].keys()) res = [] # iterating each dictionary for similar key's value for key in keys: flag = 1 for ele in test_list: # checking for similar values if test_list[0][key] != ele[key]: flag = 0 break if flag: res.append(key) # printing result print("Similar values keys : " + str(res)) #43 write a python program to filter dictionaries with ordered values test_list = [{'gfg': 2, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 4}] # sorted to check with ordered values # values() extracting dictionary values res = [sub for sub in test_list if sorted( list(sub.values())) == list(sub.values())] # printing result print("The filtered Dictionaries : " + str(res)) #44 write a python program to rotate dictionary by K # Python3 code to demonstrate working of # Rotate dictionary by K # Using list comprehension + items() + dictionary comprehension # initializing dictionary test_dict = {1: 6, 8: 1, 9: 3, 10: 8, 12: 6, 4: 9} # initializing K K = 2 # converting to tuples list test_dict = list(test_dict.items()) # performing rotate res = [test_dict[(i - K) % len(test_dict)] for i, x in enumerate(test_dict)] # reconverting to dictionary res = {sub[0]: sub[1] for sub in res} # printing result print("The required result : " + str(res)) #45 write a python program to Count if dictionary position equals key or value and print it test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} res = 0 test_dict = list(test_dict.items()) for idx in range(0, len(test_dict)): # checking for key or value equality if idx == test_dict[idx][0] or idx == test_dict[idx][1]: res += 1 # printing result print("The required frequency : " + str(res)) #46 write a python program to test if Values Sum is Greater than Keys Sum in dictionary and print it test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} res = sum(list(test_dict.keys())) < sum(list(test_dict.values())) # printing result print("The required result : " + str(res)) #47 write a program to sort Dictionary by key-value Summation and print it test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1} # sorted() to sort, lambda provides key-value addition res = sorted(test_dict.items(), key=lambda sub: sub[0] + sub[1]) # converting to dictionary res = {sub[0]: sub[1] for sub in res} # printing result print("The sorted result : " + str(res)) #48 write a program to divide dictionary and its keys into K equal dictionaries and print it test_dict = {"Gfg": 20, "is": 36, "best": 100} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing size K = 4 s=list(test_dict.keys()) print(s) q=list(test_dict.values()) t=[] for i in q: t.append(i//K) print(t) q=[] d={} for i in range(K): for i in range(0,len(s)): d[s[i]] = t[i] q.append(d) print(q) #49 Write a Python function to Sort a List of Dictionaries by the Sum of their Values and print it test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}] def func(test_list): return sum(list(test_list.values())) for i in test_list: test_list.sort(key=func) print(test_list) #50 write a python program to remove double quotes from dictionary keys and print it test_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9} # dictionary comprehension to make double quotes free # dictionary res = {key.replace('"', ''):val for key, val in test_dict.items()} # printing result print("The dictionary after removal of double quotes : " + str(res)) #51 write a python program to check whether the values of a dictionary are in same order as in a list test_dict = {"gfg" : 4, "is" : 10, "best" : 11, "for" : 19, "geeks" : 1} # initializing list sub_list = [4, 10, 11, 19, 1] l=list(test_dict.values()) if l == sub_list: print(True) else: print(False) #52 write a python program to update a dictionary with the values from a dictionary list and print it test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing dictionary list dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}] for i in dict_list: test_dict.update(i) print(test_dict) #53 write a python program that displays the key of list value with maximum range and print it test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]} max_res = 0 for sub, vals in test_dict.items(): # storing maximum of difference max_res = max(max_res, max(vals) - min(vals)) if max_res == max(vals) - min(vals): res = sub # printing result print("The maximum element key : " + str(res)) #54 write a pythom program to find Maximum value from dictionary whose key is present in the list test_dict = {"Gfg": 4, "is" : 5, "best" : 9, "for" : 11, "geeks" : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing list test_list = ["Gfg", "best", "geeks"] c=sorted(test_dict.values(),reverse=True) for key,value in test_dict.items(): if key in test_list and value in c[0:2]: print(key) #55 write a python program to extract N largest dictionaries keys and print it test_dict = {6 : 2, 8: 9, 3: 9, 10: 8} # initializing N N = 4 res = [] # write a python program to extract N largest dictionaries keys and print it for key, val in sorted(test_dict.items(), key = lambda x: x[0], reverse = True)[:N]: res.append(key) # printing result print("Top N keys are: " + str(res)) #56 write a python program to print a Dictionary Keys whose Values summation equals K test_dict = {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing K K = 14 l=[] s=list(test_dict.values()) v=list(test_dict.keys()) for i in range(0,len(s)): for j in range(i+1,len(s)-1): if s[i]+s[j] == K: #print((i,j)) print([v[i],v[j]]) #57 write a python program to add prefix to each key name in dictionary and print it test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # initializing prefix temp = "Pro" d={} for key,value in test_dict.items(): d.update({temp+key:value}) print(d) #58 write a python program to extract Kth index elements from Dictionary Value list and print it test_dict = {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing K K = 1 s=[] for key,value in test_dict.items(): s.append(value[K]) print(s) #59 write a python program to remove digits from Dictionary String Values List import re # initializing dictionary test_dict = {'Gfg' : ["G4G is Best 4", "4 ALL geeks"], 'is' : ["5 6 Good"], 'best' : ["Gfg Heaven", "for 7 CS"]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # using dictionary comprehension to go through all keys res = {key: [re.sub('\d', '', ele) for ele in val] for key, val in test_dict.items()} # printing result print("The filtered dictionary : " + str(res)) #60 write a program to Test for Even values dictionary values lists and print it test_dict = {"Gfg" : [6, 7, 3], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} res = dict() for sub in test_dict: flag = 1 # checking for even elements for ele in test_dict[sub]: if ele % 2 != 0: flag = 0 break # adding True if all Even elements res[sub] = True if flag else False # printing result print("The computed dictionary : " + str(res)) #61 write a program to sort Dictionary by Values and Keys and print it test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2, "for" : 3, "Geeks" : 2} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # - sign for descended values, omit if low-high sorting required res = {val[0] : val[1] for val in sorted(test_dict.items(), key = lambda x: (-x[1],x[0]))} # printing result print("Sorted dictionary : " + str(res)) #62 write a program to concatenate Ranged Values in String list and print it test_list = ["abGFGcs", "cdforef", "asalloi"] # initializing range i, j = 2, 5 r='' for z in test_list: r += z[i:j] print(r) #63 write a program to replace dictionary value from other dictionary and print it test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing updict updict = {"Gfg" : 10, "Best" : 17} d={} for key in test_dict.keys(): if key in updict: d.update({key:updict[key]}) else: d.update({key:test_dict[key]}) print(d) #64 write a program to convert string to dictionary and print it # Python implementation of converting # a string into a dictionary # initialising string str = " Jan = January; Feb = February; Mar = March" # generates key:value pair for each item dictionary = dict(subString.split("=") for subString in str.split(";")) # printing the generated dictionary print(dictionary) #65 write a python program to extract item with Maximum Tuple Value test_dict = {'gfg' : (4, 6), 'is' : (7, 8), 'best' : (8, 2)} # initializing tuple index # 0 based indexing tup_idx = 1 # Extract Item with Maximum Tuple Value # Using max() + lambda res = max(test_dict.items(), key = lambda ele: ele[1][tup_idx]) # printing result print("The extracted maximum element item : " + str(res)) #66 write a python program to Remove dictionary Key Words and print it test_str = 'gfg is best for geeks' # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {'geeks' : 1, 'best': 6} l=test_str.split() print(l) s='' for i in l: if i in test_dict: l.remove(i) print(" ".join(i for i in l)) #67 write a python program to group Strings on Kth character and print it test_list = ["gfg", "is", "best", "for", "geeks"] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 2 d={} for i in test_list: d.update({i[K-1]:[i]}) print(d) #68 write a python program to convert List of Dictionaries to List of Lists and print it test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20}, {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10}, {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}] s=[] count=0 for i in test_list: if count<1: s.append(list(i.keys())) s.append(list(i.values())) count+=1 print(s) #69 write a python program for printing custom order dictionary # initializing dictionary test_dict = {'is' : 2, 'for' : 4, 'gfg' : 1, 'best' : 3, 'geeks' : 5} # initializing order ord_list = ['gfg', 'is', 'best', 'for', 'geeks'] c={} for i in ord_list: if i in test_dict: c.update({i:test_dict[i]}) print(c) #70 write a python program to extract Numerical Dictionary values and print it test_dict = {"Gfg" : ["34", "45", 'geeks'], 'is' : ["875", None, "15"], 'best' : ["98", 'abc', '12k']} # printing original dictionary res = [] for a, b, c in zip(*test_dict.values()): if a.isdigit() : res.append((a, b, c)) # printing result print("The Numerical values : " + str(res)) #71 write a python program to count dictionaries in a list in Python and print it test_list = [10, {'gfg' : 1}, {'ide' : 2, 'code' : 3}, 20] # printing original list print("The original list is : " + str(test_list)) count=0 for i in test_list: if isinstance(i,dict): count=count+1 print(count) #72 write a python program to Filter and Double keys greater than K and print it test_dict = {'Gfg' : 4, 'is' : 2, 'best': 3, 'for' : 6, 'geeks' : 1} # printing original dictionary print("The original dictionary : " + str(test_dict)) d={} # initializing K K = 2 for keys,values in test_dict.items(): if values >K: d.update({keys:2*values}) else: d.update({keys:values}) print(d) #73 write a python program to Convert Frequency dictionary to list and print it test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5} # printing original dictionary print("The original dictionary : " + str(test_dict)) s=[] for key,value in test_dict.items(): for i in range(0,value): s.append(key) print(s) #74 write a python program to assign list items to Dictionary and print it test_list = [{'Gfg' : 1, 'id' : 2 }, {'Gfg' : 4, 'id' : 4 }] # initializing key new_key = 'best' # initializing list add_list = [12, 2] # Assign list items to Dictionary # Using zip() + loop res = [] for sub, val in zip(test_list, add_list): sub[new_key] = val res.append(sub) # printing result print("The modified dictionary : " + str(res)) #75 write a python program to test Boolean Value of Dictionary and print it test_dict = {'gfg' : True, 'is' : False, 'best' : True} # printing original dictionary print("The original dictionary is : " + str(test_dict)) res=True for key,value in test_dict.items(): if value==False: res=False break print(f"Dictionary is {res}") #76 write a python program to print Dictionary values String Length Summation test_dict = {'gfg' : '2345', 'is' : 'abcde', 'best' : 'qwerty'} # printing original dictionary print("The original dictionary is : " + str(test_dict)) list1=list(test_dict.values()) print(list1) s="".join(i for i in list1) print(f'Summation of string values is {len(s)}') #77 write a python program to printlist of Keys with shortest length lists in dictionary test_dict = {'gfg' : [4, 5], 'is' : [9, 7, 3, 10], 'best' : [11, 34], 'for' : [6, 8, 2], 'geeks' : [12, 24]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) s=[] a=0 q=[] for key,value in test_dict.items(): s.append(len(value)) q.append(key) l=[] print(s) print(q) for k,z in zip(q,s): if z==min(s): l.append(k) print(l) #78 write a python program to decrement Dictionary value by K test_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Initialize K K = 5 for key,value in test_dict.items(): test_dict.update({key:value-K}) print(test_dict) #79 write a python program to find Common items among dictionaries and print it test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3} test_dict2 = {'gfg' : 1, 'is' : 2, 'good' : 3} # printing original dictionaries print("The original dictionary 1 is : " + str(test_dict1)) print("The original dictionary 2 is : " + str(test_dict2)) count=0 for key1,value1 in test_dict1.items(): for key2,value2 in test_dict2.items(): if key1==key2 and value1==value2: count=count+1 print(count) #80 write a python program to print Nth largest values in dictionary #81 write a python program to print consecutive Kth column Difference in Tuple List # Consecutive Kth column Difference in Tuple List test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 1 s=[] for i in range(0,len(test_list)-1): s.append(abs(test_list[i][K]-test_list[i+1][K])) print(s) #82 write a python program to find Tuples with positive elements in List of tuples and print it test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original list print("The original list is : " + str(test_list)) #[all(i) for i in test_list if i>0] result = [i for i in test_list if all(ele >= 0 for ele in i)] # printing result print("Positive elements Tuples : " + str(result)) #83 write a python program to remove given character from first element of Tuple and print it test_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)] # printing original list print("The original list is : " + str(test_list)) # initializing K K = "!" # replace with empty string removes the desired char. res = [(sub[0].replace(K, ''), sub[1]) for sub in test_list] # printing result print("The filtered tuples : " + str(res)) #84 write a python program remove particular data type Elements from Tuple and print it test_tuple = (4, 5, 'Gfg', 7.7, 'Best') # printing original tuple print("The original tuple : " + str(test_tuple)) # initializing data type a=tuple() data_type = int for i in test_tuple: if not isinstance(i,data_type): a=a+(i,) print(list(a)) #85 write a python program to print rear element extraction from list of tuples records test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] # printing original list print ("The original list is : " + str(test_list)) s=[] for i in test_list: l=len(i) s.append(i[l-1]) print(s) #86 write a python program to raise elements of tuple as power to another tuple and print it test_tup1 = (10, 4, 5, 6) test_tup2 = (5, 6, 7, 5) s=tuple() # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) for i in range(0,len(test_tup1)): s+= (test_tup1[i] ** test_tup2[i],) print(s) #87 write a python program to Count the elements till first tuple and print it test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) count=0 for i in test_tup: if isinstance(i,tuple): break count=count+1 print(f'count of element till first tuple is {count}') #88 write a python program to print Dissimilar Elements in Tuples test_tup1 = (3, 4, 5, 6) test_tup2 = (5, 7, 4, 10) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) c=tuple() c=tuple(set(test_tup1) ^ set(test_tup2)) print(f'Dissimilar element tuple is {c}') #89 write a python program to flatten Tuples List to String and print it test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')] # printing original tuples list print("The original list : " + str(test_list)) s='' for i in test_list: for j in i: s+=' '+j+' ' print(f' string after flattening is {s}') #90 write a python program to filter tuples according to list element presence and print it test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)] s=[] # initialize target list tar_list = [6, 10] for i in test_list: for j in i: #print(j) if j in tar_list: #print(j) s.append(i) print(s) #91 write a python program to concatenate tuple and print it test_tup1 = (1, 3, 5) test_tup2 = (4, 6) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) c=test_tup1+test_tup2 print(c) #92 write a python program to sort list under tuples and print it test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) # printing original tuple print("The original tuple is : " + str(test_tup)) s=tuple(sorted([j for j in i],reverse=False ) for i in test_tup) print(f'the sorted list inside tuple is {s}') #93 write a python program for removing strings from tuple and printing it test_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] # printing original list print("The original list : " + str(test_list)) s=[] for i in test_list: t=tuple() for j in i: if not isinstance(j,str): t+=(j,) s.append(t) print(f'List after removing string from tuple is {s}') #94 write a program to remove matching tuples and print it test_list1 = [('Early', 'morning'), ('is','good'), ('for', 'Health')] test_list2 = [('Early', 'morning'), ('is','good')] l=[] for i in range(0,len(test_list1)): for j in range(0,len(test_list2)): if test_list1[i] not in test_list2: #continue l.append(test_list1[i]) break print(l) #95 write a program to Split tuple into groups of n and print it ini_tuple = (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) n=4 N=0 s=tuple() #t=tuple() for i in range(0,len(ini_tuple)//n): t=tuple() for j in range(N,N+n): #print(ini_tuple[j]) t+=(ini_tuple[j],) N=N+n s+=(t,) print(s) #96 write a python program to convert list of tuples into digits and print it lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)] a='' for i in lst: for j in i: a+=str(j) print(list(set(a))) #97 write a python program to Join tuple elements in a list and print it test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')] # printing original list print ("The original list is : " + str(test_list)) l=[] #s='' for i in test_list: s='' for j in i: s+=j+' ' l.append(s) print(l) #98 write a python program to count the elements in a list until an element is a Tuple and print it li = [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] count=0 for i in li: if isinstance(i,tuple): break count=count+1 print(f'count of element till tuple is encountered {count}') #99 write a python program to get maximum of each key Dictionary List and print it test_list = [{"Gfg": 8, "is": 1, "Best": 9}, {"Gfg": 2, "is": 9, "Best": 1}, {"Gfg": 5, "is": 10, "Best": 7}] # printing original list print("The original list is : " + str(test_list)) res = {} for i in test_list: for key, value in i.items(): # checking for key presence and updating max if key in res: res[key] = max(res[key], value) else: res[key] = value # printing result print("All keys maximum : " + str(res)) #100 write a python program to extract Keys with specific Value Type test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing type targ_type = int res = [] for key, val in test_dict.items(): # checking for values datatype if isinstance(val, targ_type): res.append(key) # printing result print("The extracted keys : " + str(res)) # Driver Code if __name__ == '__main__': string = "SchoolofAI" # Remove nth index element i = 5 # Print the new string print(remove(string, i)) # 1 # write a python function to remove last element in the list def remove_last_element_list(list1): list1.pop() return list1 # 2 # write a python function to find the add two numbers and then find the largest among sum and other two inputs def find_the_largest(num1, num2): sum_ = num1+num2 if num1 >= sum_ and num1 >= num2: return num1 elif num2 >= sum_ and num2 >= num1: return num2 else: return sum_ # 3 # write a function to calculate the area of polygon given the number of edges, circumradius import math def area_of_polygon(number_of_edges, circumradius): return number_of_edges * 2 * circumradius * math.sin(180/number_of_edges) * circumradius * math.cos(180/number_of_edges) * 0.5 # 4 # write a function to calculate the apothem of polygon given the number of edges, circumradius import math def apothem_of_polygon(number_of_edges, circumradius): return circumradius * math.cos(180/number_of_edges) # 5 # write a function which creates a deck of cards, given the list of suits and values def create_deck_of_cards(values: list, suits: list): card_deck = [] for i in range(52): tup = (values[i], suits[i]) card_deck.append(tup) return card_deck # 6 # write a function which converts temperature values, from Celsius(C) to Fahreinheit(F) and from Fahreinheit(F) to Celsius(C) \ # given the temperature value and its unit def temp_converter(value, unit): if unit =='F' and value in range(32, 212): converts = (value - 32) * 5.0/9.0 return converts elif unit =='C' and value in range(0,100): converts = (9.0/5.0) * value + 32 return converts else: raise ValueError # 7 # write a function which takes in a list and a number as an input and returns a list with each list element raised to power of that number def powered_list(a_list, a_number): a_list = [math.pow(a_number) for i in a_list] return a_list # 8 # write a function to execute a string containing Python code def execute_python_code(a_string): return exec(a_string) # 9 # write a function to multiply all the numbers in a list def multiply_all(a_list): product = 1 for i in a_list: product *= i return product # 10 # write a function to slice a tuple, given an input tuple and start, stop, step=1 def slice_a_tuple(a_tuple, start, stop, step=1): return a_tuple[start:stop:step] # 11 # write a function to check if a list is empty or not def list_is_empty(a_list): if not a_list: return True else: return False # 12 # Write a Python function to convert a string list to a normal list type import ast def convert_string_to_list(str_lst): return ast.literal_eval(str_lst) # 13 # Write a Python function to extend a list without append. def extend_list_without_append(list1, list2): return list1.extend(list2) # 14 # Write a Python function to find the median among three given numbers def find_the_median(x,y,z): list_ = sorted([x,y,z]) return list_[1] # 15 # Write a python function to remove a newline in Python def remove_newline(string): return string.strip() # 16 # Write a python function to convert a string to a list def convert_str_to_list(string): return string.split(' ') # 17 # Write a python function to remove spaces from a given string def remove_spaces_from_string(string): return string.replace(' ', '') # 18 # Write a python function to capitalize first and last letters of each word of a given string capitalize_both_ends = lambda x: x[0].upper() + x[1:-1] + x[-1].upper() def capitalize_first_and_last(string): string = string.strip().split() new_string = [capitalize_both_ends(word) for word in string] return new_string # 19 # Write a python function to remove duplicate words from a given string def remove_duplicate_words(string): string = string.strip().split() return ' '.join(set(string)) # 20 # Write a python function to calculate number of days between two dates using datetime module from datetime import date def day_diff(date1, date2): diff = date1 - date2 return diff.days # 21 # Write a python function to get the volume of a sphere with radius as input def sphere_volume(radius): volume = 4.0/3.0 * 3.14 * radius ** 3 return volume # 22 # Write a Python function to check whether the input letter is a vowel or not def check_vowel_or_not(letter): result = str(letter) in "aeiou" return result # 23 # Write a Python function to get OS name & platform using os & platform library import os import platform def get_info(): return f'OS: {os.name}\n Platform: {platform.system}' # 24 # Write a Python program to print out the number of CPUs working behind the scenes using multiprocessing library import multiprocessing print(multiprocessing.cpu_count()) # 25 # Write a Python program to calculate the hypotenuse of a right angled triangle using math library from math import sqrt print("Input lengths of shorter triangle sides:") def hypotenuse(side1, side2): hyp = sqrt(side1**2 + side2**2) return hyp # 26 # Write a Python function to convert height (in feet and inches) to centimeters def height_converter(h_ft, h_inch): h_inch += h_ft * 12 h_cm = round(h_inch * 2.54, 1) return h_cm # 27 # Write a Python function to convert the distance (in feet) to inches, yards, and miles. def distance_converter(d_ft): d_inches = d_ft * 12 d_yards = d_ft / 3.0 d_miles = d_ft / 5280.0 return f"Distance in Inches:{d_inches}\nDistance in Yards :{d_yards}\nDistance in Miles :{d_miles}" # 28 # Write a Python program to get the copyright information using sys module import sys print("\nPython Copyright Information") print(sys.copyright) print() # 29 # Write a Python program to find the available built-in modules using sys and textwrap modules import sys import textwrap module_name = ', '.join(sorted(sys.builtin_module_names)) print(textwrap.fill(module_name, width=70)) # 30 # Write a Python program to get the current username using getpass library import getpass print(getpass.getuser()) # 31 # Write a Python program to accept a filename from the user and print the extension of that def filename_extension(file): f_extns = file.split(".") return f"The extension of the file is :{repr(f_extns[-1])}" # 32 # Write a Python function that calculates the area of parallelogram and takes in base, height as input def area_shape(base, height, shape): return {'triangle': 0.5*base*height, 'parallelogram': base*height}[shape] # 33 # Write a Python function to reverse a string if it's length is a multiple of 4. def reverse_string(str1): if len(str1) % 4 == 0: return ''.join(reversed(str1)) return str1 # 34 # Write a Python function to reverse words in a string. def reverse_string_words(text): for line in text.split('\n'): return(' '.join(line.split()[::-1])) # 35 # Write a Python program to count and display the vowels of a given text. def vowel(text): vowels = "aeiuoAEIOU" main_list = [letter for letter in text if letter in vowels] return len(main_list), main_list # 36 # Write a Python program to find the first repeated character in a given string def first_repeated_char(str1): for index,c in enumerate(str1): if str1[:index+1].count(c) > 1: return c return "None" # 37 # Write a Python program to find the first repeated word in a given string. def first_repeated_word(str1): temp = set() for word in str1.split(): if word in temp: return word else: temp.add(word) return 'None' # 38 # Write a Python program to remove spaces from a given string def remove_spaces(str1): str1 = str1.replace(' ','') return str1 # 39 # Write a Python program to remove spaces from a given string using set def remove_duplicate(str1): list_str = str1.split() return "".join(set(list_str)) # 40 # Write a Python function that will accept the base and height of a triangle and compute the area. def triangle_area(base, height): area = base*height/2 return area # 41 # Write a Python function to create all possible permutations from a given collection of distinct numbers. def permute(nums): result_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) result_perms = new_perms return result_perms # 42 # Write a Python program to print the calendar of a given month and year import calendar y = int(input("Input the year : ")) m = int(input("Input the month : ")) print(calendar.month(y, m)) # 43 # Write a python function to get the volume of a cube with side as input def cube_volume(side): volume = side ** 3 return volume # 44 # Write a python function to get the volume of a prism with base area & height as input def prism_volume(base_area, height): volume = base_area * height return volume # 45 # Write a python function to get the volume of a cylinder with radius & height as input def cylinder_volume(radius, height): volume = 3.14 * (radius ** 2) * height return volume # 46 # Write a python function to get the volume of a cone with radius & vertical height as input def cone_volume(radius, height): volume = 1/3 * 3.14 * (radius ** 2) * height return volume # 47 # Write a python function to get the volume of a pyramid with base area & vertical height as input def pyramid_volume(base_area, height): volume = 1/3 * base_area * height return volume # 48 # Write a python function to get the surface area of a cube with side as input def cube_surface_area(side): surface_area = 6 * side ** 2 return surface_area # 49 # Write a python function to get the volume of a rectangular prism with side as length, width and height as input def rec_prism_volume(length, width, height): volume = length * width * height return volume # 50 # Write a python function to get the surface_area of a rectangular prism with side as length, width and height as input def rec_prism_surface_area(length, width, height): surface_area = 2*((length * width) + (width * height) + (height * length)) return surface_area # 51 # Write a python function to get the surface_area of a prism with base area, base perimeter & height as input def prism_surface_area(base_area, base_perimeter, height): surface_area = 2*base_area + (base_perimeter*height) return surface_area # 52 # Write a python function to get the surface_area of a cylinder with radius & height as input def cylinder_surface_area(radius, height): surface_area = 3.14 * (radius ** 2) + (2 * 3.14 * radius * height) return surface_area # 53 # Write a python function to get the surface_area of a cone with radius & slant height as input def cone_surface_area(radius, slant_height): surface_area = 3.14 * (radius ** 2) + 3.14 * radius * slant_height return surface_area # 54 # Write a python function to get the surface_area of a pyramid with base area & vertical height as input def pyramid_surface_area(base_area, height): surface_area = 1/3 * base_area * height return surface_area # 55 # Write a python function to get the volume of a cuboid with length, breadth & height as input def cuboid_volume(length, breadth, height): volume = length * breadth * height return volume # 56 # Write a python function to break a list into chunks of size N use generator my_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] # Yield successive n-sized # chunks from l. def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n] # 57 # Write a python function to generate Lucas Numbers (2, 1, 3, 4, 7, 11, 18...) def lucas_numbers(n): first, second = 2,1 for _ in range(n): first, second = second, first+second return first # 58 # Write a python function to generate Square Numbers (1, 4, 9, 16, 25...) def square_numbers(n): for i in range(n): yield i ** 2 # 59 # Write a python function to generate Cube Numbers (1, 8, 27, 64, 125...) def cube_numbers(n): for i in range(n): yield i ** 3 # 60 # Write a python function to generate Triangular Number Series (1, 3, 6, 10, 15...) def triangle_numbers(n): for i in range(n): yield int(i*(i+1)/2) # 61 # Write a python function to generate Euclid Number Series(2, 3, 7, 31, 211, 2311, 30031) from math import sqrt from itertools import count, islice def is_prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1))) def euclid_numbers(n): product = 1 if n > 3: for i in range(n): if is_prime(i): product = product * i yield product # 61 # Write a Python program to add a prefix text to all of the lines in a string. import textwrap sample_text =''' Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. ''' text_without_Indentation = textwrap.dedent(sample_text) wrapped = textwrap.fill(text_without_Indentation, width=50) #wrapped += '\n\nSecond paragraph after a blank line.' final_result = textwrap.indent(wrapped, '> ') # 62 # Write a Python program to print the following floating numbers with no decimal places. x = 3.1415926 y = -12.9999 print("\nOriginal Number: ", x) print("Formatted Number with no decimal places: "+"{:.0f}".format(x)) print("Original Number: ", y) print("Formatted Number with no decimal places: "+"{:.0f}".format(y)) # 63 # Write a Python program to append a list to the second list. list1 = [1, 2, 3, 0] list2 = ['Red', 'Green', 'Black'] final_list = list1 + list2 print(final_list) # 64 # Write a Python program to create the colon of a tuple. from copy import deepcopy #create a tuple tuplex = ("HELLO", 5, [], True) print(tuplex) #make a copy of a tuple using deepcopy() function tuplex_colon = deepcopy(tuplex) tuplex_colon[2].append(50) #65 # Write a Python program to find the repeated items of a tuple. tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 print(tuplex) #return the number of times it appears in the tuple. count = tuplex.count(4) print(count) # 66 # Write a Python program to slice a tuple #create a tuple tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1) #used tuple[start:stop] the start index is inclusive and the stop index _slice = tuplex[3:5] # 67 # Write a Python program to reverse a tuple. #create a tuple x = ("w3resource") # Reversed the tuple y = reversed(x) # 68 # Write a Python program to convert a list of tuples into a dictionary. #create a list l = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)] d = {} for a, b in l: d.setdefault(a, []).append(b) print (d) # 69 # Write a Python program to check whether an element exists within a tuple. tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e") print("e" in tuplex) # 70 # Write a Python function to convert a list to a tuple. def convert_list_to_tuple(list_input): return tuple(list_input) # 71 # Write a Python function to unzip a list of tuples into individual lists def unzip_list_of_tuples(list_tuple): return list(zip(*l)) # 72 # Write a Python program to convert a list of tuples into a dictionary. l = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)] d = {} for a, b in l: d.setdefault(a, []).append(b) print(d) # 73 # Write a Python function to clear a set. def clear_set(set_input): setp_copy = set_input.copy() setp_copy.clear() return setp_copy # 74 # Write a Python function that returns the ASCII value of the passed in character. def ascii_value_of_character(char): return ord(char) # 75 # Write a Python function to create a union of sets. #Union def union_of_sets(Set1, Set2): result = Set1 | Set2 return result # 76 # Write a Python program to add member in a set #A new empty set color_set = set() color_set.add("Red") print(color_set) # 77 # Write a Python function to add two given lists using map and lambda. def add_two_lists(list_1, list_2): result = map(lambda x, y: x + y, list_1, list_2) return result # 78 # Write a Python function to find numbers within a given range where every number is divisible by every digit it contains. def divisible_by_digits(start_num, end_num): return [n for n in range(start_num, end_num+1) \ if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))] # 79 # Write a Python function to find the maximum value in a given heterogeneous list using lambda def max_val(list_val): max_val = max(list_val, key = lambda i: (isinstance(i, int), i)) return(max_val) # 80 # Write a Python function that takes a string and returns the concatenated first and last character def first_last(name): return name[0] + name[-1] # 81 # Write a Python function to return Syslvester's Sequence # a(n) = a(n-1)**2 + a(n-1) + 1 def syslvester_seq(n): if n == 1: return 2 if n > 1: return syslvester_seq(n-1)**2 - syslvester_seq(n-1) + 1 # 82 # Write a Python function to return Tribonacci's Sequence # T(n) = T(n āˆ’ 1) + T(n āˆ’ 2) + T(n āˆ’ 3) for n ā‰„ 3 [T(0) = 0, T(1) = 1, T(2) = 1] def tribonacci_seq(n): if n >= 0: if n == 0: return 0 elif n == 1: return 1 elif n == 2 : return 1 else: return tribonacci_seq(n-1) + tribonacci_seq(n-2) + tribonacci_seq(n-3) # 83 # Write a Python function to return Pell's Sequence # a(n) = 2a(n āˆ’ 1) + a(n āˆ’ 2) for n ā‰„ 2, with a(0) = 0, a(1) = 1. def pell_seq(n): if n >= 0: if n == 0: return 0 elif n == 1: return 1 else: return 2 * pell_seq(n-1) + pell_seq(n-2) # 84 # Write a Python function to return Fermat's Sequence # Fn = 2 ** 2n + 1 for n ā‰„ 0. def fermat_seq(n): if n >= 0: return 2 ** (2**n) + 1 # 85 # Write a Python function to return Padovan's Sequence # P(n) = P(n āˆ’ 2) + P(n āˆ’ 3) for n ā‰„ 3, with P(0) = P(1) = P(2) = 1. def padovan_seq(n): if n >= 0: if n in {0,1,2}: return 1 else: return padovan_seq(n-3) + padovan_seq(n-2) # 86 # Write a Python function to return Jacobsthal's number # a(n) = a(n āˆ’ 1) + 2a(n āˆ’ 2) for n ā‰„ 2, with a(0) = 0, a(1) = 1. def jacobsthal_seq(n): if n >= 0: if n == 0: return 0 elif n == 1: return 1 else: return 2 * jacobsthal_seq(n-2) + jacobsthal_seq(n-1) # 87 # Write a Python function to return perrin's number # P(n) = P(nāˆ’2) + P(nāˆ’3) for n ā‰„ 3, with P(0) = 3, P(1) = 0, P(2) = 2. def perrins_number(n): if n >= 0: if n == 0: return 3 elif n == 1: return 0 elif n == 2: return 2 else: return perrins_number(n-3) + perrins_number(n-2) # 88 # Write a Python function to return cullen number # Cn = nā‹…2n + 1, with n ā‰„ 0. def cullen_number(n): if n >= 0: return n * 2 ** n + 1 # 89 # Write a Python function to return woodall numbers # nā‹…2n āˆ’ 1, with n ā‰„ 1. def woodall_number(n): if n >= 0: return n * 2 ** n - 1 # 90 # Write a Python function to return carol numbers # (2n āˆ’ 1)**2 - 2, with n ā‰„ 1. def carol_number(n): if n >= 0: return (2**n - 1)**2 - 2 # 91 # Write a Python function to return star numbers # The nth star number is Sn = 6n(n āˆ’ 1) + 1. def star_number(n): return 6*n*(n-1)+1 # 92 # Write a Python function to return stella octangula numbers # Stella octangula numbers: n (2n2 āˆ’ 1), with n ā‰„ 0. def stella_octangula_number(n): if n >= 0: return n*(2**n - 1) # 93 # Write a Python function to convert Hours into Seconds def hours_to_seconds(hours): return hours * 60 * 60 # 94 # Write a Python function which returns the Modulo of the two given numbers. def mod(m, n): return m % n # 95 # Write a Python function that finds the maximum range of a triangle's third edge, where the side lengths are all integers. def next_edge(side1, side2): return (side1+side2-1) # 96 # Write a Python function that takes a list and returns the difference between the biggest and smallest numbers. def difference_max_min(lst): return abs(min(lst) - max(lst)) # 97 # Write a Python function that returns the number of frames shown in a given number of minutes for a certain FPS. def number_of_frames(minutes, fps): return (minutes * 60) * fps # 98 # Write a Python function that returns True if a string is empty and False otherwise. def is_empty(s): if s == "": return True else: return False # 99 # Write a Python function that accepts a measurement value in inches and returns the equivalent in feet def inches_to_feet(inches): if inches < 12: return 0 return inches/12 # 100 # Write a Python function that takes the age and return the age in days. def calc_age(age): calculation = age*365 return calculation # write a Python function to remove empty tuples from a list of tuples function to remove empty tuples using filter def Remove(tuples): tuples = filter(None, tuples) return tuples tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()] print(Remove(tuples)) # write a Python function to count the number of occurrences in list def countX(lst, x): return lst.count(x) lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print('{} has occurred {} times'.format(x, countX(lst, x))) # write a Python function to clone or copy a list using the in-built function list() def Cloning(li1): li_copy = list(li1) return li_copy li1 = [4, 8, 2, 10, 15, 18] li2 = Cloning(li1) print("Original List:", li1) print("After Cloning:", li2) # write a Python program to print odd Numbers in a List list1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print("Odd numbers in the list: ",only_odd) # write a Python program to print even Numbers in a List list1 = [10, 21, 4, 45, 66, 93] even_nos = [num for num in list1 if num % 2 == 0] print("Even numbers in the list: ", even_nos) # write a Python program to find N largest element from given list of integers l = [1000,298,3579,100,200,-45,900] n = 4 l.sort() print(l[-n:]) # write a Python program to find the second largest number in given list. list1 = [10, 20, 4, 45, 99] list1.sort() print("Second largest element is:", list1[-2]) # write a python function to swap first and last element of a list def swapList(newList): newList[0], newList[-1] = newList[-1], newList[0] return newList newList = [12, 35, 9, 56, 24] print(swapList(newList)) # write a python function to find simple interest for given principal amount, time and rate of interest. def simple_interest(p,t,r): print('The principal is', p) print('The time period is', t) print('The rate of interest is',r) si = (p * t * r)/100 print('The Simple Interest is', si) return si simple_interest(8, 6, 8) # write a python function for implementation of Insertion Sort def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key arr = [12, 11, 13, 5, 6] insertionSort(arr) print (f"Sorted array is: {arr}") # write a python function for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print (f"Sorted array {arr}") # write a python program for implementation of selection sort of list A = [64, 25, 12, 22, 11] for i in range(len(A)): min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j A[i], A[min_idx] = A[min_idx], A[i] print (f"Sorted array {A}") # write a python program for adding two binary numbers num1 = '00001' num2 = '10001' sum = bin(int(num1,2) + int(num2,2)) print(sum) # write a python program to count the number of each vowels vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' ip_str = ip_str.casefold() count = {}.fromkeys(vowels,0) for char in ip_str: if char in count: count[char] += 1 print(count) # write a python program to print two sets union using operations like in mathematic E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; print("Union of E and N is",E | N) # write a python program to print two sets intersection using operations like in mathematic E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; print("Intersection of E and N is",E & N) # write a python program to print two sets differences using operations like in mathematic E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; print("Difference of E and N is",E - N) # write a python program to print two sets symmetric differences using operations like in mathematic E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; print("Symmetric difference of E and N is",E ^ N) # write a python program to sort alphabetically the words form a string provided by the user my_str = "Hello this Is an Example With cased letters" words = [word.lower() for word in my_str.split()] words.sort() print("The sorted words are:") for word in words: print(word) # write a python program to remove punctuations from a string punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) # write a python program to check if a string is palindrome or not my_str = 'aIbohPhoBiA' my_str = my_str.casefold() rev_str = reversed(my_str) if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") # write a python program to transpose a matrix using a nested loop X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) # write a python function to find the factors of a number def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) num = 63 print_factors(num) # write a python function to find the L.C.M. of two input number def compute_lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) # write a python function to find H.C.F of two numbers def compute_hcf(x, y): if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 print("The H.C.F. is", compute_hcf(num1, num2)) # write a python program to print anonymous function to find all the numbers divisible by 13 in the list. my_list = [12, 65, 54, 39, 102, 339, 221,] result = list(filter(lambda x: (x % 13 == 0), my_list)) print("Numbers divisible by 13 are",result) # write a python program to print display the powers of 2 using anonymous function terms = 10 result = list(map(lambda x: 2 ** x, range(terms))) for i in range(terms): print("2 raised to power",i,"is",result[i]) # write a python program to print sum of natural numbers up to num num = 16 if num < 0: print("Enter a positive number") else: sum = 0 while(num > 0): sum += num num -= 1 print("The sum is", sum) # write a python program to print Armstrong numbers in a certain interval lower = 100 upper = 2000 for num in range(lower, upper + 1): order = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) # write a python program to check if the number is an Armstrong number or not num = 663 sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") # write a python program to print all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # write a python program to check if a number is prime or not num = 407 if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") # write a python program to convert paragraph string into sentense case a = 'hello. i am a sentence.' a = '. '.join(i.capitalize() for i in a.split('. ')) print(a) # write a python program to convert raw string integer inputs to integers str_input = "1 2 3 4 5 6" int_input = map(int, str_input.split()) print(list(int_input)) # write a python program to find index of min element lst = [40, 10, 20, 30] def minIndex(lst): return min(range(len(lst)), key=lst.__getitem__) print(minIndex(lst)) # write a python program to find index of max element lst = [40, 10, 20, 30] def maxIndex(lst): return max(range(len(lst)), key=lst.__getitem__) print(maxIndex(lst)) # write a python program to use maxsplit with arbitrary whitespace s = "foo bar foobar foo" print(s.split(None, 2)) # write a python program to loop over dictionaries that share (some) keys dctA = {'a': 1, 'b': 2, 'c': 3} dctB = {'b': 4, 'c': 3, 'd': 6} for ky in dctA.keys() & dctB.keys(): print(ky) # write a python program to loop over dictionaries that share (some) keys and values dctA = {'a': 1, 'b': 2, 'c': 3} dctB = {'b': 4, 'c': 3, 'd': 6} for item in dctA.items() & dctB.items(): print(item) # write a python program to converts list of mix data to comma separated string data = [2, 'hello', 3, 3.4] print (','.join(map(str, data))) # write a python program to deep flattens a nested list L = [1, 2, [3, 4], [5, 6, [7]]] def flatten(L): for item in L: if isinstance(item, list): yield from flatten(item) else: yield item print(list(flatten(L))) # write a python program to swaps keys and values in a dict _dict = {"one": 1, "two": 2} # make sure all of dict's values are unique assert len(_dict) == len(set(_dict.values())) reversed_dict = {v: k for k, v in _dict.items()} print(reversed_dict) # write a python program to add whitespaces both sides of a string s = 'The Little Price' width = 20 s3 = s.center(width) print(s3) # write a python program to sort a dictionary by its values and print the sorted dictionary with 'key' argument. d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1} print(sorted(d.items(), key=lambda x: x[1])) # write a python program to sort dict keys by value and print the keys d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1} print(sorted(d, key=d.get)) # write a python program to call different functions based on condition with same arguments def product(a, b): return a * b def subtract(a, b): return a - b b = True print((product if b else subtract)(1, 1)) # write a python program to do chained comparison a = 10 print(1 < a < 50) print(10 == a < 20) # write a python program to define a decorator to cache property class PropertyCache(object): """ a decorator to cache property """ def __init__(self, func): self.func = func def __get__(self, obj, cls): if not obj: return self value = self.func(obj) setattr(obj, self.func.__name__, value) return value class Foo: def __init__(self): self._property_to_be_cached = 'result' @PropertyCache def property_to_be_cached(self): print('compute') return self._property_to_be_cached test = Foo() print(test.property_to_be_cached) print(test.property_to_be_cached) # write a python program to merge two dictionary x = {'a': 1, 'b' : 2} y = {'c': 3, 'd' : 4} z = {**x, **y} print(z) # write a Python program to get the Cumulative sum of a list list1=[10,20,30,40,50] new_list=[] j=0 for i in range(0,len(list1)): j+=list1[i] new_list.append(j) print(new_list) # write a Python program to Break a list into chunks of size N in Python l = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 4 x = [l[i:i + n] for i in range(0, len(l), n)] print(x) # write a Python function to check Check if a Substring is Present in a Given String def check(string, sub_str): if (string.find(sub_str) == -1): print("NO") else: print("YES") string = "geeks for geeks" sub_str ="geek" check(string, sub_str) # write a Python program to demonstrate working of Words Frequency in String Shorthands test_str = 'Gfg is best . Geeks are good and Geeks like Gfg' print("The original string is : " + str(test_str)) res = {key: test_str.count(key) for key in test_str.split()} print("The words frequency : " + str(res)) # write a Python program to demonstrate working of Convert Snake case to Pascal case test_str = 'geeksforgeeks_is_best' print("The original string is : " + test_str) res = test_str.replace("_", " ").title().replace(" ", "") print("The String after changing case : " + str(res)) # write a Python function to print even length words in a string def printWords(s): s = s.split(' ') for word in s: if len(word)%2==0: print(word) s = "i am muskan" printWords(s) # write a Python function to Remove all duplicates from a given string def removeDuplicate(str): s=set(str) s="".join(s) print("Without Order:",s) t="" for i in str: if(i in t): pass else: t=t+i print("With Order:",t) str1="geeksforgeeks" removeDuplicate(str1) # write a Python program to find Least Frequent Character in String test_str = "GeeksforGeeks" print ("The original string is : " + test_str) all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print ("The minimum of all characters in GeeksforGeeks is : " + res) # write a Python program to find Maximum Frequent Character in String test_str = "GeeksforGeeks" print ("The original string is : " + test_str) all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = max(all_freq, key = all_freq.get) print ("The maximum of all characters in GeeksforGeeks is : " + res) # write a Python function to find all string which are greater than given length k def string_k(k, str): string = [] text = str.split(" ") for x in text: if len(x) > k: string.append(x) return string k = 3 str1 ="geek for geeks" print(string_k(k, str1)) # write a Python function to check if a string is binary or not def check2(string) : t = '01' count = 0 for char in string : if char not in t : count = 1 break else : pass if count : print("No, string is not binary") else : print("Yes, string is binary") string = "001021010001010" check2(string) # write a Python program to find a list of uncommon words def UncommonWords(A, B): count = {} for word in A.split(): count[word] = count.get(word, 0) + 1 for word in B.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] == 1] A = "Geeks for Geeks" B = "Learning from Geeks for Geeks" print(UncommonWords(A, B)) # write a Python program to demonstrate working of Replace duplicate Occurrence in String test_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . ' print("The original string is : " + test_str) repl_dict = {'Gfg' : 'It', 'Classes' : 'They' } test_list = test_str.split(' ') res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and test_list.index(val) != idx else val for idx, val in enumerate(test_list)]) print("The string after replacing : " + res) # write a Python Function to rotate string left and right by d length def rotate(input,d): Lfirst = input[0 : d] Lsecond = input[d :] Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] print ("Left Rotation : ", (Lsecond + Lfirst) ) print ("Right Rotation : ", (Rsecond + Rfirst)) input = 'GeeksforGeeks' d=4 rotate(input,d) # write a Python program to demonstrate working of Swap Binary substring test_str = "geeksforgeeks" print("The original string is : " + test_str) temp = str.maketrans("geek", "abcd") test_str = test_str.translate(temp) print("The string after swap : " + test_str) # write a Python program to demonstrate working of Extract Unique values dictionary values test_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} print(f"The original dictionary is : {test_dict}") res = sorted({ele for val in test_dict.values() for ele in val}) print(f"The unique values list is : {res}") # write a Python function to find sum of all items in a Dictionary def returnSum(dict): sum = 0 for i in dict.values(): sum = sum + i return sum dict = {'a': 100, 'b':200, 'c':300} print("Sum :", returnSum(dict)) # write a Python program to demonstrate removal of dictionary pair test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21} print (f"The dictionary before performing remove is : {test_dict}") del test_dict['Mani'] print (f"The dictionary after remove is : {test_dict}") # write a Python program for Handling missing keys in dictionaries country_code = {'India' : '0091', 'Australia' : '0025', 'Nepal' : '00977'} print(country_code.get('India', 'Not Found')) print(country_code.get('Japan', 'Not Found')) # write a Python program to reverse a linked list class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(85) print("Given Linked List") llist.printList() llist.reverse() print("\nReversed Linked List") llist.printList() # write a Python Recursive function to solve the tower of hanoi def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print("Move disk 1 from source",source,"to destination",destination) return TowerOfHanoi(n-1, source, auxiliary, destination) print("Move disk",n,"from source",source,"to destination",destination) TowerOfHanoi(n-1, auxiliary, destination, source) n = 4 TowerOfHanoi(n,'A','B','C') # write a Python function to find time for a given angle. def calcAngle(hh, mm): hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm angle = abs(hour_angle - minute_angle) angle = min(360 - angle, angle) return angle def printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm)==theta): print(hh, ":", mm, sep = "") return print("Input angle not valid.") return theta = 90.0 printTime(theta) # write a Python program to find the minute at which the minute hand and hour hand coincide def find_time(h1): theta = 30 * h1 print("(", end = "") print((theta * 2),"/ 11) minutes") h1 = 3 find_time(h1) # write a Python function to convert number to english def num_to_eng(n): if n == 0: return 'zero' unit = ('','one','two','three','four','five','six','seven','eight','nine') tens = ('','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety') teen = ('ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen') h, t, u = '', '', '' if n//100: h = unit[n//100] + ' hundred' n = n%100 if n >= 20: t = tens[n//10] n = n%10 elif n >= 10: t = teen[n-10] n = 0 u = unit[n] return ' '.join(filter(None,[h,t,u])) print(num_to_eng(115)) # write a Python function to convert Fraction to Mixed Number def reduce_frac(n, d): for i in range(min(n, d), 0, -1): if not n%i and not d%i: return '{}/{}'.format(n//i, d//i) def mixed_number(frac): n, d = map(int, frac.lstrip('-').split('/')) sign = '-' if frac.startswith('-') else '' if not n%d: return sign + str(n//d) n, r = divmod(n, d) return sign + '{} {}'.format(n, reduce_frac(r, d)).lstrip('0 ') print(mixed_number("5/4")) # write a Python function to print First n Digits of Pi def pi(n): i = 1 p = x = 3 * 10 ** (n + 10) while x: x = x * i // ((i + 1) * 4) i += 2 p += x // i return '3.' + f"{p // 10 ** 10}"[1:] print(pi(7)) # write a Python function to Non-Repeating Integers def non_repeats(radix): count = 0 for num_digits in range(1, radix + 1): product = radix - 1 for i in range(1, num_digits): product *= (radix - i) count += product return count print(non_repeats(6)) # write a Python function that returns the determinant of a given square matrix def determinant(A): if len(A) == 1: return A[0][0] elif len(A) == 2: return A[0][0]*A[1][1] - A[0][1]*A[1][0] else: s = 0 for i in range(len(A)): B = [[A[row][col] for col in range(1,len(A))] for row in range(len(A)) if row!=i ] s += ((-1)**i)*A[i][0]*determinant(B) return s print(determinant([[3, 0], [2, 2]])) # write a Python function that finds a root of a polynomial curve using the Newton-Raphson method. def newton_raphson(c, x=0): for _ in range(20): polynomial = c[0]*x**3 + c[1]*x**2 + c[2]*x + c[3] derivative = 3*c[0]*x**2 + 2*c[1]*x + c[2] x -= polynomial/derivative return round(x, 3) print(newton_raphson([-0.1, 0.4, 0.1, -0.8])) # write a Python function to find area of an Ellipse. def findArea(a, b): Area = 3.142 * a * b ; print("Area:", round(Area, 2)); a = 5; b = 4; findArea(a, b) # write a Python function to find the area of the triangle inscribed within the rectangle which in turn is inscribed in an ellipse def area(a, b): if (a < 0 or b < 0): return -1 A = a * b return A a = 5 b = 2 print(area(a, b)) # write a Python function To Calculate Volume OF Cylinder pi = 22/7 def volume(r, h): vol = pi * r * r * h return vol r = 5 h = 8 print("Volume Of Cylinder = ",volume(r, h)) # write a Python function To Calculate Total Surface Area of Cylinder def totalsurfacearea(r, h): tsurf_ar = (2 * pi * r * h) + (2 * pi * r * r) return tsurf_ar r = 5 h = 8 print("Total Surface Area Of Cylinder = ",totalsurfacearea(r,h)) # write a Python function to Calculate Curved Surface Area of Cylinder def curvedsurfacearea(r, h): cursurf_ar = (2 * pi * r * h) return cursurf_ar r = 5 h = 8 print("Curved Surface Area Of Cylinder = ",curvedsurfacearea(r,h)) # write a Python function to find the Area of Icosahedron def findArea(a): area = 5 * 3 ** 0.5 * a * a return area a = 5 print("Area: " , findArea(a)) # write a Python function to find the volume of Icosahedron def findVolume(a): volume = ((5 / 12) * (3 + 5 ** 0.5) * a * a * a) return volume a = 5 print("Volume: " , findVolume(a)) # write a Python function to find surface area of the Pentagonal Prism def surfaceArea(a, b, h): return 5 * a * b + 5 * b * h a = 5 b = 3 h = 7 print("surface area =", surfaceArea(a, b, h)) # write a Python function to find volume of the Pentagonal Prism def volume(b, h): return (5 * b * h) / 2 a = 5 b = 3 h = 7 print("volume =", volume(b, h)) # write a Python function to return the volume of the rectangular right wedge def volumeRec(a, b, e, h) : return (((b * h) / 6) * (2 * a + e)) a = 2; b = 5; e = 5; h = 6; print("Volume = ",volumeRec(a, b, e, h)) # write a Python program to calculate volume of Torus r = 3 R = 7 pi = 3.14159 Volume = (float)(2 * pi * pi * R * r * r) print("Volume: ", Volume) # write a Python program to calculate surface area of Torus r = 3 R = 7 Surface = (float)(4 * pi * pi * R * r) print("Surface: ", Surface) # write a Python program to demonstrate to convert list of string to list of list test_list = [ '[1, 4, 5]', '[4, 6, 8]' ] print (f"The original list is : {test_list}") res = [i.strip("[]").split(", ") for i in test_list] print (f"The list after conversion is : {res}") # write a Python program to demonstrate working of Convert String to tuple list test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)" print("The original string is : " + test_str) res = [] temp = [] for token in test_str.split(", "): num = int(token.replace("(", "").replace(")", "")) temp.append(num) if ")" in token: res.append(tuple(temp)) temp = [] print(f"List after conversion from string : {res}") # write a Python program to demonstrate working of Convert List to Single valued Lists in Tuple test_list = [6, 8, 4, 9, 10, 2] print(f"The original list is : {test_list}") res = tuple([ele] for ele in test_list) print(f"Tuple after conversion : {res}") # write Python program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character string_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' words = string_input.split() dictionary = {} for word in words: if (word[0].lower() not in dictionary.keys()): dictionary[word[0].lower()] = [] dictionary[word[0].lower()].append(word) else: if (word not in dictionary[word[0].lower()]): dictionary[word[0].lower()].append(word) print(dictionary) # write Python program to find key with Maximum value in Dictionary Tv = {'BreakingBad':100, 'GameOfThrones':1292, 'TMKUC' : 88} Keymax = max(Tv, key=Tv.get) print(Keymax) # write Python program to demonstrate working of Get next key in Dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} print(f"The original dictionary is : {test_dict}") test_key = 'is' temp = list(test_dict) try: res = temp[temp.index(test_key) + 1] except (ValueError, IndexError): res = None print(f"The next key is : {res}") # write Python program to demonstrate check if list are identical test_list1 = [1, 2, 4, 3, 5] test_list2 = [1, 2, 4, 3, 5] print ("The first list is : " + str(test_list1)) print ("The second list is : " + str(test_list2)) test_list1.sort() test_list2.sort() if test_list1 == test_list2: print ("The lists are identical") else : print ("The lists are not identical") # write Python program to find Mathematical Median of Cumulative Records test_list = [(1, 4, 5), (7, 8), (2, 4, 10)] print("The original list : " + str(test_list)) res = [] for sub in test_list : for ele in sub : res.append(ele) res.sort() mid = len(res) // 2 res = (res[mid] + res[~mid]) / 2 print("Median of Records is : " + str(res)) # write Python program to demonstrate working of Cummulative Records Product def prod(val) : res = 1 for ele in val: res *= ele return res test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] print("The original list : " + str(test_list)) res = prod(int(j) for i in test_list for j in i) print("The Cummulative product of list is : " + str(res)) # Calculate difference in days between two dates def days_between(d1, d2): from datetime import datetime as dt f_date = dt.strptime(d1, "%d/%m/%Y").date() l_date = dt.strptime(d2, "%d/%m/%Y").date() delta = l_date - f_date print(delta.days) # Program to find the number if it is within 100 of 1000 or 2000 def near_thousand(n): return (abs(1000 - n) <= 100) or (abs(2000 - n) <= 100) print(near_thousand(1000)) print(near_thousand(900)) print(near_thousand(800)) print(near_thousand(2200)) # Calculate the sum of three given numbers, if the values are equal then return thrice of their sum def sum_thrice(x, y, z): sum1 = x + y + z if x == y == z: sum1 = sum1 * 3 return sum1 print(sum_thrice(1, 2, 3)) print(sum_thrice(3, 3, 3)) # Python program to get a string which is n (non-negative integer) copies of a given string. def larger_string(string1, n): result = "" for i in range(n): result = result + string1 return result print(larger_string('abc', 2)) print(larger_string('.py', 3)) # Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate # message to the user. def check_number(num): mod = num % 2 if mod > 0: return "This is an odd number." else: return "This is an even number." print(check_number(5)) # Given an integer, , and space-separated integers as input, create a tuple, , of those integers. Then compute and # print the result of . def hashing(num): T = tuple([int(i) for i in num.split()]) return hash(T) print(hashing(23456)) # You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. def word_join(s): words = s.split(' ') return '-'.join(words) print(word_join("This is 17B Assignment")) # Python program to compute the greatest common divisor (GCD) of two positive integers. def gcd(x, y): gcd1 = 1 if x % y == 0: return y for k in range(int(y / 2), 0, -1): if x % k == 0 and y % k == 0: gcd1 = k break return gcd1 print(gcd(12, 17)) print(gcd(4, 6)) # Python program to calculate area of a circle def area(a): from math import pi r = float(input("Input the radius of the circle : ")) return "The area of the circle with radius " + str(r) + " is: " + str(pi * a ** 2) print(area(5)) # Python program that accepts an integer (n) and computes the value of n+nn+nnn. def custom(n): a = n n1 = int("%s" % a) n2 = int("%s%s" % (a, a)) n3 = int("%s%s%s" % (a, a, a)) return n1 + n2 + n3 print(custom(20)) # Python program to count number 4 in the given list def list_count_4(nums): count = 0 for num in nums: if num == 4: count = count + 1 return count print(list_count_4([1, 4, 6, 7, 4])) print(list_count_4([1, 4, 6, 4, 7, 4])) # Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n # copies of the whole string if the length is less than 2. def substring_copy(str, n): flen = 2 if flen > len(str): flen = len(str) substr = str[:flen] result = "" for i in range(n): result = result + substr return result print(substring_copy('abcdef', 2)) print(substring_copy('p', 3)) # Python program to test whether passed letter is vowel or not def is_vowel(char): all_vowels = 'aeiou' return char in all_vowels print(is_vowel('c')) print(is_vowel('e')) # Python program to create histogram from given list def histogram(items): for n in items: output = '' times = n while times > 0: output += '*' times = times - 1 print(output) histogram([2, 3, 6, 5]) # Python program to print out all even numbers from a given numbers list in the same order and stop the printing if # any numbers that come after 237 in the sequence. numbers = [ 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 743, 527 ] for x in numbers: if x == 237: print(x) break; elif x % 2 == 0: print(x) # Python program to add two objects if both objects are of type integer def add_numbers(a, b): if not (isinstance(a, int) and isinstance(b, int)): raise TypeError("Inputs must be integers") return a + b print(add_numbers(10, 20)) # Python program to compute distance between two points def points(x1, x2): import math p1 = list(x1) p2 = list(x2) distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2)) print(distance) points((2, 3), (4, 5)) # Python program to print sum of digits of a 4 digit number def sumofdigits(num): x = num // 1000 x1 = (num - x * 1000) // 100 x2 = (num - x * 1000 - x1 * 100) // 10 x3 = num - x * 1000 - x1 * 100 - x2 * 10 print("The sum of digits in the number is", x + x1 + x2 + x3) sumofdigits(3456) # python program to multiply all the numbers in given list def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8, 2, 3, -1, 7))) # Python program to reverse the string def string_reverse(str1): rstr1 = '' index = len(str1) while index > 0: rstr1 += str1[index - 1] index = index - 1 return rstr1 print(string_reverse('1234abcd')) # Python program to calculate the factorial of a number def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = 45 print(factorial(n)) # Python program to accept string and calculate number of upper and lower case string 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 characters : ", d["UPPER_CASE"]) print("No. of Lower case Characters : ", d["LOWER_CASE"]) string_test('The quick Brown Fox') # python program to return unique element from a list def unique_list(l): x1 = [] for a in l: if a not in x1: x1.append(a) return x1 print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) # Python program to check for palindrom 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')) # Python program to make a chain of function decorators (bold, italic, underline etc. def make_bold(fn): def wrapped(): return "" + fn() + "" return wrapped def make_italic(fn): def wrapped(): return "" + fn() + "" return wrapped def make_underline(fn): def wrapped(): return "" + fn() + "" return wrapped @make_bold @make_italic @make_underline def hello(): return "hello world" print(hello()) # Python program to execute a string containing Python code. mycode = 'print("hello world")' code = """ def multiply(x,y): return x*y print('Multiply of 2 and 3 is: ',multiply(2,3)) """ exec(mycode) exec(code) # Python program to access function iside function def test(a): def add(b): nonlocal a a += 1 return a + b return add func = test(4) print(func(4)) # python program to detect number of local variables defined in a program def abc(): x = 1 y = 2 str1 = "w3resource" print("Python Exercises") print(abc.__code__.co_nlocals) # python program to add three list def add_list(num1, num2, num3): result = map(lambda x, y, z: x + y + z, num1, num2, num3) print("\nNew list after adding above three lists:") print(list(result)) nums1 = [1, 2, 3] nums2 = [4, 5, 6] nums3 = [7, 8, 9] add_list(nums1, nums2, nums3) # Python program to create a list containing the power of said number in bases raised to the corresponding number in # the index using Python map bases_num = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def power_base(num1, index1): print("Base numbers abd index: ") print(bases_num) print(index) result = list(map(pow, num1, index1)) print("\nPower of said number in bases raised to the corresponding number in the index:") print(result) power_base(bases_num, index) # Python function to find a distinct pair of numbers whose product is odd from a sequence of integer values. def odd_product(nums): for i in range(len(nums)): for j in range(len(nums)): if i != j: product = nums[i] * nums[j] if product & 1: return True return False dt1 = [2, 4, 6, 8] dt2 = [1, 6, 4, 7, 8] print(dt1, odd_product(dt1)) print(dt2, odd_product(dt2)) # Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller # than the specified number. def sum_of_cubes(n): n -= 1 total = 0 while n > 0: total += n * n * n n -= 1 return total print("Sum of cubes: ", sum_of_cubes(3)) # Python function to check whether a number is divisible by another number def multiple(m, n): return True if m % n == 0 else False print(multiple(20, 5)) print(multiple(7, 2)) # Python program to validate a Gregorian date def check_date(m, d, y): import datetime try: m, d, y = map(int, (m, d, y)) datetime.date(y, m, d) return True except ValueError: return False print(check_date(11, 11, 2002)) print(check_date('11', '11', '2002')) print(check_date(13, 11, 2002)) # Python program to create all possible permutations from a given collection of distinct numbers. def permute(nums): result_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm) + 1): new_perms.append(perm[:i] + [n] + perm[i:]) result_perms = new_perms return result_perms my_nums = [1, 2, 3] print("Original Collection: ", my_nums) print("Collection of distinct numbers:\n", permute(my_nums)) # Python program to get the third side of right angled triangle from two given sides. def pythagoras(opposite_side, adjacent_side, hypotenuse): if opposite_side == str("x"): return "Opposite = " + str(((hypotenuse ** 2) - (adjacent_side ** 2)) ** 0.5) elif adjacent_side == str("x"): return "Adjacent = " + str(((hypotenuse ** 2) - (opposite_side ** 2)) ** 0.5) elif hypotenuse == str("x"): return "Hypotenuse = " + str(((opposite_side ** 2) + (adjacent_side ** 2)) ** 0.5) else: return "You know the answer!" print(pythagoras(3, 4, 'x')) print(pythagoras(3, 'x', 5)) print(pythagoras('x', 4, 5)) print(pythagoras(3, 4, 5)) # Python program to find the digits which are absent in a given mobile number. def absent_digits(n): all_nums = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) n = set([int(i) for i in n]) n = n.symmetric_difference(all_nums) n = sorted(n) return n print(absent_digits([9, 8, 3, 2, 2, 0, 9, 7, 6, 3])) # Write a python function to generate random number between 2 integers def random_number(a, b): import random return random.randint(a, b) # Write a function to get n elements of the fibonacci series def fibonacci(n): n1, n2 = 0, 1 count = 0 if n <= 0: print('Please enter a positive integer') elif n == 1: print("Fibonacci sequence:") print(n1) else: print("Fibonacci sequence:") while count < n: print(n1) nth = n1 + n2 # update values n1, n2 = n2, nth count += 1 # Write a function to get nth element of the fibonacci series def fibonacci_nth(n): a = 0 b = 1 if n <= 0: print("Incorrect input") elif n==1: return a elif n==1: return 1 else: for i in range(2, n): c = a + b a, b = b, c return b # Write a function to count the number of digits in a number def count_digits(n): return len(str(n)) # Write a function to return the nth prime number def nth_prime_number(n): prime_list = [2] num = 3 while len(prime_list) < n: for p in prime_list: if num % p == 0: break else: prime_list.append(num) num += 2 return prime_list[-1] #1. write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') #2. write a python program to subtract two numbers num1 = 1.5 num2 = 6.3 sum = num1 - num2 print(f'Sub: {sum}') #3. write a python Program to calculate the square root num = 8 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) #4. write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum #5. write a program to find and print the largest among three numbers num1 = 10 num2 = 12 num3 = 14 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}') #6. Write a python program to swap two variables, Using a temporary variable x = 5 y = 10 temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) #7. Write a python program to swap two variables, Without Using Temporary Variable x = 5 y = 10 x, y = y, x print("x =", x) print("y =", y) #8. Python Program to Convert Kilometers to Miles kilometers = 5.0 conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) #9. Python Program to Convert Celsius To Fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) #10. Python Program to Check if a Number is Positive, Negative or 0 num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") #11. Python Program to Check if a Number is Odd or Even num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) #12. Python Program to Check Leap Year year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) #13. Python Program to Find the Largest Among Three Numbers num1 = 10 num2 = 14 num3 = 12 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is", largest) #14.Write a Python Program to check if a number is prime or not num = 407 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") #15.Python program to display all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) #16. Python program to find the factorial of a number. num = 7 factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) #17. Python Program to Display the multiplication Table num = 12 for i in range(1, 11): print(num, 'x', i, '=', num*i) #18. Python Program to Print the Fibonacci sequence nterms = int(input("How many terms? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 #19. Python Program to Check Armstrong Number (for 3 digits) num = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #20. Python Program to Check Armstrong Number (for 3 digits) num = 1634 # Changed num variable to string, # and calculated the length (number of digits) order = len(str(num)) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #21. Python Program to Find Armstrong Number in an Interval lower = 100 upper = 2000 for num in range(lower, upper + 1): # order of number order = len(str(num)) # initialize sum sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) #22. Python Program to Find the Sum of Natural Numbers num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) #23. Python Program To Display Powers of 2 Using Anonymous Function # Display the powers of 2 using anonymous function terms = 10 # Uncomment code below to take input from the user # terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) #24. Python Program to Find Numbers Divisible by Another Number # Take a list of numbers my_list = [12, 65, 54, 39, 102, 339, 221,] # use anonymous function to filter result = list(filter(lambda x: (x % 13 == 0), my_list)) # display the result print("Numbers divisible by 13 are",result) #25. Python Program to Convert Decimal to Binary dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") #26. Python Program to Convert Decimal to Octal dec = 344 print("The decimal value of", dec, "is:") print(oct(dec), "in octal.") #27. Python Program to Convert Decimal to Hexadecimal dec = 344 print("The decimal value of", dec, "is:") print(hex(dec), "in hexadecimal.") #28. Python Program to Find ASCII Value of Character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) #29. Python Program to Find HCF or GCD def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 print("The H.C.F. is", compute_hcf(num1, num2)) #30. Write a python function to find HCf or GCD and return the value def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf #31. Write a python function to find HCf or GCD and return the value using euclidian Algorithm def compute_hcf(x, y): while(y): x, y = y, x % y return x #32. Write a python program to find HCf or GCD using euclidian Algorithm def compute_hcf(x, y): while(y): x, y = y, x % y return x #33. Python Program to Find LCM def compute_lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) #34. write a Python function to Find LCM and returb the value def compute_lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm #35. Python Program to Compute LCM Using GCD # This function computes GCD def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) #36. Python funcction to Find the Factors of a Number def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) #37. Python Program to Make a Simple Calculator # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # Take input from the user choice = input("Enter choice(1/2/3/4): ") # Check if choice is one of the four options if choice in ('1', '2', '3', '4'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) break else: print("Invalid Input") #37. Python Program to Display Fibonacci Sequence Using Recursion def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) nterms = 10 # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i)) #38. Python Program to Find Sum of Natural Numbers Using Recursion def recur_sum(n): if n <= 1: return n else: return n + recur_sum(n-1) # change this value for a different result num = 16 if num < 0: print("Enter a positive number") else: print("The sum is",recur_sum(num)) #39. Python Program to Find Factorial of Number Using Recursion def recur_factorial(n): if n == 1: return n else: return n*recur_factorial(n-1) num = 7 # check if the number is negative if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num)) #40. Python Program to Add Two Matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) #41. Python Program to Add Two Matrices using Nested List Comprehension X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))] for r in result: print(r) #42. Python Program to Transpose a Matrix using Nested Loop X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) #43. Python Program to Transpose a Matrix using Nested List Comprehension X = [[12,7], [4 ,5], [3 ,8]] result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))] for r in result: print(r) #44. Python Program to Multiply Two Matrices using Nested Loop X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) #44. Python Program to Multiply Two Matrices using Nested List Comprehension X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X] for r in result: print(r) #45. Python Program to Check Whether a String is Palindrome or Not my_str = 'aIbohPhoBiA' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") #46. Python Program to Remove Punctuations From a String punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." # To take input from the user # my_str = input("Enter a string: ") # remove punctuation from the string no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # display the unpunctuated string print(no_punct) #47. Python Program to Sort Words in Alphabetic Order my_str = "Hello this Is an Example With cased letters" # To take input from the user #my_str = input("Enter a string: ") # breakdown the string into a list of words words = [word.lower() for word in my_str.split()] # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word) #48. Python Program to Illustrate Different Set Operations # define three sets E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; # set union print("Union of E and N is",E | N) # set intersection print("Intersection of E and N is",E & N) # set difference print("Difference of E and N is",E - N) # set symmetric difference print("Symmetric difference of E and N is",E ^ N) # 49. Python Program to Count the Number of Each Vowel vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: count[char] += 1 print(count) #50. Python Program to Count the Number of Each Vowel Using a list and a dictionary comprehension ip_str = 'Hello, have you tried our tutorial section yet?' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # count the vowels count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'} print(count) # Write a python function to derive slope given 2 points (x1,y1) and (x2, y2) def get_slope(x1,y1, x2,y2): if (x1 == x2 ): return ValueError return -((y2-y1)/(x2-x1)) # Write a python function to rotate a point (x,y) around a given origix (ox,oy) by an angle def rotate(origin, point, angle): ox, oy = origin px, py = point radian_angle = math.radians(angle) qx = ox + math.cos(radian_angle) * (px - ox) - math.sin(radian_angle) * (py - oy) qy = oy + math.sin(radian_angle) * (px - ox) + math.cos(radian_angle) * (py - oy) return qx, qy # Write a python function to copy the sign bit from one variable to another def copysign(dst, src) : return math.copysign(dst, src) # Write a python function Split a given file path into filename and parent directory def split_filename(input_file_name): if( isinstance(input_file_name,str) ==False ): raise TypeError tokens = input_file_name.split("/") return "/".join(tokens[:-1]),tokens[-1] # Write a python function to join directory names to create a path def join_filename(base_dir, *args): file_path_args = [base_dir ,*args] for file_name in file_path_args: if( isinstance(file_name,str) ==False ): raise TypeError return "/".join(file_path_args) # Write a python function to find linear interpolation between two points x and y given a variable t def linear_interpolate(x, y, t ): if( t >=1 or t <= 0): raise ValueError return t*x + (1-t)*y # Write a python function to find bilinear interpolation of a point x, y given 4 points represented as a list def bilinear_interpolation(x, y, points): points = sorted(points) # order points by x, then by y (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = points if x1 != _x1 or x2 != _x2 or y1 != _y1 or y2 != _y2: raise ValueError('points do not form a rectangle') if not x1 <= x <= x2 or not y1 <= y <= y2: raise ValueError('(x, y) not within the rectangle') return (q11 * (x2 - x) * (y2 - y) + q21 * (x - x1) * (y2 - y) + q12 * (x2 - x) * (y - y1) + q22 * (x - x1) * (y - y1) ) / ((x2 - x1) * (y2 - y1) + 0.0) # Write a python function to raise error when an input is not a string type def check_string(new_str): return isinstance(new_str,str) ## Write a python function to extract only alphabets from a given string and also exclude spaces def extract_alpha(my_string): return "".join([ c for c in my_string if c.isalpha()]) # Write a python function to extract only alphabets from a given string and also include spaces def extract_alpha(my_string): return "".join([ c for c in my_string if (c.isalpha() or c.isspace())]) # Write a python function to remove all non-alphabets except space from a given string using re library import re def extract_not_alpha(my_string): #result = re.findall(r'[^a-zA-Z]+',my_string) return re.sub('[^a-zA-Z\s]+', "", my_string) #return "".join(result) # Write a python function to remove all digits and underscores from a Unicode strings import re def extract_unicode(my_string): regex = re.compile(r'[^\W\d_]+', re.UNICODE) return regex.findall(my_string) # Write a python function to find all email-id patterns in a given string and write to a user input file import re def extract_mailid(my_string, outfile): regex = re.compile(r'[\w]+@[\w]+\.[\w]+', re.UNICODE) mailids = regex.findall(my_string) if(len(mailids) > 0): with open(outfile, 'w') as mailfile: for mailid in mailids: mailfile.write(mailid+"\n") mailfile.close() # Write a python function to generate a random hexadecimal key of length n import random def rand_run_name(n): ran = random.randrange(10**80) myhex = "%064x" % ran #limit string to 64 characters myhex = myhex[:n] return myhex # Write a python function to create an argument parser that takes inputs as program name and description of program and filename as inputs for variable length of args import argparse def create_parser(prog_name, prog_description, arg_name): parser = argparse.ArgumentParser(prog = prog_name, description = prog_description) parser.add_argument(arg_name, nargs='+') #args = parser.parse_args() return parser # Write a python function check if a given directory exists and has any files import os def check_dir_files(src_dir_path): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return False files_in_dir = glob.glob(src_dir_path+"/*.*") if (len(files_in_dir) <= 0): print("No files present in:",src_dir_path) return False print("The directory ", src_dir_path, " has ",len(files_in_dir), " files.") return True # Write a python function to get user specified attributes such as day, month, year from a date import datetime def get_attributes_from_date(date_string,*args): if(isinstance(date_string, datetime.datetime) == False): print("Input string is not a valid datetime type") raise TypeError get_attrs = [ i for i in dir(date_string) if not callable(i) ] arg_list = [] for attr in args: if(attr not in get_attrs): print("Invalid argument passed",attr) raise AttributeError print(attr, ':', getattr(date_string, attr)) arg_list.append((attr,getattr(date_string, attr))) return arg_list # Write a python function to find all files with a given pattern in a source directory to a different destination directory import glob import os def find_move_files(src_dir_path, dst_dir_path, file_pattern): if(os.path.exists(dst_dir_path) == False): print("Destination Path doesn't exist") return all_png_files = glob.glob(src_dir_path+"/*"+file_pattern) if (len(all_png_files) > 0): for file_name in all_png_files: base_file_name=os.path.basename(file_name) os.replace(file_name, os.path.join(dst_dir_path, base_file_name)) return else: print("No files with matching pattern found") return # Write a python function to select a random number of files from a given path of a given pattern import glob import os import random def retrieve_random_file(src_dir_path, file_pattern, count): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return files_in_dir = glob.glob(src_dir_path+"/*"+file_pattern) if (count > len(files_in_dir)): print("Requested count more than file count in:",src_dir_path," for pattern:",file_pattern) return return random.sample(files_in_dir, count) # Write a python function to return the content of a directory and the last modified date import glob import os import time def retrieve_files_bydate(src_dir_path,*args): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return files_in_dir = glob.glob(src_dir_path+"/*.*") if (len(files_in_dir) <= 0): print("No files present in:",src_dir_path) return file_date_list = [ (filename, time.ctime(os.path.getmtime(filename)))for filename in files_in_dir] return file_date_list # Write a python function to return the content of a directory sorted by last modified date import glob import os import datetime def retrieve_files_sort_bydate(src_dir_path): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return files_in_dir = glob.glob(src_dir_path+"/*.*") if (len(files_in_dir) <= 0): print("No files present in:",src_dir_path) return files_in_dir.sort(key=os.path.getmtime) return files_in_dir # Write a python function to select files from a directory that have been modified in last x hours given by the user import glob import os import random import datetime def retrieve_last_files(src_dir_path, last_modified_hour): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return if( last_modified_hour <0 or last_modified_hour>24): print("Invalid delta requested") raise ValueError files_in_dir = glob.glob(src_dir_path+"/*.*") if (len(files_in_dir) <= 0): print("No files present in:",src_dir_path) return return [ filename for filename in files_in_dir if (datetime.datetime.fromtimestamp(os.path.getmtime(filename)) < datetime.datetime.now() + datetime.timedelta(hours=last_modified_hour)) ] # Write a python function to print the size of all the files in a directory only at topmost level import os def get_filesize_for_dir(src_dir_path): if(os.path.exists(src_dir_path) == False): print("Destination Path doesn't exist") return files_in_dir = glob.glob(src_dir_path+"/*.*") if (len(files_in_dir) <= 0): print("No files present in:",src_dir_path) return total_size = 0 for filename in files_in_dir: #(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file) total_size += os.stat(filename)[6] return total_size # Write a python function to read a user specified csv file and a delimiter and return the number of rows and number of columns in the first row. import csv def read_csv_length(csv_file_name, delimiter_pattern): if(os.path.exists(csv_file_name) == False): print("Destination File doesn't exist") return with open(csv_file_name, newline='') as csvfile: csv_reader = csv.reader(csvfile, delimiter=delimiter_pattern) csv_list = list(csv_reader) return len(csv_list), len(csv_list[0]) # Write a python function to convert a list of strings to equivalent character array using itertools import itertools def extract_characters(input_list): return [ char_val for char_val in itertools.chain.from_iterable(input_list) ] # Write a python function to generate a random combination from user provided list and user specified length. import itertools def get_random_combination(input_list, combination_length): if(len(input_list) < combination_length): print("Requested combination length less than length of list") return combination_list = list(itertools.combinations(input_list, combination_length)) return random.sample(combination_list, 1) # Write a python function to generate amortization schedule given initial loan amount, interest rate, annual payments and tenure. import itertools def loan_schedule(principal, interest_rate, annual_payment, tenure): if(tenure <= 0): print("Invalid tenure",tenure) raise ValueError if(interest_rate > 1 or interest_rate < 0): print("Invalid interest rate",interest_rate," Expected between 0 and 1") raise ValueError cashflows = [principal, *list(itertools.repeat(-annual_payment, tenure))] effective_interest_rate = 1+interest_rate return [ val for val in list(itertools.accumulate(cashflows, lambda bal, pmt: (bal*effective_interest_rate + pmt))) if val > 0] # Write a python function to generate amortization schedule given initial loan amount, interest rate, annual payments and tenure. import itertools def loan_schedule(principal, interest_rate, annual_payment, tenure): if(tenure <= 0): print("Invalid tenure",tenure) raise ValueError if(interest_rate > 1 or interest_rate < 0): print("Invalid interest rate",interest_rate," Expected between 0 and 1") raise ValueError cashflows = [principal, *list(itertools.repeat(-annual_payment, tenure))] effective_interest_rate = 1+interest_rate return [ val for val in list(itertools.accumulate(cashflows, lambda bal, pmt: (bal*effective_interest_rate + pmt))) if val > 0] # Write a python function to accept user defined file, user-defined loglevel and create a file-based and invoke the user-defined function with this logger. import logging def create_logging_level(user_func, user_filename, user_loglevel): logger = logging.getLogger('simple_example') logger.setLevel(user_loglevel) ch = logging.FileHandler(user_filename) ch.setLevel(user_loglevel) logger.addHandler(ch) if callable(user_func): user_func(logger) # Write a python function to simulate an exception and log the error using logger provided by the user. def exception_simulator(logger): try: raise ValueError except ValueError: logger.exception("ValueError occured in the function") # Write a python function to call a user-input function with default exception handling and re-raise the exception again. def default_exception_simulator(user_func): try: if callable(user_func): user_func() except: print("An exception occured") raise #1. write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') #2. write a python program to subtract two numbers num1 = 1.5 num2 = 6.3 sum = num1 - num2 print(f'Sub: {sum}') #3. write a python Program to calculate the square root num = 8 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) #4. write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum #5. write a program to find and print the largest among three numbers num1 = 10 num2 = 12 num3 = 14 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}') #6. Write a python program to swap two variables, Using a temporary variable x = 5 y = 10 temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) #7. Write a python program to swap two variables, Without Using Temporary Variable x = 5 y = 10 x, y = y, x print("x =", x) print("y =", y) #8. Python Program to Convert Kilometers to Miles kilometers = 5.0 conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) #9. Python Program to Convert Celsius To Fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) #10. Python Program to Check if a Number is Positive, Negative or 0 num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") #11. Python Program to Check if a Number is Odd or Even num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) #12. Python Program to Check Leap Year year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) #13. Python Program to Find the Largest Among Three Numbers num1 = 10 num2 = 14 num3 = 12 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is", largest) #14.Write a Python Program to check if a number is prime or not num = 407 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") #15.Python program to display all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) #16. Python program to find the factorial of a number. num = 7 factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) #17. Python Program to Display the multiplication Table num = 12 for i in range(1, 11): print(num, 'x', i, '=', num*i) #18. Python Program to Print the Fibonacci sequence nterms = int(input("How many terms? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 #19. Python Program to Check Armstrong Number (for 3 digits) num = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #20. Python Program to Check Armstrong Number (for 3 digits) num = 1634 # Changed num variable to string, # and calculated the length (number of digits) order = len(str(num)) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #21. Python Program to Find Armstrong Number in an Interval lower = 100 upper = 2000 for num in range(lower, upper + 1): # order of number order = len(str(num)) # initialize sum sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) #22. Python Program to Find the Sum of Natural Numbers num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) #23. Python Program To Display Powers of 2 Using Anonymous Function # Display the powers of 2 using anonymous function terms = 10 # Uncomment code below to take input from the user # terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) #24. Python Program to Find Numbers Divisible by Another Number # Take a list of numbers my_list = [12, 65, 54, 39, 102, 339, 221,] # use anonymous function to filter result = list(filter(lambda x: (x % 13 == 0), my_list)) # display the result print("Numbers divisible by 13 are",result) #25. Python Program to Convert Decimal to Binary dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") #26. Python Program to Convert Decimal to Octal dec = 344 print("The decimal value of", dec, "is:") print(oct(dec), "in octal.") #27. Python Program to Convert Decimal to Hexadecimal dec = 344 print("The decimal value of", dec, "is:") print(hex(dec), "in hexadecimal.") #28. Python Program to Find ASCII Value of Character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) #29. Python Program to Find HCF or GCD def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 print("The H.C.F. is", compute_hcf(num1, num2)) #30. Write a python function to find HCf or GCD and return the value def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf #31. Write a python function to find HCf or GCD and return the value using euclidian Algorithm def compute_hcf(x, y): while(y): x, y = y, x % y return x #32. Write a python program to find HCf or GCD using euclidian Algorithm def compute_hcf(x, y): while(y): x, y = y, x % y return x #33. Python Program to Find LCM def compute_lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) #34. write a Python function to Find LCM and returb the value def compute_lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm #35. Python Program to Compute LCM Using GCD # This function computes GCD def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) #36. Python funcction to Find the Factors of a Number def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) #37. Python Program to Make a Simple Calculator # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # Take input from the user choice = input("Enter choice(1/2/3/4): ") # Check if choice is one of the four options if choice in ('1', '2', '3', '4'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) break else: print("Invalid Input") #37. Python Program to Display Fibonacci Sequence Using Recursion def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) nterms = 10 # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i)) #38. Python Program to Find Sum of Natural Numbers Using Recursion def recur_sum(n): if n <= 1: return n else: return n + recur_sum(n-1) # change this value for a different result num = 16 if num < 0: print("Enter a positive number") else: print("The sum is",recur_sum(num)) #39. Python Program to Find Factorial of Number Using Recursion def recur_factorial(n): if n == 1: return n else: return n*recur_factorial(n-1) num = 7 # check if the number is negative if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num)) #40. Python Program to Add Two Matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) #41. Python Program to Add Two Matrices using Nested List Comprehension X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))] for r in result: print(r) #42. Python Program to Transpose a Matrix using Nested Loop X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) #43. Python Program to Transpose a Matrix using Nested List Comprehension X = [[12,7], [4 ,5], [3 ,8]] result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))] for r in result: print(r) #44. Python Program to Multiply Two Matrices using Nested Loop X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) #44. Python Program to Multiply Two Matrices using Nested List Comprehension X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X] for r in result: print(r) #45. Python Program to Check Whether a String is Palindrome or Not my_str = 'aIbohPhoBiA' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") #46. Python Program to Remove Punctuations From a String punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." # To take input from the user # my_str = input("Enter a string: ") # remove punctuation from the string no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # display the unpunctuated string print(no_punct) #47. Python Program to Sort Words in Alphabetic Order my_str = "Hello this Is an Example With cased letters" # To take input from the user #my_str = input("Enter a string: ") # breakdown the string into a list of words words = [word.lower() for word in my_str.split()] # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word) #48. Python Program to Illustrate Different Set Operations # define three sets E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; # set union print("Union of E and N is",E | N) # set intersection print("Intersection of E and N is",E & N) # set difference print("Difference of E and N is",E - N) # set symmetric difference print("Symmetric difference of E and N is",E ^ N) # 49. Python Program to Count the Number of Each Vowel vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: count[char] += 1 print(count) #50. Python Program to Count the Number of Each Vowel Using a list and a dictionary comprehension ip_str = 'Hello, have you tried our tutorial section yet?' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # count the vowels count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'} print(count) # -*- coding: utf-8 -*- """PythonGeneration.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/10cXGL8ix2PbFMLcNlTpHdAA7GBJkQzRe """ # Given a string, find the length of the longest substring without repeating characters. str = "IshwarVenugopal" def longest_non_repeat(str): i=0 max_length = 1 for i,c in enumerate(str): start_at = i sub_str=[] while (start_at < len(str)) and (str[start_at] not in sub_str): sub_str.append(str[start_at]) start_at = start_at + 1 if len(sub_str) > max_length: max_length = len(sub_str) print(sub_str) return max_length longest_non_repeat(str) # Given an array of integers, return indices of the two numbers such that they add up to a specific target. input_array = [2, 7, 11, 15] target = 26 result = [] for i, num in enumerate(input_array): for j in range(i+1, len(input_array)): print(i,j) # Given a sorted integer array without duplicates, return the summary of its ranges. input_array = [0,1,2,4,5,7] start=0 result = [] while start < len(input_array): end = start while end+1{1}".format(input_array[start], input_array[end])) print(result) else: result.append("{0}".format(input_array[start])) print(result) start = end+1 print(result) # Rotate an array of n elements to the right by k steps. org = [1,2,3,4,5,6,7] result = org[:] steps = 3 for idx,num in enumerate(org): if idx+steps < len(org): result[idx+steps] = org[idx] else: result[idx+steps-len(org)] = org[idx] print(result) # Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. first_array = [1,2,3,4,5,6,7] second_array = [3,7,2,1,4,6] def finder(first_array, second_array): return(sum(first_array) - sum(second_array)) missing_number = finder(first_array, second_array) print(missing_number) # Given a collection of intervals which are already sorted by start number, merge all overlapping intervals. org_intervals = [[1,3],[2,6],[5,10],[11,16],[15,18],[19,22]] i = 0 while i < len(org_intervals)-1: if org_intervals[i+1][0] < org_intervals[i][1]: org_intervals[i][1]=org_intervals[i+1][1] del org_intervals[i+1] i = i - 1 i = i + 1 print(org_intervals) # Given a list slice it into a 3 equal chunks and revert each list sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89] length = len(sampleList) chunkSize = int(length/3) start = 0 end = chunkSize for i in range(1, 4, 1): indexes = slice(start, end, 1) listChunk = sampleList[indexes] mylist = [i for i in listChunk] print("After reversing it ", mylist) start = end if(i != 2): end +=chunkSize else: end += length - chunkSize # write a program to calculate exponents of an input input = 9 exponent = 2 final = pow(input, exponent) print(f'Exponent Value is:{final}') # write a program to multiply two Matrix # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] print(f"Final Result is{result}") # write a program to find and print the remainder of two number num1 = 12 num2 = 10 ratio = num1 % num2 print(f'remainder:{ratio}') # reverse a number in Python number = 1367891 revs_number = 0 while (number > 0): remainder = number % 10 revs_number = (revs_number * 10) + remainder number = number // 10 print("The reverse number is : {}".format(revs_number)) # Python program to compute sum of digits in number def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) n = 1234511 print(sumDigits(n)) # Find the middle element of a random number list my_list = [4,3,2,9,10,44,1] print("mid value is ",my_list[int(len(my_list)/2)]) # Sort the list in ascending order my_list = [4,3,2,9,10,44,1] my_list.sort() print(f"Ascending Order list:,{my_list}") # Sort the list in descending order my_list = [4,3,2,9,10,44,1] my_list.sort(reverse=True) print(f"Descending Order list:,{my_list}") # Concatenation of two List my_list1 = [4,3,2,9,10,44,1] my_list2 = [5,6,2,8,15,14,12] print(f"Sum of two list:,{my_list1+my_list2}") # Removes the item at the given index from the list and returns the removed item my_list1 = [4,3,2,9,10,44,1,9,12] index = 4 print(f"Sum of two list:,{my_list1.pop(index)}") # Adding Element to a List animals = ['cat', 'dog', 'rabbit'] animals.append('guinea pig') print('Updated animals list: ', animals) # Returns the number of times the specified element appears in the list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] count = vowels.count('i') print('The count of i is:', count) # Count Tuple Elements Inside List random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] count = random.count(('a', 'b')) print("The count of ('a', 'b') is:", count) # Removes all items from the list list = [{1, 2}, ('a'), ['1.1', '2.2']] list.clear() print('List:', list) # access first characters in a string word = "Hello World" letter=word[0] print(f"First Charecter in String:{letter}") # access Last characters in a string word = "Hello World" letter=word[-1] print(f"First Charecter in String:{letter}") # Generate a list by list comprehension list = [x for x in range(10)] print(f"List Generated by list comprehension:{list}") # Set the values in the new list to upper case list = "AMITKAYAL" newlist = [x.upper() for x in list] print(f"New list to upper case:{newlist}") # Sort the string list alphabetically thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(f"Sorted List:{thislist}") # Join Two Sets set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set2.union(set1) print(f"Joined Set:{set3}") # keep only the items that are present in both sets x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(f"Duplicate Value in Two set:{x}") # Keep All items from List But NOT the Duplicates x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(f"Duplicate Value in Two set:{x}") # Create and print a dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Sample Dictionary:{thisdict}") # Calculate the length of dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Length of Dictionary:{len(thisdict)}") # Evaluate a string and a number print(bool("Hello")) print(bool(15)) # Calculate length of a string word = "Hello World" print(f"Length of string: {len(word)}") # Count the number of spaces in a sring s = "Count, the number of spaces" lenx = s.count(' ') print(f"number of spaces in sring: {lenx}") # Split Strings word = "Hello World" ksplit = word.split(' ') print(f"Splited Strings: {ksplit}") # Prints ten dots ten = "." * 10 print(f"Ten dots: {ten}") # Replacing a string with another string word = "Hello World" replace = "Bye" input = "Hello" after_replace = word.replace(input, replace) print(f"String ater replacement: {after_replace}") #removes leading characters word = " xyz " lstrip = word.lstrip() print(f"String ater removal of leading characters:{lstrip}") #removes trailing characters word = " xyz " rstrip = word.rstrip() print(f"String ater removal of trailing characters:{rstrip}") # check if all char are alphanumeric word = "Hello World" check = word.isalnum() print(f"All char are alphanumeric?:{check}") # check if all char in the string are alphabetic word = "Hello World" check = word.isalpha() print(f"All char are alphabetic?:{check}") # test if string contains digits word = "Hello World" check = word.isdigit() print(f"String contains digits?:{check}") # Test if string contains upper case word = "Hello World" check = word.isupper() print(f"String contains upper case?:{check}") # Test if string starts with H word = "Hello World" check = word.startswith('H') print(f"String starts with H?:{check}") # Returns an integer value for the given character str = "A" val = ord(str) print(f"Integer value for the given character?:{val}") # Fibonacci series up to 100 n = 100 result = [] a, b = 0 , 1 while b < n: result. append( b) a, b = b, a + b final = result print(f"Fibonacci series up to 100:{final}") # Counting total Digits in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isdigit()): digitCount += 1 print('Number of digits: ',digitCount) # Counting total alphanumeric in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isalpha()): digitCount += 1 print('Number of alphanumeric: ',digitCount) # Counting total Upper Case in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.upper()): digitCount += 1 print('Number total Upper Case: ',digitCount) # Counting total lower Case in a string str1 = "abc4234AFdeaa" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.lower()): digitCount += 1 print('Number total lower Case: ',digitCount) # Bubble sort in python list1 = [1, 5, 3, 4] for i in range(len(list1)-1): for j in range(i+1,len(list1)): if(list1[i] > list1[j]): temp = list1[i] list1[i] = list1[j] list1[j] = temp print("Bubble Sorted list: ",list1) # Compute the product of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a*b for a in list1 for b in list2] print(f"Product of every pair of numbers from two lists:{final}") # Calculate the sum of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a+b for a in list1 for b in list2] print(f"sum of every pair of numbers from two lists:{final}") # Calculate the pair-wise product of two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [list1[i]*list2[i] for i in range(len(list1))] print(f"pair-wise product of two lists:{final}") # Remove the last element from the stack s = [1,2,3,4] print(f"last element from the stack:{s.pop()}") # Insert a number at the beginning of the queue q = [1,2,3,4] q.insert(0,5) print(f"Revised List:{q}") # Addition of two vector v1 = [1,2,3] v2 = [1,2,3] s1 = [0,0,0] for i in range(len(v1)): s1[i] = v1[i] + v2[i] print(f"New Vector:{s1}") # Replace negative prices with 0 and leave the positive values unchanged in a list original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] print(f"Final List:{prices}") # Convert dictionary to JSON import json person_dict = {'name': 'Bob', 'age': 12, 'children': None } person_json = json.dumps(person_dict) print(person_json) # Writing JSON to a file import json person_dict = {"name": "Bob", "languages": ["English", "Fench"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file) # Pretty print JSON import json person_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}' person_dict = json.loads(person_string) print(json.dumps(person_dict, indent = 4, sort_keys=True)) # Check if the key exists or not in JSON import json studentJson ="""{ "id": 1, "name": "john wick", "class": 8, "percentage": 75, "email": "jhon@pynative.com" }""" print("Checking if percentage key exists in JSON") student = json.loads(studentJson) if "percentage" in student: print("Key exist in JSON data") print(student["name"], "marks is: ", student["percentage"]) else: print("Key doesn't exist in JSON data") # Check if there is a value for a key in JSON import json studentJson ="""{ "id": 1, "name": "Ishwar Venugopal", "class": null, "percentage": 35, "email": "ishwarraja@gmail.com" }""" student = json.loads(studentJson) if not (student.get('email') is None): print("value is present for given JSON key") print(student.get('email')) else: print("value is not present for given JSON key") # Sort JSON keys in Python and write it into a file import json sampleJson = {"id" : 1, "name" : "value2", "age" : 29} with open("sampleJson.json", "w") as write_file: json.dump(sampleJson, write_file, indent=4, sort_keys=True) print("Done writing JSON data into a file") # Given a Python list. Turn every item of a list into its square aList = [1, 2, 3, 4, 5, 6, 7] aList = [x * x for x in aList] print(aList) # Remove empty strings from the list of strings list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"] resList = [i for i in (filter(None, list1))] print(resList) # Write a program which will achieve given a Python list, remove all occurrence of an input from the list list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, 20) print(resList) # Generate 3 random integers between 100 and 999 which is divisible by 5 import random print("Generating 3 random integer number between 100 and 999 divisible by 5") for num in range(3): print(random.randrange(100, 999, 5), end=', ') # Pick a random character from a given String import random name = 'pynative' char = random.choice(name) print("random char is ", char) # Generate random String of length 5 import random import string def randomString(stringLength): """Generate a random string of 5 charcters""" letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) print ("Random String is ", randomString(5) ) # Generate a random date between given start and end dates import random import time def getRandomDate(startDate, endDate ): print("Printing random date between", startDate, " and ", endDate) randomGenerator = random.random() dateFormat = '%m/%d/%Y' startTime = time.mktime(time.strptime(startDate, dateFormat)) endTime = time.mktime(time.strptime(endDate, dateFormat)) randomTime = startTime + randomGenerator * (endTime - startTime) randomDate = time.strftime(dateFormat, time.localtime(randomTime)) return randomDate print ("Random Date = ", getRandomDate("1/1/2016", "12/12/2018")) # Write a program which will create a new string by appending s2 in the middle of s1 given two strings, s1 and s2 def appendMiddle(s1, s2): middleIndex = int(len(s1) /2) middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:] print("After appending new string in middle", middleThree) appendMiddle("Ault", "Kelly") # Arrange string characters such that lowercase letters should come first str1 = "PyNaTive" lower = [] upper = [] for char in str1: if char.islower(): lower.append(char) else: upper.append(char) sorted_string = ''.join(lower + upper) print(sorted_string) # Given a string, return the sum and average of the digits that appear in the string, ignoring all other characters import re inputStr = "English = 78 Science = 83 Math = 68 History = 65" markList = [int(num) for num in re.findall(r'\b\d+\b', inputStr)] totalMarks = 0 for mark in markList: totalMarks+=mark percentage = totalMarks/len(markList) print("Total Marks is:", totalMarks, "Percentage is ", percentage) # Given an input string, count occurrences of all characters within a string str1 = "Apple" countDict = dict() for char in str1: count = str1.count(char) countDict[char]=count print(countDict) # Reverse a given string str1 = "PYnative" print("Original String is:", str1) str1 = str1[::-1] print("Reversed String is:", str1) # Remove special symbols/Punctuation from a given string import string str1 = "/*Jon is @developer & musician" new_str = str1.translate(str.maketrans('', '', string.punctuation)) print("New string is ", new_str) # Removal all the characters other than integers from string str1 = 'I am 25 years and 10 months old' res = "".join([item for item in str1 if item.isdigit()]) print(res) # From given string replace each punctuation with # from string import punctuation str1 = '/*Jon is @developer & musician!!' replace_char = '#' for char in punctuation: str1 = str1.replace(char, replace_char) print("The strings after replacement : ", str1) # Given a list iterate it and count the occurrence of each element and create a dictionary to show the count of each elemen sampleList = [11, 45, 8, 11, 23, 45, 23, 45, 89] countDict = dict() for item in sampleList: if(item in countDict): countDict[item] += 1 else: countDict[item] = 1 print("Printing count of each item ",countDict) # Given a two list of equal size create a set such that it shows the element from both lists in the pair firstList = [2, 3, 4, 5, 6, 7, 8] secondList = [4, 9, 16, 25, 36, 49, 64] result = zip(firstList, secondList) resultSet = set(result) print(resultSet) # Given a two sets find the intersection and remove those elements from the first set firstSet = {23, 42, 65, 57, 78, 83, 29} secondSet = {57, 83, 29, 67, 73, 43, 48} intersection = firstSet.intersection(secondSet) for item in intersection: firstSet.remove(item) print("First Set after removing common element ", firstSet) # Given a dictionary get all values from the dictionary and add it in a list but donā€™t add duplicates speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54} speedList = [] for item in speed.values(): if item not in speedList: speedList.append(item) print("unique list", speedList) # Convert decimal number to octal print('%o,' % (8)) # Convert string into a datetime object from datetime import datetime date_string = "Feb 25 2020 4:20PM" datetime_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p') print(datetime_object) # Subtract a week from a given date from datetime import datetime, timedelta given_date = datetime(2020, 2, 25) days_to_subtract = 7 res_date = given_date - timedelta(days=days_to_subtract) print(res_date) # Find the day of week of a given date? from datetime import datetime given_date = datetime(2020, 7, 26) print(given_date.strftime('%A')) # Add week (7 days) and 12 hours to a given date from datetime import datetime, timedelta given_date = datetime(2020, 3, 22, 10, 00, 00) days_to_add = 7 res_date = given_date + timedelta(days=days_to_add, hours=12) print(res_date) # Calculate number of days between two given dates from datetime import datetime date_1 = datetime(2020, 2, 25).date() date_2 = datetime(2020, 9, 17).date() delta = None if date_1 > date_2: delta = date_1 - date_2 else: delta = date_2 - date_1 print("Difference is", delta.days, "days") # Write a recursive function to calculate the sum of numbers from 0 to 10 def calculateSum(num): if num: return num + calculateSum(num-1) else: return 0 res = calculateSum(10) print(res) # Generate a Python list of all the even numbers between two given numbers num1 = 4 num2 = 30 myval = [i for i in range(num1, num2, 2)] print(myval) # Return the largest item from the given list aList = [4, 6, 8, 24, 12, 2] print(max(aList)) # Write a program to extract each digit from an integer, in the reverse order number = 7536 while (number > 0): digit = number % 10 number = number // 10 print(digit, end=" ") # Given a Python list, remove all occurrence of a given number from the list num1 = 20 list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, num1) print(resList) # Shuffle a list randomly import random list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list) # Generate a random n-dimensional array of float numbers import numpy random_float_array = numpy.random.rand(2, 2) print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n") # Generate random Universally unique IDs import uuid safeId = uuid.uuid4() print("safe unique id is ", safeId) # Choose given number of elements from the list with different probability import random num1 =5 numberList = [111, 222, 333, 444, 555] print(random.choices(numberList, weights=(10, 20, 30, 40, 50), k=num1)) # Generate weighted random numbers import random randomList = random.choices(range(10, 40, 5), cum_weights=(5, 15, 10, 25, 40, 65), k=6) print(randomList) # generating a reliable secure random number import secrets print("Random integer number generated using secrets module is ") number = secrets.randbelow(30) print(number) # Calculate memory is being used by an list in Python import sys list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith'] print("size of list = ",sys.getsizeof(list1)) # Find if all elements in a list are identical listOne = [20, 20, 20, 20] print("All element are duplicate in listOne:", listOne.count(listOne[0]) == len(listOne)) # Merge two dictionaries in a single expression currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"} formerEmployee = {2: 'Eric', 4: "Emma"} allEmployee = {**currentEmployee, **formerEmployee} print(allEmployee) # Convert two lists into a dictionary ItemId = [54, 65, 76] names = ["Hard Disk", "Laptop", "RAM"] itemDictionary = dict(zip(ItemId, names)) print(itemDictionary) # Alternate cases in String test_str = "geeksforgeeks" res = "" for idx in range(len(test_str)): if not idx % 2 : res = res + test_str[idx].upper() else: res = res + test_str[idx].lower() print(res) # Write a Python program to validate an Email import re regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' def check(email): if(re.search(regex,email)): print("Valid Email") else: print("Invalid Email") email = "ishwarraja@gmail.com" check(email) # Write a Program to implement validation of a Password class Password: def __init__(self, password): self.password = password def validate(self): vals = { 'Password must contain an uppercase letter.': lambda s: any(x.isupper() for x in s), 'Password must contain a lowercase letter.': lambda s: any(x.islower() for x in s), 'Password must contain a digit.': lambda s: any(x.isdigit() for x in s), 'Password must be at least 8 characters.': lambda s: len(s) >= 8, 'Password cannot contain white spaces.': lambda s: not any(x.isspace() for x in s) } valid = True for n, val in vals.items(): if not val(self.password): valid = False return n return valid input_password = "Ishwar@12Su@ 1'" p = Password(input_password) if p.validate() is True: print('Password Valid') else: print(p.validate()) # 1. python function to return the nth fibonacci number def fib(n): if n <= 1: return n else: return (fib(n-1) + fib(n-2)) # 2. python function to return the factorial of a number def fact(n): if n == 1: return n else: return n * fact(n-1) # 3. python function to return the squares of a list of numbers def sq(n): return [i**2 for i in range(n)] # 3. python function to return the squareroot of a list of numbers def sqrt(n): return [i**0.5 for i in range(n)] # 4. python function to add even number from 1st list and odd number from 2nd list def even_odd(l1, l2): return[x + y for x, y in zip(l1, l2) if x % 2 ==0 and y % 2 != 0] # 5. python function to strip vowels from a string def strip_vowel_str(str): vowels = ['a', 'e', 'i', 'o', 'u'] return "".join([x for x in str if x not in vowels]) # 6. python ReLu function def relu_like_activation(l): return[0 if x < 0 else x for x in l] # 7. python sigmoid function def sigmoid_activation(l): return[round(1/(1+math.exp(-x)),2) for x in l] #8. python function to identify profane words def profane_filter(str): profane_word_url = "https://raw.githubusercontent.com/RobertJGabriel/Google-profanity-words/master/list.txt" file = urllib.request.urlopen(profane_word_url) for line in file: decoded_line = line.decode("utf-8") return decoded_line str = re.findall(r'\w+', str) return [i for i in str if i in decoded_line] # 9. python function to add even mubers in a list def add_even_num(l): sum = reduce(lambda a, b: a + b, filter(lambda a: (a % 2 == 0), l)) return sum # 10. python function to find the area of a circle def circle_area(r): return 22/7 * r**2 # 11. python program to find whether a number is prime def test_prime(n): if (n==1): return False elif (n==2): return True; else: for x in range(2,n): if(n % x==0): return False return True # 12. python function to return the cubes of a list of numbers def cube(n): return [i*i*i for i in range(n)] # 13. python function to find the average of given numbers def average(): numbers = [] def add(number): numbers.append(number) total = sum(numbers) count = len(numbers) return total/count return add a = average() a(10) a(20) a(45) # 14. python function to create adders def create_adders(): adders = [] for n in range(1, 4): adders.append(lambda x, y=n: x + y) return adders adders = create_adders() # 15. python function for datetime from datetime import datetime datetime.utcnow() def log(msg, *, dt = datetime.utcnow()): print(f'Message at {dt} was {msg}') # 16. python function for count of address reference import ctypes def ref_count(address : int): #what is int doing here? Annotations return ctypes.c_long.from_address(address).value # 17. python function to modify a tuple def modify_tuple(t): print(f'Initial t mem-add = {id(t)}') t[0].append(100) print(f'Final t mem-add = {id(t)}') # 18. python program to compare strings def compare_using_equals(n): a = 'a long string that is not intered' * 200 b = 'a long string that is not intered' * 200 for i in range(n): if a == b: pass # 19. python program to compare strings using interning import sys def compare_using_interning(n): a = sys.intern('a long string that is not intered' * 200) b = sys.intern('a long string that is not intered' * 200) for i in range(n): if a is b: pass # 20. python program to calculate the time taken to create a float and decimal import time def run_float(n = 1): for i in range(n): a = 3.1415 def run_decimal(n = 1): for i in range(n): a = Decimal('3.1415') n = 10000000 start = time.perf_counter() run_float(n) end = time.perf_counter() print ('float: ', end - start) start = time.perf_counter() run_decimal(n) end = time.perf_counter() print ('decimal: ', end - start) # 21. python function for factorial using reduce def fact(n): from operator import mul from functools import reduce return reduce(mul, range(1, n+1)) fact(10) # 22. python program to find if given co-ordinates are inside circle from random import uniform from math import sqrt def random_shot(rad): r_x = uniform(-rad, rad) r_y = uniform(-rad, rad) if sqrt(r_x**2 + r_y**2) <= rad: is_in_circle = True else: is_in_circle = False return r_x, r_y, is_in_circle # 23. python function to find the area of a circle def square_area(x): return x ** 2 # 24. python program for the sum of first n numbers. def sum_n_num(n): return n * (n + 1)/2 # 25. Python Program to Add two Lists NumList1 = [] NumList2 = [] total = [] Number = int(input("Please enter the Total Number of List Elements: ")) print("Please enter the Items of a First and Second List ") for i in range(1, Number + 1): List1value = int(input("Please enter the %d Element of List1 : " %i)) NumList1.append(List1value) List2value = int(input("Please enter the %d Element of List2 : " %i)) NumList2.append(List2value) for j in range(Number): total.append( NumList1[j] + NumList2[j]) print("\nThe total Sum of Two Lists = ", total) # 26. Python Program to find Largest and Smallest Number in a List NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) smallest = largest = NumList[0] for j in range(1, Number): if(smallest > NumList[j]): smallest = NumList[j] min_position = j if(largest < NumList[j]): largest = NumList[j] max_position = j print("The Smallest Element in this List is : ", smallest) print("The Index position of Smallest Element in this List is : ", min_position) print("The Largest Element in this List is : ", largest) print("The Index position of Largest Element in this List is : ", max_position) # 27. Python Palindrome Program using Functions reverse = 0 def integer_reverse(number): global reverse if(number > 0): Reminder = number % 10 reverse = (reverse * 10) + Reminder integer_reverse(number // 10) return reverse number = int(input("Please Enter any Number: ")) rev = integer_reverse(number) print("Reverse of a Given number is = %d" %rev) if(number == rev): print("%d is a Palindrome Number" %number) else: print("%d is not a Palindrome Number" %number) # 28. Python Program to Swap Two Numbers a = float(input(" Please Enter the First Value a: ")) b = float(input(" Please Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) temp = a a = b b = temp print("After Swapping two Number: a = {0} and b = {1}".format(a, b)) # 29. Python Program to Concatenate Strings str1 = input("Please Enter the First String : ") str2 = input("Please Enter the Second String : ") concat1 = str1 + str2 print("The Final String After Python String Concatenation = ", concat1) concat2 = str1 + ' ' + str2 print("The Final After String Concatenation with Space = ", concat2) # 30. Python Program to find Largest of Three Numbers a = float(input("Please Enter the First value: ")) b = float(input("Please Enter the First value: ")) c = float(input("Please Enter the First value: ")) if (a > b and a > c): print("{0} is Greater Than both {1} and {2}". format(a, b, c)) elif (b > a and b > c): print("{0} is Greater Than both {1} and {2}". format(b, a, c)) elif (c > a and c > b): print("{0} is Greater Than both {1} and {2}". format(c, a, b)) else: print("Either any two values or all the three values are equal") # 31. Python Program to find Diameter, Circumference, and Area Of a Circle import math def find_Diameter(radius): return 2 * radius def find_Circumference(radius): return 2 * math.pi * radius def find_Area(radius): return math.pi * radius * radius r = float(input(' Please Enter the radius of a circle: ')) diameter = find_Diameter(r) circumference = find_Circumference(r) area = find_Area(r) print("\n Diameter Of a Circle = %.2f" %diameter) print(" Circumference Of a Circle = %.2f" %circumference) print(" Area Of a Circle = %.2f" %area) # 32. Python Program to Convert String to Uppercase string = input("Please Enter your Own String : ") string1 = string.upper() print("\nOriginal String in Lowercase = ", string) print("The Given String in Uppercase = ", string1) # 33. Python Program to Calculate Simple Interest princ_amount = float(input(" Please Enter the Principal Amount : ")) rate_of_int = float(input(" Please Enter the Rate Of Interest : ")) time_period = float(input(" Please Enter Time period in Years : ")) simple_interest = (princ_amount * rate_of_int * time_period) / 100 print("\nSimple Interest for Principal Amount {0} = {1}".format(princ_amount, simple_interest)) # 34. Python Program to Map two lists into a Dictionary keys = ['name', 'age', 'job'] values = ['John', 25, 'Developer'] myDict = {k: v for k, v in zip(keys, values)} print("Dictionary Items : ", myDict) # 35. write a Python function To Calculate Volume OF Cylinder def volume(r, h): vol = 22/7 * r * r * h return vol # 36. Recursive Python function to solve the tower of hanoi def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print "Move disk 1 from source",source,"to destination",destination return TowerOfHanoi(n-1, source, auxiliary, destination) print "Move disk",n,"from source",source,"to destination",destination TowerOfHanoi(n-1, auxiliary, destination, source) n = 4 TowerOfHanoi(n,'A','B','C') Python 3 program to find time for a # given angle. # 37. python function to find angle between hour hand and minute hand def calcAngle(hh, mm): # Calculate the angles moved by # hour and minute hands with # reference to 12:00 hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm # Find the difference between # two angles angle = abs(hour_angle - minute_angle) # Return the smaller angle of two # possible angles angle = min(360 - angle, angle) return angle # 38. python function to print all time when angle between hour hand and minute # hand is theta def printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm)==theta): print(hh, ":", mm, sep = "") return print("Input angle not valid.") return # 39. write a Python program to reverse a linked list class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(85) print("Given Linked List") llist.printList() llist.reverse() print("\nReversed Linked List") llist.printList() # 40. write a Python function to Remove all duplicates from a given string def removeDuplicate(str): s=set(str) s="".join(s) print("Without Order:",s) t="" for i in str: if(i in t): pass else: t=t+i print("With Order:",t) str1="conondrum" removeDuplicate(str1) from .sin import sine from .cos import cosine from .tan import tangent from .softmax import softmax from .sigmoid import sigmoid from .tanh import tanh from .relu import ReLU from .log import log from .exp import exp from .sin import dsine from .cos import dcosine from .tan import dtangent from .sigmoid import dsigmoid from .tanh import dtanh from .log import dlog from .exp import dexp import math # 41. python function for finding cosine angle def cosine(angle): """ returns the cosine value for an angle mentioned in radians""" return math.cos(angle) # 42. python function for finding the derivative of cosine angle def dcosine(angle): """ returns the cosine value for an angle mentioned in radians""" return -math.sin(angle) # 43. python function for finding sine angle def sine(angle): """ returns the sine value for an angle mentioned in radians""" return math.sin(angle) # 44. python function for finding the derivative of sine angle def dsine(angle): """ returns the sine value for an angle mentioned in radians""" return math.cos(angle) # 45. python function for finding tangent angle def tangent(angle): """ returns the tangent value for an angle mentioned in radians""" return math.tan(angle) # 46. python function for finding the derivative of tangent angle def dtangent(angle): """ returns the tangent value for an angle mentioned in radians""" return 1/(math.cos(angle)**2) # 47. python function for finding the exponent of a number def exp(x): """returns e^x of a number""" return math.exp(x) # 48. python function for finding the derivative of exponent of a number def dexp(x): return math.exp(x) # 49. python function for finding the logarithmic value of a number def log(x): """returns the logarithmic value of a number""" return math.log(x) # 50. python function for finding the derivative of logarithmic value of a number def dlog(x): return 1/x # 51. python function for finding softmax output of a vector def softmax(x): """returns the softmax output of a vector""" if(type(x) == int or type(x) == float): return 1 denom = 0 for i in x: denom+=math.exp(i) new_vec = [] for i in x: new_vec.append(math.exp(i)/denom) return new_vec # 52. python function for finding the hyperbolic tangent value of a number def tanh(x): """ returns the hyperbolic tangent value of a number""" return math.tanh(x) # 53. python function for finding the derivative of hyperbolic tangent value of a number def dtanh(x): """ returns the hyperbolic tangent value of a number""" return 1 - (math.tanh(x)**2) # write a python function to check if a given string is a palindrome def isPalindrome(s): return s == s[::-1] # write a python function to check if a given string is symmetrical def symmetry(a): n = len(a) flag = 0 if n%2: mid = n//2 +1 else: mid = n//2 start1 = 0 start2 = mid while(start1 < mid and start2 < n): if (a[start1]== a[start2]): start1 = start1 + 1 start2 = start2 + 1 else: flag = 1 break return flag # write a function to reverse words of string def rev_sentence(sentence): words = sentence.split(' ') reverse_sentence = ' '.join(reversed(words)) return reverse_sentence # write a program to check if a substring is present in a given string string = "how are you?" substring = "are" if (string.find(substring) == -1): print("NO") else: print("YES") # write a program to print length of a string str1 = "great way to learn!" print(len(str1)) # write a program to print words frequncy in a given string test_str = "It is a great meal at a great restaurant on a great day" print("Original String: " + str(test_str)) res = {key: test_str.count(key) for key in test_str.split()} print("The words frequency: " + str(res)) # write a program to print even length words in a string str1 = "I am doing fine" s = str1.split(' ') for word in s: if len(word)%2==0: print(word) # write a program to accept the strings which contains all vowels str1 = "__main__" if len(set(str1).intersection("AEIOUaeiou"))>=5: print('accepted') else: print("not accepted") # write a program to print count of number of unique matching characters in a pair of strings str1="ababccd12@" str2="bb123cca1@" matched_chars = set(str1) & set(str2) print("No. of matching characters are : " + str(len(matched_chars)) ) # write a program to remove all duplicate characters from a string str1 = "what a great day!" print("".join(set(str1))) # write a program to print least frequent character in a string str1="watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print("Minimum of all characters is: " + str(res)) # write a program to print maximum frequency character in a string str1 = "watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = max(all_freq, key = all_freq.get) print("Maximum of all characters is: " + str(res)) # write a program to find and print all words which are less than a given length in a string str1 = "It is wonderful and sunny day for a picnic in the park" str_len = 5 res_str = [] text = str1.split(" ") for x in text: if len(x) < str_len: res_str.append(x) print("Words that are less than " + str(str_len) + ": " + str(res_str)) # write a program to split and join a string with a hyphen delimiter str1 = "part of speech" delimiter = "-" list_str = str1.split(" ") new_str = delimiter.join(list_str) print("Delimited String is: " + new_str) # write a program to check if a string is binary or not str1="01110011 a" set1 = set(str1) if set1 == {'0','1'} or set1 == {'0'} or set1 == {'1'}: print("string is binary") else: print("string is not binary") # write a function to remove i-th indexed character in a given string def remove_char(string, i): str1 = string[ : i] str2 = string[i + 1: ] return str1 + str2 # write a function to find all urls in a given string import re def find_urls(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # write a function to find uncommon words from two strings def UncommonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] == 1] # write a function to find common words from two strings def commonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] > 1] # write a program to replace duplicate word occurence in String str1 = "IISC is the best. IISC has Classes in the evening for professionals. Classes help to learn new things." repl_dict = {'IISC':'It', 'Classes': 'They'} str_list = str1.split(' ') res = set() for idx, ele in enumerate(str_list): if ele in repl_dict: print(str(idx) + ' '+ele) if ele in res: str_list[idx] = repl_dict[ele] else: res.add(ele) res = ' '.join(str_list) print("Replaced String: " + str(res)) # write a program to replace multiple words with a single word str1 = 'CoffeeDay is best for coffee and having long conversations' word_list = ["best", 'long'] repl_word = 'good' res = ' '.join([repl_word if idx in word_list else idx for idx in str1.split()]) print("String after multiple replace : " + str(res)) # write a function to rotate string left by a given length def rotate_left(input,d): Lfirst = input[0 : d] Lsecond = input[d :] return (Lsecond + Lfirst) # write a function to rotate string right by a given length def rotate_right(input,d): Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] return (Rsecond + Rfirst) # write a function to replace all occurances of a substring in a string str1 = "Hello! It is a Good thing" substr1 = "Good" substr2 = "bad" replaced_str = str1.replace(substr1, substr2) print("String after replace :" + str(replaced_str)) # write a program to move numbers to the end of a string str1 = 'hi 123 how are you doing? 567 is with you. Take care of 89' res = '' dig = '' for ele in str1: if ele.isdigit(): dig += ele else: res += ele res += dig print("Strings after digits at end : " + str(res)) # write a program to count characters surrounding vowels str1 = 'week after week the numbers are increasing' res = 0 vow_list = ['a', 'e', 'i', 'o', 'u'] for idx in range(1, len(str1) - 1): if str1[idx] not in vow_list and (str1[idx - 1] in vow_list or str1[idx + 1] in vow_list): res += 1 if str1[0] not in vow_list and str1[1] in vow_list: res += 1 if str1[-1] not in vow_list and str1[-2] in vow_list: res += 1 print("Characters around vowels count : " + str(res)) # write a function that return space count def count_space(str1): count = 0 for i in range(0, len(str1)): if str1[i] == " ": count += 1 return count # write a program to break up string into individual elements str1 = "whatisthis" split_string = list(''.join(str1)) print(split_string) # write a program to extract string of N size and having K distict characters str1 = 'GoodisalwaysGoood' N = 3 K = 2 res = [] for idx in range(0, len(str1) - N + 1): if (len(set(str1[idx: idx + N])) == K): res.append(str1[idx: idx + N]) print("Extracted Strings : " + str(res)) # write a program to increment number which is at end of string import re str1 = 'count001' res = re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", str1) print("Incremented numeric String : " + str(res)) # write a program to calculate and print number of letters and digits in a string str1 = "python1234" total_digits = 0 total_letters = 0 for s in str1: if s.isnumeric(): total_digits += 1 else: total_letters += 1 print("Total letters found : ", total_letters) print("Total digits found : ", total_digits) # write a function to check if a lower case letter exists in a given string def check_lower(str1): for char in str1: k = char.islower() if k == True: return True if(k != 1): return False # write a function to check if a upper case letter exists in a given string def check_upper(str1): for char in str1: k = char.isupper() if k == True: return True if(k != 1): return False # write a program to print number of words in a string str1 = 'It is a glorious day' res = len(str1.split()) print("The number of words in string are : " + str(res)) # write a program to print number of characters in a string str1 = 'It is a glorious day' res = len(str1) print("The number of characters in string are : ", str(res)) # write a funtion that accepts two lists of equal length and converts them into a dictioinary def list_to_dict(list1, list2): return dict(zip(list1, list2)) # write a python function that accepts a list of dictionaries and sorts it by a specified key def sort_dict_list(dict_list, sort_key): dict_list.sort(key=lambda item: item.get(sort_key)) # write a program to print the longest key in a dictioinary dict_1 = {"key1": 10, "keeeey2": 2, "ky3": 30} max_key='' for key in dict_1: if len(key)>len(max_key): max_key=key print(max_key) # write a program to capitalize the first and last character of each key in a dictionary input_dict = {'key_a': 10, 'kEy': 2, 'Key_B': 13} for key in list(input_dict.keys()): new_key = key[0].upper() + key[1:-1] + key[-1].upper() input_dict[new_key] = input_dict[key] if key != new_key: del input_dict[key] # write a program that iterates over a dictionary and prints "Bingo!" if length of value is greater than the length of key. Otherwise print "no bingo" key_val_map = {"key1": "length1", "key2": "len2", "Hello": "hi", "bingo": "print bingo"} for key, val in key_val_map.items(): if len(val) > len(key): print("Bingo!") else: print("no bingo") # write a python function that accepts a dictionary that has unique values and returns its inversion def invert_dict(input_dict): my_inverted_dict = {value: key for key, value in input_dict.items()} return my_inverted_dict # write a function that inverts a dictionary with non-unique values. Keys that map to the same values should be appended to a list in the inverted dictionary def invert_dict_non_unique(my_dict): my_inverted_dict = dict() for key, value in my_dict.items(): my_inverted_dict.setdefault(value, list()).append(key) return my_inverted_dict # write a program to merge a list of dictionaries into a single dictionary using dictionary comprehension input = [{"foo": "bar", "Hello": "World"}, {"key1": "val1", "key2": "val2"}, {"sample_key": "sample_val"}] merged_dict = {key: value for d in input for key, value in d.items()} # write a function to return the mean difference in the length of keys and values of dictionary comprising of strings only. def mean_key_val_diff(input_dict): sum_diff = 0 for key, val in input_dict.items(): sum_diff += abs(len(val) - len(key)) return sum_diff/len(input_dict) # write a program that prints the number of unique keys in a list of dictionaries. list_of_dicts = [{"key1": "val1", "Country": "India"}, {"Country": "USA", "foo": "bar"}, {"foo": "bar", "foo2":"bar2"}] unique_keys = [] for d in list_of_dicts: for key in d: if key not in unique_keys: unique_keys.append(key) print(f"Number of unique keys: {len(unique_keys)}") # write a Python program to replace the value of a particular key with nth index of value if the value of the key is list. test_list = [{'tsai': [5, 3, 9, 1], 'is': 8, 'good': 10}, {'tsai': 1, 'for': 10, 'geeks': 9}, {'love': 4, 'tsai': [7, 3, 22, 1]}] N = 2 key = "tsai" for sub in test_list: if isinstance(sub[key], list): sub[key] = sub[key][N] # write a program to convert a dictionary value list to dictionary list and prints it. test_list = [{'END' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}] res =[{} for idx in range(len(test_list))] idx = 0 for sub in test_list: for key, val in sub.items(): for ele in val: res[idx][key] = ele idx += 1 idx = 0 print("Records after conversion : " + str(res)) # write a program to convert a list of dictionary to list of tuples and print it. ini_list = [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] temp_dict = {} result = [] for ini_dict in ini_list: for key in ini_dict.keys(): if key in temp_dict: temp_dict[key] += ini_dict[key] else: temp_dict[key] = ini_dict[key] for key in temp_dict.keys(): result.append(tuple([key] + temp_dict[key])) print("Resultant list of tuples: {}".format(result)) # write a program that categorizes tuple values based on second element and prints a dictionary value list where each key is a category. test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)] res = {} for i, j in test_list: res.setdefault(j, []).append(i) print("The dictionary converted from tuple list : " + str(res)) # write a Python3 program that prints a index wise product of a Dictionary of Tuple Values test_dict = {'END Program' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)} prod_list=[] for x in zip(*test_dict.values()): res = 1 for ele in x: res *= ele prod_list.append(res) res = tuple(prod_list) print("The product from each index is : " + str(res)) # write a program to Pretty Print a dictionary with dictionary values. test_dict = {'tsai' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}} print("The Pretty Print dictionary is : ") for sub in test_dict: print(f"\n{sub}") for sub_nest in test_dict[sub]: print(sub_nest, ':', test_dict[sub][sub_nest]) # write a program to sort a nested dictionary by a key and print the sorted dictionary test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17}, 'Akshat' : {'roll' : 54, 'marks' : 12}, 'Akash' : { 'roll' : 12, 'marks' : 15}} sort_key = 'marks' res = sorted(test_dict.items(), key = lambda x: x[1][sort_key]) print("The sorted dictionary by marks is : " + str(res)) # write a python function to combine three lists of equal lengths into a nested dictionary and return it def lists_to_dict(test_list1, test_list2, test_list3): res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)] return res # write a program to print keys in a dictionary whose values are greater than a given input. test_dict = {'tsai' : 4, 'random_key' : 2, 'foo' : 3, 'bar' : 'END'} K = 3 res = {key : val for key, val in test_dict.items() if type(val) != int or val > K} print("Values greater than K : ", res.keys()) # write a function that converts a integer dictionary into a list of tuples. def dict_to_tuple(input_dict): out_tuple = [(a, b) for a,b in input_dict.items()] return out_tuple # write a python function to return a flattened dictionary from a nested dictionary input def flatten_dict(dd, separator ='_', prefix =''): flattened = { prefix + separator + k if prefix else k : v for kk, vv in dd.items() for k, v in flatten_dict(vv, separator, kk).items() } if isinstance(dd, dict) else { prefix : dd } return flattened # write a program that prints dictionaries having key of the first dictionary and value of the second dictionary test_dict1 = {"tsai" : 20, "is" : 36, "best" : 100} test_dict2 = {"tsai2" : 26, "is2" : 19, "best2" : 70} keys1 = list(test_dict1.keys()) vals2 = list(test_dict2.values()) res = dict() for idx in range(len(keys1)): res[keys1[idx]] = vals2[idx] print("Mapped dictionary : " + str(res)) # write a program to combine two dictionaries using a priority dictionary and print the new combined dictionary. test_dict1 = {'Gfg' : 1, 'is' : 2, 'best' : 3} test_dict2 = {'Gfg' : 4, 'is' : 10, 'for' : 7, 'geeks' : 12} prio_dict = {1 : test_dict2, 2: test_dict1} res = prio_dict[2].copy() for key, val in prio_dict[1].items(): res[key] = val print("The dictionary after combination : " + str(res)) # write a Python program to combine two dictionary by adding values for common keys dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass # write a Python program that sorts dictionary keys to a list using their values and prints this list. test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3} res = list(sum(sorted(test_dict.items(), key = lambda x:x[1]), ())) print("List after conversion from dictionary : ", res) # write a program to concatenate values with same keys in a list of dictionaries. Print the combined dictionary. test_list = [{'tsai' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, {'tsai' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, {'tsai' : [7, 5], 'best' : [5, 7]}] res = dict() for inner_dict in test_list: for inner_list in inner_dict: if inner_list in res: res[inner_list] += (inner_dict[inner_list]) else: res[inner_list] = inner_dict[inner_list] print("The concatenated dictionary : " + str(res)) # write a python program to print the top N largest keys in an integer dictionary. test_dict = {6 : 2, 8: 9, 3: 9, 10: 8} N = 4 res = [] for key, val in sorted(test_dict.items(), key = lambda x: x[0], reverse = True)[:N]: res.append(key) print("Top N keys are: " + str(res)) # write a program to print the values of a given extraction key from a list of dictionaries. test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}] K = 'Best' res = [sub[K] for sub in test_list if K in sub][0] print("The extracted value : " + str(res)) # write a program to convert date to timestamp and print the result import time import datetime str1 = "20/01/2020" element = datetime.datetime.strptime(str1,"%d/%m/%Y") timestamp = datetime.datetime.timestamp(element) print(timestamp) # write a program to print the product of integers in a mixed list of string and numbers test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2] res = 1 for ele in test_list: try: res *= int(ele) except : pass print("Product of integers in list : " + str(res)) # write a python program to add an element to a list. Print the final list. lst = ["Jon", "Kelly", "Jessa"] lst.append("Scott") print(lst) # write a python function to append all elements of one list to another def extend_list(list1, list2): list1 = [1, 2] list2 = [3, 4] return list1.extend(list2) # write a python function to add elements of two lists def add_two_lists(list1, list2): list1 = [1, 2, 3] list2 = [4, 5, 6] sum_list = [] for (item1, item2) in zip(list1, list2): sum_list.append(item1+item2) return sum_list # Write a python program to print the last element of a list list1 = ['p','r','o','b','e'] print(list1[-1]) # Write a python program to print positive Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num >= 0: print(num, end = " ") # Write a python function to multiply all values in a list def multiplyList(myList) : result = 1 for x in myList: result = result * x return result # Write a python program to print the smallest number in a list list1 = [10, 20, 1, 45, 99] print("Smallest element is:", min(list1)) # Write a python program to remove even numbers from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] for ele in list1: if ele % 2 == 0: list1.remove(ele) print("New list after removing all even numbers: ", list1) # Write a python program to print a list after removing elements from index 1 to 4 list1 = [11, 5, 17, 18, 23, 50] del list1[1:5] print(*list1) # Write a python program to remove 11 and 18 from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] unwanted_num = {11, 18} list1 = [ele for ele in list1 if ele not in unwanted_num] print("New list after removing unwanted numbers: ", list1) # Write a python program to Remove multiple empty spaces from List of strings. Print the original and final lists. test_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] print("The original list is : " + str(test_list)) res = [ele for ele in test_list if ele.strip()] print("List after filtering non-empty strings : " + str(res)) # Write a python function to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Write a python program to print if a string "hello" is present in the list l = [1, 2.0, 'hello','have', 'a', 'good', 'day'] s = 'hello' if s in l: print(f'{s} is present in the list') else: print(f'{s} is not present in the list') # Write a python program to print the distance between first and last occurrence of even element. test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11] indices_list = [idx for idx in range( len(test_list)) if test_list[idx] % 2 == 0] res = indices_list[-1] - indices_list[0] print("Even elements distance : " + str(res)) # Write a python fuction to create an empty list def emptylist(): return list() # Write a python program to print a list with all elements as 5 and of length 10 list1 = [5] * 10 print(list1) # Write a python program to reverse a list and print it. def Reverse(lst): return [ele for ele in reversed(lst)] lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst)) # Write a python program to print odd numbers in a List list1 = [10, 21, 4, 45, 66, 93, 11] odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) # Write a python program to print negative Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num < 0: print(num, end = " ") # Write a python program print the the number of occurrences of 8 in a list def countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print('{} has occurred {} times'.format(x, countX(lst, x))) # Write a python program to swap first and last element of a list . Print the final list def swapList(newList): size = len(newList) # Swapping temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList newList = [12, 35, 9, 56, 24] print(swapList(newList)) # Write a python program to convert each list element to key-value pair. Print the final dictionary test_list = [2323, 82, 129388, 234, 95] print("The original list is : " + str(test_list)) res = dict() for ele in test_list: mid_idx = len(str(ele)) // 2 key = int(str(ele)[:mid_idx]) val = int(str(ele)[mid_idx:]) res[key] = val print("Constructed Dictionary : " + str(res)) # Write a python program for print all elements with digit 7. test_list = [56, 72, 875, 9, 173] K = 7 res = [ele for ele in test_list if str(K) in str(ele)] print("Elements with digit K : " + str(res)) # Write a python program for printing number of unique elements in a list input_list = [1, 2, 2, 5, 8, 4, 4, 8] l1 = [] count = 0 for item in input_list: if item not in l1: count += 1 l1.append(item) print("No of unique items are:", count) # Write a python program to find the sum and average of the list. Print the sum and average L = [4, 5, 1, 2, 9, 7, 10, 8] count = 0 for i in L: count += i avg = count/len(L) print("sum = ", count) print("average = ", avg) # Write a python program to Remove Tuples of Length 1 from a list of tuples. Print the final list. test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] K = 1 res = [ele for ele in test_list if len(ele) != K] print("Filtered list : " + str(res)) # Write a python program to print a list of tuples from given list having number and its cube in each tuple list1 = [1, 2, 5, 6] res = [(val, pow(val, 3)) for val in list1] print(res) # Write a python program to print the combination of tuples in list of tuples test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] res = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] print("The list tuple combination : " + str(res)) # Write a python program to swap tuple elements in list of tuples. Print the output. test_list = [(3, 4), (6, 5), (7, 8)] res = [(sub[1], sub[0]) for sub in test_list] print("The swapped tuple list is : " + str(res)) # Write a python function to sort a list of tuples by the second Item def Sort_Tuple(tup): lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Write a python program to print all pair combinations of 2 tuples. test_tuple1 = (4, 5) test_tuple2 = (7, 8) res = [(a, b) for a in test_tuple1 for b in test_tuple2] res = res + [(a, b) for a in test_tuple2 for b in test_tuple1] print("The filtered tuple : " + str(res)) # Write a python program to print positive Tuples in List. test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] print("The original list is : " + str(test_list)) res = [sub for sub in test_list if all(ele >= 0 for ele in sub)] print("Positive elements Tuples : " + str(res)) # Write a python program to join Tuples from a list of tupels if they have similar initial element. Print out the output test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)] print("The original list is : " + str(test_list)) res = [] for sub in test_list: if res and res[-1][0] == sub[0]: res[-1].extend(sub[1:]) else: res.append([ele for ele in sub]) res = list(map(tuple, res)) print("The extracted elements : " + str(res)) # Write a python program to print the uncommon elements in List test_list1 = [ [1, 2], [3, 4], [5, 6] ] test_list2 = [ [3, 4], [5, 7], [1, 2] ] res_list = [] for i in test_list1: if i not in test_list2: res_list.append(i) for i in test_list2: if i not in test_list1: res_list.append(i) print ("The uncommon of two lists is : " + str(res_list)) # write a Function to convert the time from 12 hour format to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] # write a python program to multiply three numbers num1 = 1.5 num2 = 6.3 num3 = -2.3 product = num1 * num2 * num3 print(f'Product: {product}') # write a python function that when given two numbers, would divide the first number by second number and return the quotient and remainder def divide_first_number_by_second(num1, num2): return (num1 // num2), (num1 % num2) # write a python function to return the largest and smallest numbers in the given list and return None if the list is empty def largest_and_smallest(list_of_nums): if list_of_nums: return max(list_of_nums), min(list_of_nums) else: return # write a python function that would read the given input file path and print its contents def read_and_print_file(filepath): with open(filepath, "r") as infile: print( infile.read() ) # write a python program that would print the first n positive integers using a for loop n = 62 for num in range(n): print(num) # write a python function that returns the input list sorted in ascending order def sort_ascending(list_to_be_sorted): return sorted(list_to_be_sorted) # write a python function that returns the input list sorted in descending order def sort_descending(list_to_be_sorted): return sorted(list_to_be_sorted, reverse=True) # write a python function that would return the sum of first n natural numbers, where n is the input def sum_first_n(n): return ( n * (n+1) ) // 2 # write a recursive python function that would return the sum of first n natural numbers, where n is the input def sum_first_n_recursive(n): if n == 0: return 0 return sum_first_n_recursive(n-1) + n # write a python function that would filter a list of dictionaries where a specified key equals given value, list_of_dictionaries, key and value are inputs to this function. def filter_with_key_value(list_of_dicts, key, value): return list( filter( lambda x: x.get(key) == value, list_of_dicts ) ) # write a recursive python function that takes either a list or tuple as input and reverses the order of its elements def reverse(seq): SeqType = type(seq) emptySeq = SeqType() if seq == emptySeq: return emptySeq restrev = reverse(seq[1:]) first = seq[0:1] result = restrev + first return result # write a python function that returns the square of a given input number def square(x): return x**2 # write a python function that performs selection sort on the given list or tuple or string and returns the new sorted sequence def selection_sort(list_to_be_sorted): sorted_list = list_to_be_sorted[:] for i in range(len(sorted_list)): new_min = sorted_list[i] new_min_old_place = i for j in range(i+1, len(sorted_list)): if new_min > sorted_list[j]: new_min = sorted_list[j] new_min_old_place = j old_val = sorted_list[i] sorted_list[i] = new_min sorted_list[new_min_old_place] = old_val return sorted_list # write a python program that asks for user input and prints the given input a = input("User Input") print(a) # write a python function shifts and scales all numbers in the given list by the given mean and standard deviation def shift_and_scale(list_of_nums, mean, std): return [ (x-mean) / std for x in list_of_nums ] # write a python function that takes in a list of sequences and zips each corresponding element from the list into a tuple and returns the list of such tuples def zip_(list_of_seq): return list(zip(*list_of_seq)) # write a python program that asks user to guess a number between 1 and 5 and guess it within 3 guesses print("Please guess a number between 1 and 5 and I will guess within 3 chances!") guess1 = input("Is it <= 3? enter y/n \n") if guess1 == "y": guess2 = input("Is it <= 2? enter y/n \n") if guess2 == "y": guess3 = input("Is it 1? enter y/n \n") if guess3 == "y": print("Yay! found the number, its 1") else: print("Yay! found the number, its 2") else: print("Yay! found the number, its 3") else: guess2 = input("Is it 4? enter y/n \n") if guess2 == "y": print("Yay! found the number, its 4") else: print("Yay! found the number, its 5") # write python program that would merge two dictionaries by adding the second one into the first a = {"a": 1, "b": 3} b = {"c": 1, "d": 3} a.update(b) # write a python function that would reverse the given string def reverse_string(str_to_be_reversed): return str_to_be_reversed[::-1] # write a python program that would print "Hello World" print("Hello World") # write a python program that would swap variable values a = 10 b = 15 a, b = b, a # write a python program that iterates over a dictionary and prints its keys and values a = {"a":1, "b":2, "c":3, "d":4} for k, v in a.items(): print(k, v) # write a python function that would print the ASCII value of a given character def print_ascii(char): print(ord(char)) # write a python function that takes in two numbers and returns their HCF def hcf(num1, num2): smaller = num1 if num1 < num2 else num2 for i in range(1, smaller+1): if (num1 % i == 0) and (num2 % i == 0): hcf = i return hcf # write a python function that takes in two numbers and returns their LCM def lcm(num1, num2): bigger = num1 if num1 > num2 else num2 while True: if (bigger % num1 == 0) and (bigger % num2 == 0): break bigger += 1 return bigger # write a recursive python function to calculate sum of natural numbers upto n, where n is an argument def recursive_sum(n): if n <= 1: return n else: return n + recursive_sum(n-1) # write a python function that deletes the last element of a list and returns the list and the deleted element def delete_last_element(list_to_be_processed): deleted_element = list_to_be_processed.pop() return list_to_be_processed, deleted_element # write a python function that takes in a list and returns a list containing the squares of the elements of the input list def square_list_elements(list_to_be_squared): return list( map(lambda x: x**2, list_to_be_squared) ) # write a python function that finds square roots of a given number, if the square root is an integer, else returns the message "Error - the square root is not an integer" def find_integer_square_roots(num): found = False for k in range(1, (num//2)+1): if ((k**2)==num): found = True break if not found: return "Error - the square root is not an integer" return -k, k # write a python program that prints out natural numbers less than or equal to the given number using a while loop input_num = 27 while input_num: print(input_num) input_num -= 1 # write a python function that takes two numbers. The function divides the first number by the second and returns the answer. The function returns None, if the second number is 0 def divide(num1, num2): if num2 == 0: return else: return num1 / num2 # write a python program uses else with for loop seq = "abcde" for k in seq: if k == "f": break else: print("f Not Found!") # write a recursive python function that performs merge sort on the given list or tuple or string and returns the new sorted sequence def sort_and_merge(l1, l2): new_list = [] i = 0 j = 0 l1_len = len(l1) l2_len = len(l2) while (i <= l1_len-1) and (j <= l2_len-1): if l1[i] < l2[j]: new_list.append(l1[i]) i +=1 else: new_list.append(l2[j]) j +=1 if i <= (l1_len-1): new_list += l1[i:] if j <= (l2_len-1): new_list += l2[j:] return new_list def recursive_merge_sort(list_to_be_sorted): final_list = [] first = 0 last = len(list_to_be_sorted) if last <= 1: final_list.extend( list_to_be_sorted ) else: mid = last // 2 l1 = recursive_merge_sort( list_to_be_sorted[:mid] ) l2 = recursive_merge_sort( list_to_be_sorted[mid:] ) final_list.extend( sort_and_merge( l1, l2 ) ) return final_list # Write a function to return the mean of numbers in a list def cal_mean(num_list:list)->float: if num_list: return sum(num_list)/len(num_list) else: return None # Write a function to return the median of numbers in a list def cal_median(num_list:list)->float: if num_list: if len(num_list)%2 != 0: return sorted(num_list)[int(len(num_list)/2) - 1] else: return (sorted(num_list)[int(len(num_list)/2) - 1] + sorted(num_list)[int(len(num_list)/2)])/2 else: return None # Write a function to return the area of triangle by heros formula def cal_triangle_area(a:float,b:float,c:float)->float: if a or b or c: s = (a+b+c)/2 if s>a and s>b and s>c: area = (s*(s-a)*(s-b)*(s-c))**(1/2) return round(area,2) else: return None return None # Write a function to return the area of a equilateral triangle def cal_eq_triangle_area(a:float)->float: if a: return (3**(1/2))*(a**2)/4 else: return None # Write a function to return the area of a right angle triangle def cal_rt_triangle_area(base:float,height:float)->float: if base and height: return (base*height)/2 else: return None # Write a function to return the cartisian distance of a point from origin def cal_dist_from_orign(x:float,y:float)->float: return (x**2+y**2)**(1/2) # Write a function to return the cartisian distance between two points def cal_cart_distance(x1:float,y1:float,x2:float,y2:float)->float: return ((x1-x2)**2+(y1-y2)**2)**(1/2) # Write a function to return the type roots of a quadratic equation ax**2 + bx + c = 0 def root_type(a:float,b:float,c:float): if b**2-4*a*c >= 0: return 'real' else: return 'imaginary' # Write a function to return the sum of the roots of a quadratic equation ax**2 + bx + c = 0 def sum_of_roots(a:float,c:float): if a: return c/a else: return None # Write a function to return the product of the roots of a quadratic equation ax**2 + bx + c = 0 def prod_of_roots(a:float,b:float): if a: return -b/a else: return None # Write a function to return the real of the roots of a quadratic equation else return None ax**2 + bx + c = 0 def roots_of_qad_eq(a:float,b:float,c:float): d = b**2-4*a*c if d >= 0: return (-b+(d)**(1/2))/2*a,(-b-(d)**(1/2))/2*a else: return None # Write a function to return the profit or loss based on cost price and selling price def find_profit_or_loss(cp,sp): if cp > sp: return 'loss', cp-sp elif cp < sp: return 'profit', sp-cp else: return 'no profit or loss', 0 # Write a function to return the area of a rectangle def cal_area_rect(length, breadth): return length*breadth # Write a function to return the area of a square def cal_area_square(side): return side**2 # Write a function to return the area of a rhombus with diagonals q1 and q2 def cal_area_rhombus(q1,q2): return (q1*q2)/2 # Write a function to return the area of a trapezium with base a base b and height h between parallel sides def cal_area_trapezium(a,b,h): return h*(a+b)/2 # Write a function to return the area of a circle of raidus r def cal_area_circle(r): pi = 3.14 return pi*r**2 # Write a function to return the circumference of a circle def cal_circumference(r): pi = 3.14 return 2*pi*r # Write a function to return the perimeter of a rectangle def cal_perimeter_rect(length, bredth): return 2*(length+bredth) # Write a function to return the perimeter of a triangle def cal_perimeter_triangle(s1,s2,s3): return s1+s2+s3 # Write a function to return the perimeter of a square def cal_perimeter_square(side): return 4*side # Write a function to return the perimeter of an equilateral triangle def cal_perimeter_eq_triangle(a): return 3*a # Write a function to return the perimeter of a isoscales triangle def cal_perimeter_iso_triangle(s1,s2): return 2*s1+s2 # Write a function to return the area of an ellipse def cal_area_ellipse(minor, major): pi = 3.14 return pi*(minor*major) # Write a function to return the lateral surface area of a cylinder def cal_cylinder_lat_surf_area(height,radius): pi=3.14 return 2*pi*radius*height # Write a function to return the curved surface area of a cone def cal_cone_curved_surf_area(slant_height,radius): pi=3.14 return pi*radius*slant_height # Write a function to return the total surface area of a cube of side a def cal_surface_area_cube(a): return 6*(a**2) # Write a function to return the total surface area of a cuboid of length l, bredth b and height h def cal_surface_area_cuboid(l,b,h): return 2*(l*b+b*h+h*l) # Write a function to return the surface area of a sphere def cal_area_sphere(radius): pi = 3.14 return 4*pi*(radius**2) # Write a function to return the surface area of a hemi-sphere def cal_area_hemisphere(radius): pi = 3.14 return 2*pi*(radius**2) # Write a function to return the total surface area of a cylinder def cal_cylinder_surf_area(height,radius): pi=3.14 return 2*pi*radius**2*+2*pi*radius*height # Write a function to return the lateral surface area of a cone def cal_cone_lateral_surf_area(height,radius): pi=3.14 return pi*radius*(((height**2)+(radius**2))**(1/2)) # Write a function to return the volume of a cylinder def cal_cylinder_volume(height, radius): pi=3.14 return pi*(radius**2)*height # Write a function to return the volume of a cone def cal_cone_volume(height,radius): pi=3.14 return pi*(radius**2)*height/3 # Write a function to return the volume of a hemi sphere def cal_hemisphere_volume(radius:float)->float: pi=3.14 return (2/3)*pi*(radius**3) # Write a function to return the volume of a sphere def cal_sphere_volume(radius:float)->float: pi=3.14 return (4/3)*pi*(radius**3) # Write a function to return the volume of a cuboid def cal_cuboid_volume(length:float, breadth:float, height:float)->float: return length*breadth*height # Write a function to return the volume of a cube def cal_cube_volume(side:float)->float: return side**3 # Write a function to return the speed of moving object based of distance travelled in given time def cal_speed(distance:float,time:float)->float: return distance/time # Write a function to return the distance covered by a moving object based on speend and given time def cal_distance(time:float,speed:float)->float: return time*speed # Write a function to return the time taken by a given of moving object based of distance travelled in given time def cal_time(distance:float,speed:float)->float: return distance/speed # Write a function to return the torque when a force f is applied at angle thea and distance for axis of rotation to place force applied is r def cal_torque(force:float,theta:float,r:float)->float: import math return force*r*math.sin(theta) # Write a function to return the angualr veolcity based on augualr distance travelled in radian unit and time taken def cal_angular_velocity(angular_dist:float,time:float)->float: return angular_dist/time # Write a function to calculate the focal length of a lense buy the distance of object and distance of image from lense def cal_focal_length_of_lense(u:float,v:float)->float: return (u*v)/(u+v) # Write a function to calculate the gravitational force between two objects of mass m1 and m2 and distance of r between them def cal_gforce(mass1:float,mass2:float, distance:float)->float: g = 6.674*(10)**(-11) return (g*mass1*mass2)/(distance**2) # Write a function to calculate the current in the curcit where the resistance is R and voltage is V def cal_current(resistance:float, voltage:float)->float: return voltage/resistance # Write a function to calculate the total capacitance of capacitors in parallel in a given list def cal_total_cap_in_parallel(cap_list:list)->float: return sum(cap_list) # Write a function to calculate the total resistance of resistances in parallel in a given list def cal_total_res_in_parallel(res_list:list)->float: return sum([1/r for r in res_list]) # Write a function to calculate the total resistance of resistances in series in a given list def cal_total_res_in_series(res_list:list)->float: return sum(res_list) # Write a function to calculate the moment of inertia of a ring of mass M and radius R def cal_mi_ring(mass:float,radius:float)->float: return mass*(radius**2) # Write a function to calculate the moment of inertia of a sphere of mass M and radius R def cal_mi_sphere(mass:float,radius:float)->float: return (7/5)*mass*(radius**2) # Write a function to calculate the pressure P of ideal gas based on ideal gas equation - Volume V, and Temperatue T are given def find_pressure_of_ideal_gas(volume:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/volume # Write a function to calculate the volume V of ideal gas based on ideal gas equation Pressure P and Tempreature T given def find_volume_of_ideal_gas(pressure:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/pressure # Write a function to calculate the Temprature T of ideal gas based on ideal gas equation Pressure P and Volume V given def find_temp_of_ideal_gas(pressure:float, volume:float,n:float)->float: r = 8.3145 # gas constant R return (pressure*volume)/n*r # Write a function to calculate the velocity of an object with initial velocity u, time t and acceleration a def cal_final_velocity(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity + accelration*time # Write a function to calculate the displacement of an object with initial velocity u, time t and acceleration a def cal_displacement(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity*time + .5*accelration*(time)**2 # Write a function to calculate amount of radioactive element left based on initial amount and half life def cal_half_life(initail_quatity:float, time_elapsed:float, half_life:float)->float: return initail_quatity*((1/2)**(time_elapsed/half_life)) # Write a function to calculate the new selling price based on discount percentage def cal_sp_after_discount(sp:float,discount:float)->float: return sp*(1 - discount/100) # Write a function to calculate the simple interest for principal p, rate r and time in years y def get_si(p:float, r:float, t:float)->float: return (p*r*t)/100 # Write a function to calculate the compound interest for principal p, rate r and time in years y def get_ci(p:float, r:float, t:float, n:float)->float: return round(p*((1+(r/(n*100)))**(n*t)) - p,2) # Write a function to calculate the energy released by converting mass m in kg to energy def cal_energy_by_mass(mass:float)->float: c = 300000 return mass * (c**2) # Write a function to calculate the kinetic energy of an object of mass m and velocity v def cal_ke(mass:float,velocity:float)->float: return (mass*(velocity)**2)/2 # Write a function to calculate the potential energy of an object of mass m at height h def cal_pe(mass:float,height:float)->float: g = 9.8 return (mass*g*height) # Write a function to calculate the electrostatic force between two charged particles with charge q1 and q2 at a distance d apart def cal_electrostatic_force(q1,q2,d): k = 9*(10**9) return (k*q1*q2)/(d**2) # Write a function to calculate the density given mass and volume def cal_density(mass,volume): return (mass/volume) # Write a function to convert the temprature celsius 'c' to fahrenheit 'f' or fahrenheit to celsius def temp_converter(temp,temp_given_in = 'f'): # Return the converted temprature if temp_given_in.lower() == 'f': # Convert to C return (temp - 32) * (5/9) else: # Convert to F return (temp * 9/5) + 32 # Write a function to merge dictionaries def merge1(): test_list1 = [{"a": 1, "b": 4}, {"c": 10, "d": 15}, {"f": "gfg"}] test_list2 = [{"e": 6}, {"f": 3, "fg": 10, "h": 1}, {"i": 10}] print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) for idx in range(0, len(test_list1)): id_keys = list(test_list1[idx].keys()) for key in test_list2[idx]: if key not in id_keys: test_list1[idx][key] = test_list2[idx][key] print("The Merged Dictionary list : " + str(test_list1)) # Write a function for vertical concatenating of a matrix def vertical_concatenation(): test_list = [["this","is"], ["program", "for"], ["vertical","concatenation"]] print("The original list : " + str(test_list)) res = [] N = 0 while N != len(test_list): temp = '' for idx in test_list: try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] print("List after column Concatenation : " + str(res)) vertical_concatenation() # Write a function to Get Kth Column of Matrix def kth_column(test_list=[[4, 5, 6], [8, 1, 10], [7, 12, 5]],k=2): print("The original list is : " + str(test_list)) K =k res = list(zip(*test_list))[K] print("The Kth column of matrix is : " + str(res)) # Write a function to print all possible subarrays using recursion def printSubArrays(arr, start, end): if end == len(arr): return elif start > end: return printSubArrays(arr, 0, end + 1) else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) arr = [1, 2, 3] printSubArrays(arr, 0, 0) # Write a function to find sum of nested list using Recursion total = 0 def sum_nestedlist(l): global total for j in range(len(l)): if type(l[j]) == list: sum_nestedlist(l[j]) else: total += l[j] sum_nestedlist([[1, 2, 3], [4, [5, 6]], 7]) print(total) #Write a function to find power of number using recursion def power(N, P): if (P == 0 or P == 1): return N else: return (N * power(N, P - 1)) print(power(5, 2)) # Write a function to Filter String with substring at specific position def f_substring(): test_list = ['program ', 'to', 'filter', 'for', 'substring'] print("The original list is : " + str(test_list)) sub_str = 'geeks' i, j = 0, 5 res = list(filter(lambda ele: ele[i: j] == sub_str, test_list)) print("Filtered list : " + str(res)) # Write a function to remove punctuation from the string def r_punc(): test_str = "end, is best : for ! Nlp ;" print("The original string is : " + test_str) punc = r'!()-[]{};:\, <>./?@#$%^&*_~' for ele in test_str: if ele in punc: test_str = test_str.replace(ele, "") print("The string after punctuation filter : " + test_str) # Write a function to implement Gnome Sort def gnomeSort(arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index = index - 1 return arr arr = [34, 2, 10, -9] n = len(arr) arr = gnomeSort(arr, n) print("Sorted seqquence after applying Gnome Sort :") for i in arr: print(i) # Write a function to implement Pigeonhole Sort */ def pigeonhole_sort(a): my_min = min(a) my_max = max(a) size = my_max - my_min + 1 holes = [0] * size for x in a: assert type(x) is int, "integers only please" holes[x - my_min] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3, 2, 7, 4, 6, 8] print("Sorted order is : ", end=" ") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end=" ") #Write a function to implement stooge sort def stoogesort(arr, l, h): if l >= h: return if arr[l] > arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t if h - l + 1 > 2: t = (int)((h - l + 1) / 3) stoogesort(arr, l, (h - t)) stoogesort(arr, l + t, (h)) stoogesort(arr, l, (h - t)) arr = [2, 4, 5, 3, 1] n = len(arr) stoogesort(arr, 0, n - 1) for i in range(0, n): print(arr[i], end = '') #Write a function to find the difference between two times def difference(h1, m1, h2, m2): t1 = h1 * 60 + m1 t2 = h2 * 60 + m2 if (t1 == t2): print("Both are same times") return else: diff = t2 - t1 h = (int(diff / 60)) % 24 m = diff % 60 print(h, ":", m) difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) #Write a function to convert time from 12 hour to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] print(convert24("08:05:45 PM")) #Write a function to find time for a given angle. def calcAngle(hh, mm): hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm angle = abs(hour_angle - minute_angle) angle = min(360 - angle, angle) return angle #Write a function to print all time when angle between hour hand and minute def printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm) == theta): print(hh, ":", mm, sep="") return print("Input angle not valid.") return theta = 90.0 printTime(theta) # write a python program to read and print contents of a file filepath = 'data.txt' with open(filepath, 'r') as file: data = file.read() print(f'Data: {data}') # write a python function to add numbers in a list def add(list): sum = 0 for i in range(0, len(list)): sum += list[i] return sum # write a function to check if a number is positive or not def check(num): if num > 0: return True return False # write a python function to that performs as ReLU def ReLU(num): if num > 0: return num return 0 # write a boolean python function to check if a given string matches a given pattern import re def match(pattern, string): if re.match(pattern, string): return True return False # write a python program to swap two numbers and print them num1 = 2 num2 = 4 num1, num2 = num2, num1 print(num1, num2) # write a python function to get the maximum element in a list def max(list): return max(list) # write a python program list comprehension to make a list of size n of random integers in ranges a and b import random n = 10 a = 1 b = 100 rand = [random.randint(a, b) for i in range(n)] print(f'list : {rand}') # write a python program to tokenise a string into words and print them string = 'the sun is shining' words = string.split() print(words) # write a python program to print the command line arguements given to a file import sys args = sys.argv print(args) # write a python program to print a string in lowercase string = 'SFG'; print(string.lower()) # write a python function to return the absolute difference between two numbers def abs_diff(num1, num2): return abs(num1 - num2) # write a program to terminate the program execution import sys sys.exit() # write a python program to print the datatype of a variable x = 2 print(type(x)) # write a python program to sort a list in descending order and print it list = [3, 1, 5, 6] result = sorted(list, reverse = True) print(result) # write a python function to check if a string contains a vowel or not def check_vowel(string): vowels = ['a', 'e', 'i', 'o', 'u'] for vowel in vowels: if vowel in string: return True return False # write a python program to filter a list and return words with alphabets only and print it list = ['sadgas1', 'sasg.as3$', 'hsd', '^atg', 'gaf'] result = [item for item in list if item.isalpha()] print(result) # write a python program to trim whitespace characters from a string and print it string = ' asdga \t\r' print(string.strip()) # write a python program to typecast an integer to string and print it x = 2 y = str(x) print(y) # write a python program to round up a number and print it import math x = 2.3 y = math.ceil(x) print(y) # write a function to accept a simple iterable and print the elements def print_iter(iter): for item in iter: print(item) # write a function to reverse a string def reverse_string(string): return string[::-1] # write a function to check if a string is a palindrome or not def reverse_string(string): return string[::-1] def ispalin(string): if string == reverse_string(string): return True return False # write a python function to return the largest value in a dictionary def dic_largest(dic): return max(dic.values()) # write a python print to return the first n fibonacci numbers def fibonacci(n): a, b = 0, 1 print(a) print(b) for i in range(n - 2): print(a + b) a, b = b, a + b # write a python function to return the number of whitespace separated tokens def tokenise(string): return len(string.split()) # write a python function to return the cube of a number def cube(num) return num * num * num # write a python function to return the area of a circle with given radius import math def area_circle(radius): return math.pi * radius * radius # write a python function to calculate age given date of birth from datetime import date def calculateAge(birthDate): today = date.today() age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day)) return age # write a python function to calculate simple interest given principal , rate and time def simpleIntereset(principal, rate, time): return principal * rate * time / 100 # write a function to calculate the frequency of a number in a list def frequency(list, num): count = 0 for item in list: if item == num: count = count + 1 return count # write a program to print ascii code of a character x = '5' print(ord(x)) # write a function to calculate factorial of number def factorial(num): if num == 0: return 1 return num * factorial(num - 1) # write a function to print if a number is even or odd def oddeven(num): if num % 2 == 0: print('even') else: print('odd') # write a python program to accept username and print hello along with the username name = input() print('Hello ' + name) # write a python program to print current datetime from datetime import datetime now = datetime.now() print(now) # write a python function to convert from Celcius to fahrenhiet def cel_to_fah(celcius): return 9 * celcius / 5 + 32 # write a python program to delete an element from a list list = ['a', 'bc', 'd', 'e'] element = 'bc' list.remove(element) # Write a program to print the union of two sets Set1 = {"1","2","3"} Set2 = {"a","b","c"} Set = Set1.union(Set2) print(Set) #write a program to remove common element between two sets s1 = {"apple", "banana", "cherry"} s2 = {"google", "microsoft", "apple"} s1.difference_update(s2) print(s1) # write a program to find a given character in a string and print its position a= "Hello World" x= a.find("r") print(x) # write a program to print logrithmic values of any number import math x = 100 base = 5 print(math.log(x,base)) # write a program to join two lists list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) # write a function to check a valid email id import re def check(email): regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if(re.search(regex,email)): print("Valid Email") else: print("Invalid Email") # write a program to print difference in between today and given date import datetime dd = int(input("date: ")) mm = int(input("month: ")) yy = int(input("year: ")) a = datetime.date(yy,mm,dd) x = date.today() print(x-a) # write a program to check if year is a leap year or not year = int(input("Year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) # write a function to replace vowels with a specific character K def replacewith_K(test_str, K): vowels = 'AEIOUaeiou' for ele in vowels: test_str = test_str.replace(ele, K) return test_str # write a python function to return mean of a list of numbers def mean(list): sum = 0 for num in list: sum += num return sum / len(list) # write a python class named complex with constructor accepting real and imaginary parts class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart # write a program to convert key-values list to flat dictionary and print it from itertools import product test_dict = {'month' : [1, 2, 3], 'name' : ['Jan', 'Feb', 'March']} print("The original dictionary is : " + str(test_dict)) res = dict(zip(test_dict['month'], test_dict['name'])) print("Flattened dictionary : " + str(res)) # write a program to remove duplicate elements in a list and print the list test_list = [1, 3, 5, 6, 3, 5, 6, 1] print ("The original list is : " + str(test_list)) res = [] for i in test_list: if i not in res: res.append(i) print ("The list after removing duplicates : " + str(res)) # write a program to print sum of all even numbers in a list ls = [1,2,3,4,5,6,7,8,10,22] sum = 0 for i in ls: if i % 2 == 0: sum += i print(sum) # write a program to write a string in a file filename = 'file1.txt' string = "programming in \n python" f1 = open(filename,'w') f1.write(string) f1.close() # write a function to check weather a number is prime or not def isprime(num): for i in range(2, num): if num % i == 0: return False return True # write a program to print binary of a decimal number n binaryNum = [0] * n; i = 0; while (n > 0): binaryNum[i] = n % 2; n = int(n / 2); i += 1; for j in range(i - 1, -1, -1): print(binaryNum[j], end = "") # write a function to check if a number is perfect square or not import math def checksquare(num): x = int(math.sqrt(num)) if x * x == num: return True return False # write a program to print the sine value of a number import math num = 3 print(math.sin(num)) # write a function to calculate the hypotenuse of a triangle give base and height import math def calc_hypotenuse(base, height): return math.sqrt(base * base + height * height) # write a function to calculate the sum of digits of a number def sum_of_digits(num): sum = 0 while(num > 0): sum += num % 10 num = num // 10 return sum # write a python function to find URLs in a string import re def Find(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # write a python function to calculate the dot product of two lists def dot(l1, l2): return sum(x*y for x,y in zip(l1, l2)) # write a function to accept input as feet and inches into centimeters def height_into_cms(feet, inches): ininches = feet * 12 + inches return ininches * 2.54 # write a python function to convert temperature from celcius to kelvin def cel_to_kel(celcius): return celcius + 273 # write a python program to find difference between elements of two lists and print it l1 = [1, 2, 3, 4] l2 = [5, 8, 7, 0] res = [] for i in range(len(l1)): res.append(l1[i] - l2[i]) print(res) # write a function to calculate BMI given height in meters and weights in kgs def bmi(height, weight): return weight / (height * height) # write a function to calculate area of a triangle given height and base def area_triangle(base, height): return 0.5 * base * height # write a program to print the bitwise OR of two numbers num1 = 5 num2 = 10 print(num1 | num2) # write a function to convert weight from kgs to pounds def kgs_to_pounds(weight_kg): return weight_kg * 2.2 # write a function to convert miles to kilometers def miles_to_kms(dist): return dist * 1.609 # write a function to calculate speed given distance covered and time taken def calspeed(dist, time): return dist / time # write a python function to return count of number of vowels in a sentence def count_vowels(sentence): count = 0 for letter in sentence: if letter in "aeiouAEIOU": count += 1 return count # write a python function to check if a given string is a palindrome def is_palindrome(string): return string == string[::-1] # write a program to print the nth fibonacci number n1 = 1 n2 = 1 n = 5 for _ in range(n): n1, n2 = n2, n1 + n2 print(n2) # write a function to return the square of first N numbers def get_squares(n): return [i*i for i in range(n)] # write a python function to return only even numbers in a list def filter_even(nums): return list(filter(lambda num: num % 2 == 0, nums)) # write a python function to return only odd numbers in a list def filter_odd(nums): return list(filter(lambda num: num % 2 == 1, nums)) # write a python program to calculate the sum of numbers using reduce and print it from functools import reduce nums = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50] total_sum = reduce(lambda a, b: a + b, nums) print(f'Sum: {total_sum}') # write a python program to print unique numbers in a list numbers = [1, 2, 2, 3, 4, 4, 5, 6] unique = set(numbers) print(f'Unique numbers: {list(unique)}') # write a python program to count how many times each letter occurs in a string string = 'The quick brown fox jumps over the lazy dog' countmap = {} for letter in string: if letter in countmap: countmap[letter] += 1 else: countmap[letter] = 1 print(f'Count of letters: {countmap}') # write a python function to repeat a given string n times def repeat_string(string, frequency): return string * frequency # write a program to capitalize the first letter of every word in a string and print it string = 'The quick brown fox jumps over the lazy dog' print(string.title()) # write a function that merges two dictionaries def merge_dictionaries(dict1, dict2): return {**dict1, **dict2} # write a program to merge two lists into a dictionary keys = [1, 2, 3] values = ['aye', 'bee', 'sea'] dictionary = dict(zip(keys, values)) # write a python function that inverts the key and values in a dict and returns it def invert_dict(dictionary): inverted_dict = {value: key for key, value in dictionary.items()} return inverted_dict # write a python program to print the difference in days between two dates from datetime import date date1 = date(2020, 10, 25) date2 = date(2020, 12, 25) print(f'Difference between dates: {(date2 - date1).days}') # write a python function that returns the weighted average of numbers def get_weighted_average(numbers, weightage): return sum(x * y for x, y in zip(numbers, weightage)) / sum(weightage) # write a python program to print if year is a leap year or not year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) # write a python program to check and print if a number is prime num = 407 if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number") # write a python program to print all prime numbers in a given interval lower = 900 upper = 1000 for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # write a python function to return words in a sentence in sorted order def get_sorted_words(sentence): words = [word for word in sentence.split()] words.sort() return words # write a python function to remove all punctuation from a string def remove_punctuations(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct = '' for char in sentence: if char not in punctuations: no_punct = no_punct + char return no_punct # write a python function to return the nth fibonacci number def fib(n): if n <= 1: return n else: return (fib(n-1) + fib(n-2)) # write a python function to return the sum of first n numbers def sum_of_nums(n): if n <= 1: return n else: return n + sum_of_nums(n-1) # write a python function to return the factorial of a number def fact(n): if n == 1: return n else: return n * fact(n-1) # write a python program to print the factors of a number num = 320 for i in range(1, num + 1): if num % i == 0: print(i) # write a python function that returns the lcm of two numbers def lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # write a python function that returns the gcd of two numbers def gcd(x, y): if x > y: smaller = y else: smaller = x for i in range(1, smaller + 1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd # write a python program to print the ASCII value of a character character = 'x' print(f'The ASCII value of {character} is {ord(character)}') # write a python program to print the character of an ASCII value value = 65 print(f'The ASCII value {value} is of the character {chr(value)}') # write a python function to print the binary value of a decimal number def print_binary(dec): print(bin(dec)) # write a python function to print the octal value of a decimal number def print_octal(dec): print(oct(dec)) # write a python function to print the hexadecimal value of a decimal number def print_hexadecimal(dec): print(hex(dec)) # write a python program that prints the sum of natural numbers up to a given number num = 16 sum = 0 while (num > 0): sum += num num -= 1 print(f'The sum is {sum}') # write a python function to return the number of lines in a file def count_lines(filename): with open(filename, 'r') as f: contents = f.read().split('\n') return len(contents) # write a program to print the current date and time from datetime import datetime now = datetime.now() print(now) # write a python program to extract the file name and extension of a file import os filename, extension = os.path.splitext('/path/to/some/file.ext') # write a python program to merge two lists odd = [1, 3, 5, 7, 9] even = [2, 4, 6, 8, 10] odd.extend(even) # write a python program to print a random vowel import random vowels = ['a', 'e', 'i', 'o', 'u'] print(random.choice(vowels)) # write a python program to flip a coin 100 times and print number of heads and tails import random heads = 0 tails = 0 for i in range(100): if(random.choice([True, False])): heads += 1 else: tails += 1 print(f'{heads} heads, {tails} tails') # write a python program to print common elements in two lists list_a = [1, 2, 3, 4, 5, 6, 7] list_b = [2, 4, 6, 8, 10] print(f'Common elements: { set(list_a).intersection(set(list_b)) }') # write a python program to print squares of numbers until 20 for i in range(20): print(i*i) # write a python program to print the number of uppercase and lowercase letters in a string sentence = 'The Quick Brown Fox' lowercase = 0 uppercase = 0 for c in sentence: if c.isupper(): uppercase += 1 elif c.islower(): lowercase += 1 else: pass print(f'Lowercase: {lowercase}, Uppercase: {uppercase}') # write a python program to print the number of letters and digits in sentence sentence = 'The Quick 123 Fox' digits = 0 letters = 0 for c in sentence: if c.isdigit(): digits += 1 elif c.isalpha(): letters += 1 else: pass print(f'Digits: {digits}, Letters: {letters}') # write a python function to print a given string n times def printn(string, n): print(string * n) # write a python program that creates a dictionary whose keys are numbers from 1 to 10 and values are squares of the key square_dict = {} for i in range(1, 11): square_dict[i] = i*i # write a python class called Person that has a name property class Person: def __init__(self, name): self.name = name # write a python function that takes two strings as a parameter and prints the shorter one def print_shorter(str1, str2): if (len(str1) > len(str2)): print(str2) else: print(str1) # write a program to compute the count of each word in a sentence and print it word_freq = {} line = 'how many how words does this many have' for word in line.split(): word_freq[word] = word_freq.get(word, 0) + 1 print(word_freq) # write a python function that squares every number in a list using a list comprehension and returns the result def square_numbers(nums): return [i*i for i in nums] # write a python program that converts a binary number to decimal and prints it binary_num = '1010101' decimal_num = int(binary_num, 2) print(decimal_num) # write a python program that converts a octal number to octal and prints it octal_num = '17' decimal_num = int(octal_num, 8) print(decimal_num) # write a python program that converts a hexadecimal number to hexadecimal and prints it hexadecimal_num = 'FF' decimal_num = int(hexadecimal_num, 16) print(decimal_num) # write a python program that alphabetically sorts the words in a sentence and prints it sentence = 'the quick brown fox jumps' sorted_words = sentence.split(' ') sorted_words.sort() print(' '.join(sorted_words)) # write a python program that prints the area of a circle import math radius = 5 print(f'Area: {math.pi * radius * radius}') # write a python function that returns a dictionary with the area and perimeter of a rectangle def calculate_rect_properties(width, height): return { 'perimeter': 2 * (width + height), 'area': width * height } # write a python program that removes all blank spaces in a sentence and prints it sentence = 'the quick brown fox' print(sentence.replace(' ', '')) # write a python program that prints all characters at even indexes in a sentence sentence = 'the quick brown fox' print(sentence[::2]) # write a python program that prints every third character in a sentence sentence = 'the quick brown fox' print(sentence[::3]) # write a program to remove odd numbers from a list using list comprehensions nums = [1, 2, 3, 4, 5, 6, 7, 8] no_odd_nums = [i for i in nums if i % 2 == 0] # write a program to remove even numbers from a list using list comprehensions nums = [1, 2, 3, 4, 5, 6, 7, 8] no_even_nums = [i for i in nums if i % 2 == 1] # write a program to print 5 random numbers between 100 and 200 import random print(random.sample(range(100, 200), 5)) # write a program to print 5 even random numbers between 10 and 100 import random print(random.sample([i for i in range(10, 100) if i%2 == 0], 5)) # write a program to print 5 odd random numbers between 100 and 200 import random print(random.sample([i for i in range(10, 100) if i%2 == 1], 5)) # write a program to print 5 random numbers divisible by 4 between 100 and 200 import random print(random.sample([i for i in range(10, 100) if i%4 == 0], 5)) # write a program that adds corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] sum_list = [a+b for (a,b) in zip(list1, list2)] print(sum_list) # write a program that subtracts corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] diff_list = [a-b for (a,b) in zip(list1, list2)] print(diff_list) # write a program that multiplies corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] prod_list = [a*b for (a,b) in zip(list1, list2)] print(prod_list) # write a program that divides corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] quot_list = [a/b for (a,b) in zip(list1, list2)] print(quot_list) # write a python program to print 5 random vowels import random vowels = ['a', 'e', 'i', 'o', 'u'] print([random.choice(vowels) for _ in range(5)]) # write a python program that creates a dictionary whose keys are numbers from 1 to 10 and values are cubes of the key cube_dict = {} for i in range(1, 11): cube_dict[i] = i ** 3 # write a program to create a string variable and print the amount of memory it consumes import sys string_var = 'string variable' print(sys.getsizeof(string_var)) # write a python function that joins strings in a list and returns the result def join_string_parts(str_list): return " ".join(str_list) # write a python program that reverses an integer and prints it num = 12345 reversed = int(str(num)[::-1]) print(reversed) # write a python program that sorts and prints a comma separated list of values values = 'one,two,three,four,five' items = values.split(',') items.sort() print(','.join(items)) # write a python program to print unique words in a sentence sentence = 'the king is the one' unique = set(sentence.split(' ')) print(unique) # write a python program that multiplies a tuple n times and print the result my_tuple = (1, 2, 3) n = 3 print(my_tuple * 3) # write a python program to multiply three numbers and print the result num1 = 2 num2 = 4 num3 = 6 print(num1 * num2 * num3) # write a python program to print the sum of first n numbers n = 10 sum = 0 while n > 0: sum += n n -= 1 print(sum) # write a python program to print the factorial of a number num = 5 fact = 1 while num > 0: fact *= num num -= 1 print(fact) # write a python function to return the factors of a number def get_factors(num): factors = [] for i in range(1, num + 1): if num % i == 0: factors.append(i) return factors # write a python function that returns True if the product of two provided numbers is even def is_prod_even(num1, num2): prod = num1 * num2 return not prod % 2 # write a python function that returns True if the sum of two provided numbers is even def is_prod_even(num1, num2): sum = num1 + num2 return not sum % 2 # write a python program to print the first 5 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[:5]) # write a python program to print the last 3 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[-3:]) # write a python program to print the items in a list apart from the first 4 my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[4:]) # write a python function that makes all negative values in a list zero and returns it def make_negative_zero(items): return [0 if item < 0 else item for item in items] # write a python program to shuffle the items in a list and print it from random import shuffle mylist = [1, 2, 3, 4, 5] shuffle(mylist) print(mylist) # write a python program that adds the elements of a list to a set and prints the set my_set = {1, 2, 3} my_list = [4, 5, 6] my_set.update(my_list) print(my_set) # write a python program that prints the circumference of a circle import math radius = 10 print(f'Area: {2 * math.pi * radius}') # write a python program that prints the area of a rectangle length = 10 width = 5 print(f'Area: {length * width}') # write a python program that prints the area of a square side = 5 print(f'Area: {side * side}') # write a python program to create a dictionary with numbers 1 to 5 as keys and the numbers in english as values number_dict = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' } # write a python program to remove words less than a specified length from a sentence sentence = 'this is my sentence and i will write it my way' minlength = 3 result = [word for word in sentence.split(' ') if len(word) >= minlength] # write a python program to keep words less than a specified length in a sentence sentence = 'this is my sentence and i will write it my way' maxlength = 3 result = [word for word in sentence.split(' ') if len(word) <= minlength] #### 93 # write a python function that takes a list as an input and converts all numbers to positive numbers and returns the new list def make_all_positive(nums): return [num if num > 0 else -num for num in nums] # write a python function that takes a list as an input and converts all numbers to negative numbers and returns the new list def make_all_negative(nums): return [num if num < 0 else -num for num in nums] # write a python function to return a set of all punctuation used in a string def get_punctuations(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' used_punctuation = set() for char in sentence: if char in punctuations: used_punctuation.add(char) return used_punctuation # write a python program to print the words in a sentence in reverse order sentence = 'the quick brown fox' words = sentence.split(' ') words.reverse() print(' '.join(words)) # write a python program to replace each word in a sentence with the length of the word and print it sentence = 'the quick brown fox jumps over the lazy dog' words = sentence.split(' ') lengths = [str(len(word)) for word in words] print(' '.join(lengths)) # write a python program to convert a set to a list myset = {1, 2, 4, 7} mylist = list(myset) # write a python program to convert a list to a dictionary where the key is the index and the value is the item in the list my_list = [1, 8, 1, 2, 2, 9] my_dict = {key: value for key, value in enumerate(my_list)} # Write a function that adds 2 iterables a and b such that a is even and b is odd def add_even_odd_list(l1:list,l2:list)-> list: return [a+b for a,b in zip(l1,l2) if a%2==0 and b%2!=0] # Write a function that strips every vowel from a string provided def strip_vowels(input_str:str)->str: vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ] return ''.join(list(filter(lambda x: x not in vowels, input_str))) # write a function that acts like a ReLU function for a 1D array def relu_list(input_list:list)->list: return [(lambda x: x if x >= 0 else 0)(x) for x in input_list] # Write a function that generates Factorial of number def factorial(n): if n == 0 or n ==1: return 1 else: return n*factorial(n-1) # Write a function that returns length of the list def list_length(l): return len(l) # Write a function that sorts list of numbers and returns top element def biggest_no(l:list)->int: sorted(l) # Write a function to print a string by repeating it n times def print_repeatnstring(text:str, n:int)-> str: return text*n # Write a function to merge two lists element wise def merge_lists(l1:list, l2:list): return list(zip(l1,l2)) # Write a function to merge two lists element wise def merge_lists(l1:list, l2:list): return list(zip(l1,l2)) # Write a function to append two lists def append_lists(l1:list, l2:list)->list: return l1.extend(l2) # Write a function to return reverse of a list def reverse_list(l1:list)->list: return l1[::-1] # Write a function to adds two lists element wise def adds_listelements(l1:list, l2:list): return [i+j for i, j in zip(l1,l2)] # Write a function to Subtracts two lists element wise def sub_listelements(l1:list, l2:list): return [i-j for i, j in zip(l1,l2)] # Write a function to adds two lists element wise only if numbers are even def adds_listevenelements(l1:list, l2:list): return [i+j for i, j in zip(l1,l2) if i*j%2 == 0] # Write a function to multiplies two lists element wise only if numbers are odd def adds_listoddelements(l1:list, l2:list): return [i*j for i, j in zip(l1,l2) if i*j%2 == 1] # Write a function that returns list of elements with n power to elements of list def n_power(l1:list, power:int)->list: return [i**power for i in l1] # Write a function that generates fibbonacci series def Fibonacci(n:int)-> int: if n==1: fibonacci = 0 elif n==2: fibonacci = 1 else: fibonacci = Fibonacci(n-1) + Fibonacci(n-2) return fibonacci # Write a function that returns sine value of the input def sin(x:float) -> float: import math return math.sin(x) # Write a function that returns derivative of sine value of the input def derivative_sin(x:float)-> float: import math return math.cos(x) # Write a function that returns tan value of the input def tan(x:float) -> float: import math return math.tan(x) # Write a function that returns derivative of tan value of the input def derivative_tan(x:float)-> float: import math return (1/math.cos(x))**2 # Write a function that returns cosine value of the input def cos(x:float) -> float: import math return math.cos(x) # Write a function that returns cosine value of the input def derivative_cos(x:float)-> float: import math return -(math.sin(x)) # Write a function that returns the exponential value of the input def exp(x) -> float: import math return math.exp(x) # Write a function that returns Gets the derivative of exponential of x def derivative_exp(x:float) -> float: import math return math.exp(x) # Write a function that returns log of a function def log(x:float)->float: import math return math.log(x) # Write a function that returns derivative of log of a function def derivative_log(x:float)->float: return (1/x) # Write a function that returns relu value of the input def relu(x:float) -> float: x = 0 if x < 0 else x return x # Write a function that returns derivative derivative relu value of the input def derivative_relu(x:float) -> float: x = 1 if x > 0 else 0 return x # Write a function that returns runs a garbage collector def clear_memory(): import gc gc.collect() # Write a function that calculates the average time taken to perform any transaction by Function fn averaging the total time taken for transaction over Repetations def time_it(fn, *args, repetitons= 1, **kwargs): import time total_time = [] for _ in range(repetitons): start_time = time.perf_counter() fn(*args,**kwargs) end_time = time.perf_counter() ins_time = end_time - start_time total_time.append(ins_time) return sum(total_time)/len(total_time) # Write a function to identify if value is present inside a dictionary or not def check_value(d:dict, value)->bool: return any(v == value for v in dict.values()) # Write a function to identify to count no of instances of a value inside a dictionary def count_value(d:dict, value)->bool: return list(v == value for v in dict.values()).count(True) # Write a function to identify if value is present inside a list or not def check_listvalue(l:list, value)->bool: return value in l # Write a function to identify if value is present inside a tuple or not def check_tuplevalue(l:tuple, value)->bool: return value in l # Write a function that returns lowercase string def str_lowercase(s:str): return s.lower() # Write a function that returns uppercase string def str_uppercase(s:str): return s.upper() # Write a function that removes all special characters def clean_str(s): import re return re.sub('[^A-Za-z0-9]+', '', s) # Write a function that returns a list sorted ascending def ascending_sort(l:list): sorted(l, reverse=False) # Write a function that returns a list sorted descending def descending_sort(l:list): sorted(l, reverse=True) # Write a function that returns a dictionary sorted descending by its values def descending_dict_valuesort(d:dict): return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[1])} # Write a function that returns a dictionary sorted ascending by its values def ascending_dict_valuesort(d:dict): return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1])} # Write a function that returns a dictionary sorted descending by its keys def descending_dict_keysort(d:dict): return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[0])} # Write a function that returns a dictionary sorted ascending by its keys def ascending_dict_keysort(d:dict): return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[0])} # Write a function that returns a replace values in string with values provided def replace_values(s:str, old, new)->str: s.replace(old, new) # Write a function that joins elements of list def join_elements(l:list)-> str: return (''.join(str(l))) # Write a function that splits the elements of string def split_elements(s:str, seperator)-> list: return s.split(seperator) # Write a function that returns sum of all elements in the list def sum_elements(l:list): return sum(l) # Write a function that returns sum of all odd elements in the list def sum_even_elements(l:list): return sum([i for i in l if i%2==0]) # Write a function that returns sum of all odd elements in the list def sum_odd_elements(l:list): return sum([i for i in l if i%2==1]) # write a python function to count number of times a function is called def counter(fn): count = 0 def inner(*args, **kwargs): nonlocal count count += 1 print(f'Function {fn.__name__} was called {count} times.') return fn(*"args, **kwargs) return inner # write a python function to remove duplicate items from the list def remove_duplicatesinlist(lst): return len(lst) == len(set(lst)) # write a python decorator function to find how much time user given function takes to execute def timed(fn): from time import perf_counter from functools import wraps @wraps(fn) def inner(*args, **kwargs): start = perf_counter() result = fn(*args, **kwargs) end = perf_counter() elapsed = end - start args_ = [str(a) for a in args] kwargs_ = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] all_args = args_ + kwargs_ args_str = ','.join(all_args) # now it is comma delimited print(f'{fn.__name__}({args_str}) took {elapsed} seconds') return result # inner = wraps(fn)(inner) return inner # write a python program to add and print two user defined list using map input_string = input("Enter a list element separated by space ") list1 = input_string.split() input_string = input("Enter a list element separated by space ") list2 = input_string.split() list1 = [int(i) for i in list1] list2 = [int(i) for i in list2] result = map(lambda x, y: x + y, list1, list2) print(list(result)) # write a python function to convert list of strings to list of integers def stringlist_to_intlist(sList): return(list(map(int, sList))) # write a python function to map multiple lists using zip def map_values(*args): return set(zip(*args)) # write a generator function in python to generate infinite square of numbers using yield def nextSquare(): i = 1; # An Infinite loop to generate squares while True: yield i*i i += 1 # write a python generator function for generating Fibonacci Numbers def fib(limit): # Initialize first two Fibonacci Numbers a, b = 0, 1 # One by one yield next Fibonacci Number while a < limit: yield a a, b = b, a + b # write a python program which takes user input tuple and prints length of each tuple element userInput = input("Enter a tuple:") x = map(lambda x:len(x), tuple(x.strip() for x in userInput.split(','))) print(list(x)) # write a python function using list comprehension to find even numbers in a list def find_evennumbers(input_list): list_using_comp = [var for var in input_list if var % 2 == 0] return list_using_comp # write a python function to return dictionary of two lists using zip def dict_using_comp(list1, list2): dict_using_comp = {key:value for (key, value) in zip(list1, list2)} return dict_using_comp #Write a function to get list of profanity words from Google profanity URL def profanitytextfile(): url = "https://github.com/RobertJGabriel/Google-profanity-words/blob/master/list.txt" html = urlopen(url).read() soup = BeautifulSoup(html, features="html.parser") textlist = [] table = soup.find('table') trs = table.find_all('tr') for tr in trs: tds = tr.find_all('td') for td in tds: textlist.append(td.text) return textlist #write a python program to find the biggest character in a string bigChar = lambda word: reduce(lambda x,y: x if ord(x) > ord(y) else y, word) #write a python function to sort list using heapq def heapsort(iterable): from heapq import heappush, heappop h = [] for value in iterable: heappush(h, value) return [heappop(h) for i in range(len(h))] # write a python function to return first n items of the iterable as a list def take(n, iterable): import itertools return list(itertools.islice(iterable, n)) # write a python function to prepend a single value in front of an iterator def prepend(value, iterator): import itertools return itertools.chain([value], iterator) # write a python function to return an iterator over the last n items def tail(n, iterable): from collections import deque return iter(deque(iterable, maxlen=n)) # write a python function to advance the iterator n-steps ahead def consume(iterator, n=None): import itertools from collections import deque "Advance the iterator n-steps ahead. If n is None, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(itertools.islice(iterator, n, n), None) # write a python function to return nth item or a default value def nth(iterable, n, default=None): from itertools import islice return next(islice(iterable, n, None), default) # write a python function to check whether all elements are equal to each other def all_equal(iterable): from itertools import groupby g = groupby(iterable) return next(g, True) and not next(g, False) # write a python function to count how many times the predicate is true def quantify(iterable, pred=bool): return sum(map(pred, iterable)) # write a python function to emulate the behavior of built-in map() function def pad_none(iterable): """Returns the sequence elements and then returns None indefinitely. Useful for emulating the behavior of the built-in map() function. """ from itertools import chain, repeat return chain(iterable, repeat(None)) # write a python function to return the sequence elements n times def ncycles(iterable, n): from itertools import chain, repeat return chain.from_iterable(repeat(tuple(iterable), n)) # write a python function to return the dot product of two vectors def dotproduct(vec1, vec2): return sum(map(operator.mul, vec1, vec2)) # write a python function to flatten one level of nesting def flatten(list_of_lists): from itertools import chain return chain.from_iterable(list_of_lists) # write a python function to repeat calls to function with specified arguments def repeatfunc(func, times=None, *args): from itertools import starmap, repeat if times is None: return starmap(func, repeat(args)) return starmap(func, repeat(args, times)) # write a python function to convert iterable to pairwise iterable def pairwise(iterable): from itertools import tee a, b = tee(iterable) next(b, None) return zip(a, b) # write a python function to collect data into fixed-length chunks or blocks def grouper(iterable, n, fillvalue=None): from itertools import zip_longest # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) # write a python program to create round robin algorithm: "roundrobin('ABC', 'D', 'EF') --> A D E B F C" def roundrobin(*iterables): from itertools import islice, cycle # Recipe credited to George Sakkis num_active = len(iterables) nexts = cycle(iter(it).__next__ for it in iterables) while num_active: try: for next in nexts: yield next() except StopIteration: # Remove the iterator we just exhausted from the cycle. num_active -= 1 nexts = cycle(islice(nexts, num_active)) # write a python function to use a predicate and return entries particition into false entries and true entries def partition(pred, iterable): from itertools import filterfalse, tee # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) # write a python function to return powerset of iterable def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" from itertools import chain, combinations s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) list(powerset([1,2,3])) # write a python function to list all unique elements, preserving order def unique_everseen(iterable, key=None): from itertools import filterfalse # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element # write a python function to list unique elements, preserving order remembering only the element just seen." def unique_justseen(iterable, key=None): import operator from itertools import groupby # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return map(next, map(operator.itemgetter(1), groupby(iterable, key))) # write a python function to call a function repeatedly until an exception is raised. def iter_except(func, exception, first=None): """Converts a call-until-exception interface to an iterator interface. Like builtins.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop. Examples: iter_except(s.pop, KeyError) # non-blocking set iterator """ try: if first is not None: yield first() # For database APIs needing an initial cast to db.first() while True: yield func() except exception: pass # write a python function to return random selection from itertools.product(*args, **kwds) def random_product(*args, repeat=1): import random pools = [tuple(pool) for pool in args] * repeat return tuple(map(random.choice, pools)) # write a python function to return random selection from itertools.permutations(iterable, r) def random_permutation(iterable, r=None): import random pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) # write a python function to random select from itertools.combinations(iterable, r) def random_combination(iterable, r): import random pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(range(n), r)) return tuple(pool[i] for i in indices) # write a python function to perform random selection from itertools.combinations_with_replacement(iterable, r) def random_combination_with_replacement(iterable, r): import random pool = tuple(iterable) n = len(pool) indices = sorted(random.choices(range(n), k=r)) return tuple(pool[i] for i in indices) # write a python function to locate the leftmost value exactly equal to x def index(a, x): from bisect import bisect_left i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError # write a python function to locate the rightmost value less than x def find_lt(a, x): from bisect import bisect_left i = bisect_left(a, x) if i: return a[i-1] raise ValueError # write a python function to find rightmost value less than or equal to x def find_le(a, x): from bisect import bisect_right i = bisect_right(a, x) if i: return a[i-1] raise ValueError # write a python function to find leftmost value greater than x def find_gt(a, x): from bisect import bisect_right i = bisect_right(a, x) if i != len(a): return a[i] raise ValueError # write a python function to find leftmost item greater than or equal to x def find_ge(a, x): from bisect import bisect_left i = bisect_left(a, x) if i != len(a): return a[i] raise ValueError # write a python function to map a numeric lookup using bisect def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): from bisect import bisect i = bisect(breakpoints, score) return grades[i] # write a regex pattern in python to print all adverbs and their positions in user input text import re text = input("Enter a string: ") for m in re.finditer(r"\w+ly", text): print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) # write a python function to read a CSV file and print its content def read_csv(filename): import csv with open(filename, newline='') as f: reader = csv.reader(f) for row in reader: print(row) # write a python snippet to convert list into indexed tuple test_list = [4, 5, 8, 9, 10] list(zip(range(len(test_list)), test_list)) # write a python function to split word into chars def split(word): return [char for char in word] # write a python function to pickle data to a file def pickle_data(data, pickle_file): import pickle with open(pickle_file, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) return None # write a python function to load pickle data from a file def load_pickle_data(pickle_file): import pickle with open(pickle_file, 'rb') as f: data = pickle.load(f) return data # write a python function to check if a given string is a palindrome def isPalindrome(s): return s == s[::-1] # write a python function to check if a given string is symmetrical def symmetry(a): n = len(a) flag = 0 if n%2: mid = n//2 +1 else: mid = n//2 start1 = 0 start2 = mid while(start1 < mid and start2 < n): if (a[start1]== a[start2]): start1 = start1 + 1 start2 = start2 + 1 else: flag = 1 break return flag # write a function to reverse words of string def rev_sentence(sentence): words = sentence.split(' ') reverse_sentence = ' '.join(reversed(words)) return reverse_sentence # write a program to check if a substring is present in a given string string = "how are you?" substring = "are" if (string.find(substring) == -1): print("NO") else: print("YES") # write a program to print length of a string str1 = "great way to learn!" print(len(str1)) # write a program to print words frequncy in a given string test_str = "It is a great meal at a great restaurant on a great day" print("Original String: " + str(test_str)) res = {key: test_str.count(key) for key in test_str.split()} print("The words frequency: " + str(res)) # write a program to print even length words in a string str1 = "I am doing fine" s = str1.split(' ') for word in s: if len(word)%2==0: print(word) # write a program to accept the strings which contains all vowels str1 = "__main__" if len(set(str1).intersection("AEIOUaeiou"))>=5: print('accepted') else: print("not accepted") # write a program to print count of number of unique matching characters in a pair of strings str1="ababccd12@" str2="bb123cca1@" matched_chars = set(str1) & set(str2) print("No. of matching characters are : " + str(len(matched_chars)) ) # write a program to remove all duplicate characters from a string str1 = "what a great day!" print("".join(set(str1))) # write a program to print least frequent character in a string str1="watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print("Minimum of all characters is: " + str(res)) # write a program to print maximum frequency character in a string str1 = "watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = max(all_freq, key = all_freq.get) print("Maximum of all characters is: " + str(res)) # write a program to find and print all words which are less than a given length in a string str1 = "It is wonderful and sunny day for a picnic in the park" str_len = 5 res_str = [] text = str1.split(" ") for x in text: if len(x) < str_len: res_str.append(x) print("Words that are less than " + str(str_len) + ": " + str(res_str)) # write a program to split and join a string with a hyphen delimiter str1 = "part of speech" delimiter = "-" list_str = str1.split(" ") new_str = delimiter.join(list_str) print("Delimited String is: " + new_str) # write a program to check if a string is binary or not str1="01110011 a" set1 = set(str1) if set1 == {'0','1'} or set1 == {'0'} or set1 == {'1'}: print("string is binary") else: print("string is not binary") # write a function to remove i-th indexed character in a given string def remove_char(string, i): str1 = string[ : i] str2 = string[i + 1: ] return str1 + str2 # write a function to find all urls in a given string import re def find_urls(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # write a function to find uncommon words from two strings def UncommonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] == 1] # write a function to find common words from two strings def commonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] > 1] # write a program to replace duplicate word occurence in String str1 = "IISC is the best. IISC has Classes in the evening for professionals. Classes help to learn new things." repl_dict = {'IISC':'It', 'Classes': 'They'} str_list = str1.split(' ') res = set() for idx, ele in enumerate(str_list): if ele in repl_dict: print(str(idx) + ' '+ele) if ele in res: str_list[idx] = repl_dict[ele] else: res.add(ele) res = ' '.join(str_list) print("Replaced String: " + str(res)) # write a program to replace multiple words with a single word str1 = 'CoffeeDay is best for coffee and having long conversations' word_list = ["best", 'long'] repl_word = 'good' res = ' '.join([repl_word if idx in word_list else idx for idx in str1.split()]) print("String after multiple replace : " + str(res)) # write a function to rotate string left by a given length def rotate_left(input,d): Lfirst = input[0 : d] Lsecond = input[d :] return (Lsecond + Lfirst) # write a function to rotate string right by a given length def rotate_right(input,d): Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] return (Rsecond + Rfirst) # write a function to replace all occurances of a substring in a string str1 = "Hello! It is a Good thing" substr1 = "Good" substr2 = "bad" replaced_str = str1.replace(substr1, substr2) print("String after replace :" + str(replaced_str)) # write a program to move numbers to the end of a string str1 = 'hi 123 how are you doing? 567 is with you. Take care of 89' res = '' dig = '' for ele in str1: if ele.isdigit(): dig += ele else: res += ele res += dig print("Strings after digits at end : " + str(res)) # write a program to count characters surrounding vowels str1 = 'week after week the numbers are increasing' res = 0 vow_list = ['a', 'e', 'i', 'o', 'u'] for idx in range(1, len(str1) - 1): if str1[idx] not in vow_list and (str1[idx - 1] in vow_list or str1[idx + 1] in vow_list): res += 1 if str1[0] not in vow_list and str1[1] in vow_list: res += 1 if str1[-1] not in vow_list and str1[-2] in vow_list: res += 1 print("Characters around vowels count : " + str(res)) # write a function that return space count def count_space(str1): count = 0 for i in range(0, len(str1)): if str1[i] == " ": count += 1 return count # write a program to break up string into individual elements str1 = "whatisthis" split_string = list(''.join(str1)) print(split_string) # write a program to extract string of N size and having K distict characters str1 = 'GoodisalwaysGoood' N = 3 K = 2 res = [] for idx in range(0, len(str1) - N + 1): if (len(set(str1[idx: idx + N])) == K): res.append(str1[idx: idx + N]) print("Extracted Strings : " + str(res)) # write a program to increment number which is at end of string import re str1 = 'count001' res = re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", str1) print("Incremented numeric String : " + str(res)) # write a program to calculate and print number of letters and digits in a string str1 = "python1234" total_digits = 0 total_letters = 0 for s in str1: if s.isnumeric(): total_digits += 1 else: total_letters += 1 print("Total letters found : ", total_letters) print("Total digits found : ", total_digits) # write a function to check if a lower case letter exists in a given string def check_lower(str1): for char in str1: k = char.islower() if k == True: return True if(k != 1): return False # write a function to check if a upper case letter exists in a given string def check_upper(str1): for char in str1: k = char.isupper() if k == True: return True if(k != 1): return False # write a program to print number of words in a string str1 = 'It is a glorious day' res = len(str1.split()) print("The number of words in string are : " + str(res)) # write a program to print number of characters in a string str1 = 'It is a glorious day' res = len(str1) print("The number of characters in string are : ", str(res)) # write a funtion that accepts two lists of equal length and converts them into a dictioinary def list_to_dict(list1, list2): return dict(zip(list1, list2)) # write a python function that accepts a list of dictionaries and sorts it by a specified key def sort_dict_list(dict_list, sort_key): dict_list.sort(key=lambda item: item.get(sort_key)) # write a program to print the longest key in a dictioinary dict_1 = {"key1": 10, "keeeey2": 2, "ky3": 30} max_key='' for key in dict_1: if len(key)>len(max_key): max_key=key print(max_key) # write a program to capitalize the first and last character of each key in a dictionary input_dict = {'key_a': 10, 'kEy': 2, 'Key_B': 13} for key in list(input_dict.keys()): new_key = key[0].upper() + key[1:-1] + key[-1].upper() input_dict[new_key] = input_dict[key] if key != new_key: del input_dict[key] # write a program that iterates over a dictionary and prints "Bingo!" if length of value is greater than the length of key. Otherwise print "no bingo" key_val_map = {"key1": "length1", "key2": "len2", "Hello": "hi", "bingo": "print bingo"} for key, val in key_val_map.items(): if len(val) > len(key): print("Bingo!") else: print("no bingo") # write a python function that accepts a dictionary that has unique values and returns its inversion def invert_dict(input_dict): my_inverted_dict = {value: key for key, value in input_dict.items()} return my_inverted_dict # write a function that inverts a dictionary with non-unique values. Keys that map to the same values should be appended to a list in the inverted dictionary def invert_dict_non_unique(my_dict): my_inverted_dict = dict() for key, value in my_dict.items(): my_inverted_dict.setdefault(value, list()).append(key) return my_inverted_dict # write a program to merge a list of dictionaries into a single dictionary using dictionary comprehension input = [{"foo": "bar", "Hello": "World"}, {"key1": "val1", "key2": "val2"}, {"sample_key": "sample_val"}] merged_dict = {key: value for d in input for key, value in d.items()} # write a function to return the mean difference in the length of keys and values of dictionary comprising of strings only. def mean_key_val_diff(input_dict): sum_diff = 0 for key, val in input_dict.items(): sum_diff += abs(len(val) - len(key)) return sum_diff/len(input_dict) # write a program that prints the number of unique keys in a list of dictionaries. list_of_dicts = [{"key1": "val1", "Country": "India"}, {"Country": "USA", "foo": "bar"}, {"foo": "bar", "foo2":"bar2"}] unique_keys = [] for d in list_of_dicts: for key in d: if key not in unique_keys: unique_keys.append(key) print(f"Number of unique keys: {len(unique_keys)}") # write a Python program to replace the value of a particular key with nth index of value if the value of the key is list. test_list = [{'tsai': [5, 3, 9, 1], 'is': 8, 'good': 10}, {'tsai': 1, 'for': 10, 'geeks': 9}, {'love': 4, 'tsai': [7, 3, 22, 1]}] N = 2 key = "tsai" for sub in test_list: if isinstance(sub[key], list): sub[key] = sub[key][N] # write a program to convert a dictionary value list to dictionary list and prints it. test_list = [{'END' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}] res =[{} for idx in range(len(test_list))] idx = 0 for sub in test_list: for key, val in sub.items(): for ele in val: res[idx][key] = ele idx += 1 idx = 0 print("Records after conversion : " + str(res)) # write a program to convert a list of dictionary to list of tuples and print it. ini_list = [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] temp_dict = {} result = [] for ini_dict in ini_list: for key in ini_dict.keys(): if key in temp_dict: temp_dict[key] += ini_dict[key] else: temp_dict[key] = ini_dict[key] for key in temp_dict.keys(): result.append(tuple([key] + temp_dict[key])) print("Resultant list of tuples: {}".format(result)) # write a program that categorizes tuple values based on second element and prints a dictionary value list where each key is a category. test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)] res = {} for i, j in test_list: res.setdefault(j, []).append(i) print("The dictionary converted from tuple list : " + str(res)) # write a Python3 program that prints a index wise product of a Dictionary of Tuple Values test_dict = {'END Program' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)} prod_list=[] for x in zip(*test_dict.values()): res = 1 for ele in x: res *= ele prod_list.append(res) res = tuple(prod_list) print("The product from each index is : " + str(res)) # write a program to Pretty Print a dictionary with dictionary values. test_dict = {'tsai' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}} print("The Pretty Print dictionary is : ") for sub in test_dict: print(f"\n{sub}") for sub_nest in test_dict[sub]: print(sub_nest, ':', test_dict[sub][sub_nest]) # write a program to sort a nested dictionary by a key and print the sorted dictionary test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17}, 'Akshat' : {'roll' : 54, 'marks' : 12}, 'Akash' : { 'roll' : 12, 'marks' : 15}} sort_key = 'marks' res = sorted(test_dict.items(), key = lambda x: x[1][sort_key]) print("The sorted dictionary by marks is : " + str(res)) # write a python function to combine three lists of equal lengths into a nested dictionary and return it def lists_to_dict(test_list1, test_list2, test_list3): res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)] return res # write a program to print keys in a dictionary whose values are greater than a given input. test_dict = {'tsai' : 4, 'random_key' : 2, 'foo' : 3, 'bar' : 'END'} K = 3 res = {key : val for key, val in test_dict.items() if type(val) != int or val > K} print("Values greater than K : ", res.keys()) # write a function that converts a integer dictionary into a list of tuples. def dict_to_tuple(input_dict): out_tuple = [(a, b) for a,b in input_dict.items()] return out_tuple # write a python function to return a flattened dictionary from a nested dictionary input def flatten_dict(dd, separator ='_', prefix =''): flattened = { prefix + separator + k if prefix else k : v for kk, vv in dd.items() for k, v in flatten_dict(vv, separator, kk).items() } if isinstance(dd, dict) else { prefix : dd } return flattened # write a program that prints dictionaries having key of the first dictionary and value of the second dictionary test_dict1 = {"tsai" : 20, "is" : 36, "best" : 100} test_dict2 = {"tsai2" : 26, "is2" : 19, "best2" : 70} keys1 = list(test_dict1.keys()) vals2 = list(test_dict2.values()) res = dict() for idx in range(len(keys1)): res[keys1[idx]] = vals2[idx] print("Mapped dictionary : " + str(res)) # write a program to combine two dictionaries using a priority dictionary and print the new combined dictionary. test_dict1 = {'Gfg' : 1, 'is' : 2, 'best' : 3} test_dict2 = {'Gfg' : 4, 'is' : 10, 'for' : 7, 'geeks' : 12} prio_dict = {1 : test_dict2, 2: test_dict1} res = prio_dict[2].copy() for key, val in prio_dict[1].items(): res[key] = val print("The dictionary after combination : " + str(res)) # write a Python program to combine two dictionary by adding values for common keys dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass # write a Python program that sorts dictionary keys to a list using their values and prints this list. test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3} res = list(sum(sorted(test_dict.items(), key = lambda x:x[1]), ())) print("List after conversion from dictionary : ", res) # write a program to concatenate values with same keys in a list of dictionaries. Print the combined dictionary. test_list = [{'tsai' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, {'tsai' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, {'tsai' : [7, 5], 'best' : [5, 7]}] res = dict() for inner_dict in test_list: for inner_list in inner_dict: if inner_list in res: res[inner_list] += (inner_dict[inner_list]) else: res[inner_list] = inner_dict[inner_list] print("The concatenated dictionary : " + str(res)) # write a python program to print the top N largest keys in an integer dictionary. test_dict = {6 : 2, 8: 9, 3: 9, 10: 8} N = 4 res = [] for key, val in sorted(test_dict.items(), key = lambda x: x[0], reverse = True)[:N]: res.append(key) print("Top N keys are: " + str(res)) # write a program to print the values of a given extraction key from a list of dictionaries. test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}] K = 'Best' res = [sub[K] for sub in test_list if K in sub][0] print("The extracted value : " + str(res)) # write a program to convert date to timestamp and print the result import time import datetime str1 = "20/01/2020" element = datetime.datetime.strptime(str1,"%d/%m/%Y") timestamp = datetime.datetime.timestamp(element) print(timestamp) # write a program to print the product of integers in a mixed list of string and numbers test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2] res = 1 for ele in test_list: try: res *= int(ele) except : pass print("Product of integers in list : " + str(res)) # write a python program to add an element to a list. Print the final list. lst = ["Jon", "Kelly", "Jessa"] lst.append("Scott") print(lst) # write a python function to append all elements of one list to another def extend_list(list1, list2): list1 = [1, 2] list2 = [3, 4] return list1.extend(list2) # write a python function to add elements of two lists def add_two_lists(list1, list2): list1 = [1, 2, 3] list2 = [4, 5, 6] sum_list = [] for (item1, item2) in zip(list1, list2): sum_list.append(item1+item2) return sum_list # Write a python program to print the last element of a list list1 = ['p','r','o','b','e'] print(list1[-1]) # Write a python program to print positive Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num >= 0: print(num, end = " ") # Write a python function to multiply all values in a list def multiplyList(myList) : result = 1 for x in myList: result = result * x return result # Write a python program to print the smallest number in a list list1 = [10, 20, 1, 45, 99] print("Smallest element is:", min(list1)) # Write a python program to remove even numbers from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] for ele in list1: if ele % 2 == 0: list1.remove(ele) print("New list after removing all even numbers: ", list1) # Write a python program to print a list after removing elements from index 1 to 4 list1 = [11, 5, 17, 18, 23, 50] del list1[1:5] print(*list1) # Write a python program to remove 11 and 18 from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] unwanted_num = {11, 18} list1 = [ele for ele in list1 if ele not in unwanted_num] print("New list after removing unwanted numbers: ", list1) # Write a python program to Remove multiple empty spaces from List of strings. Print the original and final lists. test_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] print("The original list is : " + str(test_list)) res = [ele for ele in test_list if ele.strip()] print("List after filtering non-empty strings : " + str(res)) # Write a python function to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Write a python program to print if a string "hello" is present in the list l = [1, 2.0, 'hello','have', 'a', 'good', 'day'] s = 'hello' if s in l: print(f'{s} is present in the list') else: print(f'{s} is not present in the list') # Write a python program to print the distance between first and last occurrence of even element. test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11] indices_list = [idx for idx in range( len(test_list)) if test_list[idx] % 2 == 0] res = indices_list[-1] - indices_list[0] print("Even elements distance : " + str(res)) # Write a python fuction to create an empty list def emptylist(): return list() # Write a python program to print a list with all elements as 5 and of length 10 list1 = [5] * 10 print(list1) # Write a python program to reverse a list and print it. def Reverse(lst): return [ele for ele in reversed(lst)] lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst)) # Write a python program to print odd numbers in a List list1 = [10, 21, 4, 45, 66, 93, 11] odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) # Write a python program to print negative Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num < 0: print(num, end = " ") # Write a python program print the the number of occurrences of 8 in a list def countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print('{} has occurred {} times'.format(x, countX(lst, x))) # Write a python program to swap first and last element of a list . Print the final list def swapList(newList): size = len(newList) # Swapping temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList newList = [12, 35, 9, 56, 24] print(swapList(newList)) # Write a python program to convert each list element to key-value pair. Print the final dictionary test_list = [2323, 82, 129388, 234, 95] print("The original list is : " + str(test_list)) res = dict() for ele in test_list: mid_idx = len(str(ele)) // 2 key = int(str(ele)[:mid_idx]) val = int(str(ele)[mid_idx:]) res[key] = val print("Constructed Dictionary : " + str(res)) # Write a python program for print all elements with digit 7. test_list = [56, 72, 875, 9, 173] K = 7 res = [ele for ele in test_list if str(K) in str(ele)] print("Elements with digit K : " + str(res)) # Write a python program for printing number of unique elements in a list input_list = [1, 2, 2, 5, 8, 4, 4, 8] l1 = [] count = 0 for item in input_list: if item not in l1: count += 1 l1.append(item) print("No of unique items are:", count) # Write a python program to find the sum and average of the list. Print the sum and average L = [4, 5, 1, 2, 9, 7, 10, 8] count = 0 for i in L: count += i avg = count/len(L) print("sum = ", count) print("average = ", avg) # Write a python program to Remove Tuples of Length 1 from a list of tuples. Print the final list. test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] K = 1 res = [ele for ele in test_list if len(ele) != K] print("Filtered list : " + str(res)) # Write a python program to print a list of tuples from given list having number and its cube in each tuple list1 = [1, 2, 5, 6] res = [(val, pow(val, 3)) for val in list1] print(res) # Write a python program to print the combination of tuples in list of tuples test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] res = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] print("The list tuple combination : " + str(res)) # Write a python program to swap tuple elements in list of tuples. Print the output. test_list = [(3, 4), (6, 5), (7, 8)] res = [(sub[1], sub[0]) for sub in test_list] print("The swapped tuple list is : " + str(res)) # Write a python function to sort a list of tuples by the second Item def Sort_Tuple(tup): lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Write a python program to print all pair combinations of 2 tuples. test_tuple1 = (4, 5) test_tuple2 = (7, 8) res = [(a, b) for a in test_tuple1 for b in test_tuple2] res = res + [(a, b) for a in test_tuple2 for b in test_tuple1] print("The filtered tuple : " + str(res)) # Write a python program to print positive Tuples in List. test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] print("The original list is : " + str(test_list)) res = [sub for sub in test_list if all(ele >= 0 for ele in sub)] print("Positive elements Tuples : " + str(res)) # Write a python program to join Tuples from a list of tupels if they have similar initial element. Print out the output test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)] print("The original list is : " + str(test_list)) res = [] for sub in test_list: if res and res[-1][0] == sub[0]: res[-1].extend(sub[1:]) else: res.append([ele for ele in sub]) res = list(map(tuple, res)) print("The extracted elements : " + str(res)) # Write a python program to print the uncommon elements in List test_list1 = [ [1, 2], [3, 4], [5, 6] ] test_list2 = [ [3, 4], [5, 7], [1, 2] ] res_list = [] for i in test_list1: if i not in test_list2: res_list.append(i) for i in test_list2: if i not in test_list1: res_list.append(i) print ("The uncommon of two lists is : " + str(res_list)) # write a Function to convert the time from 12 hour format to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] #!/usr/bin/env python # coding: utf-8 # In[7]: # write a python class that defines a Tree and add child class TreeNode: def __init__(self, data): self.data = data self.parent = None self.children =[] def add_child(self, child): child.parent = self self.children.append(child) t = TreeNode("Arun") t.add_child(TreeNode("Shruthi")) # In[63]: # write a python function that takes two path strings and return the combined path string import os def path_join(PARENT_DIR, DIR): joined_path = os.path.join(PARENT_DIR, DIR) return joined_path path_join("C:/", "DATA") # In[78]: # write a python function to read a text file and return the result def read_file(filepath='test.txt'): with open(filepath, 'r') as file_reader: f_read = file_reader.read() return f_read read_file() # In[83]: # write a python function to read a text file, if no filepath is given raise Exception def read_file(filepath=None): if filepath: with open(filepath, 'r') as file_reader: f_read = file_reader.read() return f_read else: raise Exception("filepath not found") read_file() # In[87]: # write a python program to handle exception when a given value is less than 10 def check(x): if x < 10: raise ValueError('x should not be less than 10!') else: return x check(9) # In[104]: # write a python function to check if the given structure is a instance of list or dictionary def check_insst(obj): if isinstance(obj, list): return "list" elif isinstance(obj, dict): return "dict" else: return "unknown" check_insst({}) # In[102]: # write a python function to check if the given structure is a instance of tuple or string def check_inst_tup_str(obj): if isinstance(obj, set): return "set" elif isinstance(obj, tuple): return "tuple" else: return "unknown" check_inst_tup_str({1}) # In[110]: # write a python class to instantiate an object with two string attributes and write a function to return the list of attributes class Myclass: def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def get_attributes_list(self): return [self.attr1, self.attr2] dress = Myclass("pant","shirt") dress.get_attributes_list() # In[114]: # write a python function that call another function and that function prints "Inside B" def A(): B() def B(): print("Inside B") A() # In[119]: # write a python program to return the biggest character in a string (printable ascii characters) from functools import reduce input_str = 'tsai' res = reduce(lambda x, y: x if ord(x) > ord(y) else y, input_str) print(f"{res}") # In[120]: # write a python program to adds every 3rd number in a list from functools import reduce input_list = [x for x in range(10)] res = reduce(lambda x, y: x+y, [i for idx, i in enumerate(input_list) if (idx+1)%3==0]) print(f"{res}") # In[111]: # write a python program which iterates two lists of numbers simultaneously and adds corresponding values, print the result f_list = [1,2,3,4] s_list = [2,3,4,5] res = [f_n +s_n for f_n, s_n in zip(f_list, s_list)] print(f"{res}") # In[19]: # write a python function that takes a list of numbers and calculate square of each number and return it in a list def square_num(mynumbers): return list(map(lambda num: num**2,mynumbers)) square_num([1,2,3]) # In[21]: # write a python function that takes two lists and combines them without any duplicates and return the list def combine_lists(L1, L2): return L1 + [items for items in L2 if items not in L1] L1 = [1,2,3] L2 = [2,4,3] combine_lists(L1,L2) # In[29]: # write a python function that removes all the vowels from the given list of strings and return the list def myfunc(listitems): final=[] for strchar in listitems: for letters in strchar: if letters in ('a','e','i','o','u', 'A','E','I','O','U'): strchar = strchar.replace(letters,"") final.append(strchar) return final myfunc(["rohan", "END"]) # In[43]: # write a python program to print all the keys in the dictionary and store it in a list sample_dict = {'1':1, '2':2, '3':3} key_list = list(sample_dict.keys()) print(f"{key_list}") # In[45]: # write a python program to remove duplicates from a list and print the result in list input_list = [1,2,3,4,4,33,2,5] dedup = list(set(input_list)) print(f"{dedup}") # In[46]: # write a python function that takes a list of elements and n as input, extract and append first n characters and last n characters of each string and return the resultant list def nchar (list1,no): return [items[:no]+items[-no:] for items in list1] list1 = ["ROHAN", "END"] nchar(list1, 3) # In[56]: # write a python function that takes two parameters, first parameter is a list of dictionary and second is a list of tuples. Append the list of tuples to the list of dictionary def addentry (listname, addlist): for names,ages in addlist: listname.append(addlist) return listname addentry([{'1':"A"}], [("2", "B")]) # In[57]: # write a python function that takes a dictionary and a string, appends the string to the list of values def addnames_in_dict (dictname, name): for i in dictname: dictname[i].append(name) return dictname addnames_in_dict({"1":["A"]}, "Arun") # In[59]: # write a python program to iterate through the list and create a dictionary with integers as keys list_= [1,2,3,4] dict_comp = {idx:value for idx,value in enumerate(list_)} print(f"{dict_comp}") # In[60]: # write a python function to add all even numbers between minimum and maximum value def add_even_num(min, max): return sum([i for i in range(min, max) if i%2==0]) add_even_num(1, 6) # In[123]: # write a python program to iterate through a string using for loop h_letters = [] for letter in 'human': h_letters.append(letter) print(f"{h_letters}") # In[127]: # write a python program to iterate through a string using lambda and print the result letters = list(map(lambda x: x, 'human')) print(letters) # In[129]: # write a python function to calculate the price after tax for a list of transactions txns = [1.09, 23.56, 57.84, 4.56, 6.78] TAX_RATE = .08 def get_price_with_tax(txn): return txn * (1 + TAX_RATE) final_prices = list(map(get_price_with_tax, txns)) print(f"{final_prices}") # In[138]: # write a python program to print python version using sys import sys print(f"{sys.version}") # In[144]: # write a python program to merge two sorted lists a = [3, 4, 6, 10, 11, 18] b = [1, 5, 7, 12, 13, 19, 21] a.extend(b) c = sorted(a) print(f"{c}") # In[146]: # write a python program to index every 4th character from the below string code = 'varCjjlopaxntrrgnbXrOPraiiItUuUuzaQlliyaxx*t#rgiffFoce&ntPls87C!' code[3::4] # In[149]: # write a python program to split a string based on space strin = "Hello how are you ?" res = strin.split() print(f"{res}") # In[151]: # write a python program to convert a dictionary to list of tuples dict_new = {'1':'A', '2':'B'} tup = dict_new.items() print(list(tup)) # In[153]: # write a python program to remove an element from a list li = [1, 2, 3, 4] li.remove(1) li # In[140]: # write a python program to print system time import time print(f"{time.time()}") # In[143]: # write a python function to inherit a parent class person in a child class Student class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): pass # In[130]: # write a python program to replace all the negative values to zero and keep only positive values in the list original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] print(f"{prices}") # In[133]: # write a python function to generate random number between a given range import random def get_weather_data(min, max): return random.randrange(min, max) rand_num = get_weather_data(11, 20) print(f"{rand_num}") # In[135]: # write a python function which uses generator to sum all the numbers in a range min_value = 10 max_value = 10000 sum_all = sum(i * i for i in range(min_value, max_value)) print(f"{sum_all}") # In[126]: # write a python program to transpose Matrix using Nested Loops and print the result transposed = [] matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] for i in range(len(matrix[0])): transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed.append(transposed_row) print(f"{transposed}") # In[142]: # write a python function to create two threads and start and join the two threads import threading def print_cube(num): print("Cube: {}".format(num * num * num)) t1 = threading.Thread(target=print_cube, args=(10,)) t2 = threading.Thread(target=print_cube, args=(10,)) t1.start() t2.start() t1.join() t2.join() # In[145]: # write a python function which is decorated on another function def myDecorator(func): def new_func(n): return '$' + func(n) return new_func @myDecorator def myFunction(a): return(a) # call the decorated function print(myFunction('100')) # -*- coding: utf-8 -*- """Assignment8_part2_python_programs.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1L3UkCJFHDkuGHoibhSFxZVESxbw0NUrz """ ## write a python function to convert given variable to said datatype def type_conversion(typ,a): if(typ)=='int': return(int(a)) elif(typ)=='float': return(float(a)) else: return(str(a)) type_conversion('str',1) ## Write a python class to welcome class Welcome(object): # Constructor def __init__(self, name): self.name = name # Create an instance variable # Instance method def welcome(self, up=False): if up: print('Hi, %s!' % self.name.upper()) else: print('Hey, %s' % self.name) w = Welcome('Geeta') w.welcome(up=True) ## 3. Write a program to reverse dictionary key order sample_dict = {1:'Hi',2:'Hello',3:'Hey'} print("The original dictionary : " + str(sample_dict)) res = dict(reversed(list(sample_dict.items()))) print("The reversed order dictionary : " + str(res)) ## Write a program to reverse the key and item mapping sample_dict = {1:'Seeta',2:'Geeta',3:'Babita'} print("The original dictionary : " + str(sample_dict)) sample_dict = {v:k for k, v in sample_dict.items()} print("Inverse mapped dictionary : ", str(sample_dict)) # Write a program to generate the Fibonacci sequence up to n-th term nterms = int(10000) # first two terms n1, n2 = 0, 1 count = 0 fab_list = [] # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: while count < nterms: #print(n1) fab_list.append(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 fn = lambda x: "FIBONACCI" if x in fab_list else "NOT_FIBONACCI" print("Given number is",fn(20)) # Write a python function to add 2 iterables a and b such that a is even and b is odd n=10 a = [] b = [] _ = [a.append(i) if i%2==0 else b.append(i) for i in range(n)] def add(a,b): return [a+b for a,b in (zip(a,b))] add(a,b) # 6. Write a program to strips every vowel from a string provided vowels = ('a', 'e', 'i', 'o', 'u') input_string = "hello" print('Vowel in a string',' '.join([x for x in input_string.lower() if x not in vowels])) # Write a python function that takes a small character string and shifts all characters by 5 def shift_n_letters(letter, n): return chr((ord(letter) - 97 + n % 26) % 26 + 97) if ord(letter)>=97 else chr((ord(letter) - 65 + n % 26) % 26 + 65) name = "hello" res="".join([shift_n_letters(x,5) for x in name]) print('Resulting string',res) # Write a python function to add only even numbers in a list from functools import reduce input_list = [x for x in range(100)] def sum_even(it): return reduce(lambda x, y: x + y if (y % 2)==0 else x, it, 0) res=sum_even(input_list) print('Sum of even numbers in the list is ', res) # write a program to adds every 5th number in a list input_list = [x for x in range(20)] res=reduce((lambda x, y: x + y), [val for idx, val in enumerate(input_list) if (idx+1)%5==0]) print('Sum of every 5th element in the list is', res) # Write a python function to identify type of given data structure def ds_type(ds): return(type(ds)) l=[1,2,3,4] ds_type(l) # Write a python function to remove duplicates from list def remove_duplicates(lista): lista2 = [] if lista: for item in lista: if item not in lista2: #is item in lista2 already? lista2.append(item) else: return lista return lista2 print("List with duplicates removed:",remove_duplicates([1,2,3,3])) # Write a python function get unique value from tuple def unique_values(v): return(list(set(v))) t=[(1,2),(3,4),(4,3),(1,2)] unique_values(t) # write a program to convert temperature from Celsius to Fahrenheit Cel = 90 Far = 9.0/5.0 * Cel + 32 print("Temperature:", Cel, "Celsius = ", Far, " F") # Write a program to convert kilometers per hour to mile per hour kmh = 16 mph = 0.6214 * kmh print("Speed:", kmh, "KM/H = ", mph, "MPH") # Write a python function to find greatest common divisor def greatest_common_divisor(x,y): print("For", x, "and", y,"," ) r=x%y while r>0: r=x%y if r ==0: print("the greatest common divisor is", y,".") else: q=y x=q y=r greatest_common_divisor(1071,1029) # Write a program to check your external ip address import re import requests url = "http://checkip.dyndns.org" request = requests.get(url) clean = request.text.split(': ', 1)[1] your_ip = clean.split('', 1)[0] print("your IP Address is: ", your_ip) # Write a python function to generate a random password import random LOWERCASE_CHARS = tuple(map(chr, range(ord('a'), ord('z')+1))) UPPERCASE_CHARS = tuple(map(chr, range(ord('A'), ord('Z')+1))) DIGITS = tuple(map(str, range(0, 10))) SPECIALS = ('!', '@', '#', '$', '%', '^', '&', '*') SEQUENCE = (LOWERCASE_CHARS, UPPERCASE_CHARS, DIGITS, SPECIALS, ) def generate_random_password(total, sequences): r = _generate_random_number_for_each_sequence(total, len(sequences)) password = [] for (population, k) in zip(sequences, r): n = 0 while n < k: position = random.randint(0, len(population)-1) password += population[position] n += 1 random.shuffle(password) while _is_repeating(password): random.shuffle(password) return ''.join(password) def _generate_random_number_for_each_sequence(total, sequence_number): """ Generate random sequence with numbers (greater than 0). The number of items equals to 'sequence_number' and the total number of items equals to 'total' """ current_total = 0 r = [] for n in range(sequence_number-1, 0, -1): current = random.randint(1, total - current_total - n) current_total += current r.append(current) r.append(total - sum(r)) random.shuffle(r) return r def _is_repeating(password): """ Check if there is any 2 characters repeating consecutively """ n = 1 while n < len(password): if password[n] == password[n-1]: return True n += 1 return False if __name__ == '__main__': print(generate_random_password(random.randint(6, 30), SEQUENCE)) # Write a python function to get a user name from prompt #get the username from a prompt username = input("Login: >> ") #list of allowed users user1 = "Ram" user2 = "Mohan" #control that the user belongs to the list of allowed users if username == user1: print("Access granted") elif username == user2: print("Welcome to the system") else: print("Access denied") # Write a python function to convert hours to either mins or seconds def convert_to_minutes(num_hours): '''(int) -> int Return the number of minutes there are in num_hours hours. ''' minutes = num_hours * 60 return minutes def convert_to_seconds(num_hours): '''(int) -> int Return the number of seconds there are in num_hours hours. ''' minutes = convert_to_minutes(num_hours) seconds = minutes * 60 return seconds min = convert_to_minutes(1) print(min) seconds = convert_to_seconds(1) print(seconds) # Write python function role a dice import random min = 1 max = 6 roll_again = "yes" while roll_again == "yes" or roll_again == "y": print("Rolling the dices...") print("The values are....") print(random.randint(min, max)) print(random.randint(min, max)) roll_again = input("Roll the dices again?") # Write a program to reverse a number n=int(input("Enter number: ")) rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 print("Reverse of the number:",rev) # Write a program to take an average of given scores s1=50 s2=77 s3=87 print('Avg score is',(s1+s2+s3)/3) # Write a python program to print odd numbers in given range lower=int(input("Enter the lower limit for the range:")) upper=int(input("Enter the upper limit for the range:")) for i in range(lower,upper+1): if(i%2!=0): print(i) # Write a python program print all the integers that arenā€™t divisible by either 2 or 3 and lies between 1 and 25. for i in range(0,25): if(i%2!=0 and i%3!=0): print(i) # Write a program to concatinate two strings # Python String Operations str1 = 'Good' str2 ='Morning!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3) # Write python function to convert a given string to either lower, upper and capitalize def string_opertaion(st,conversion): if(conversion=='lower'): return(st.lower()) elif(conversion=='upper'): return(st.upper()) else: return(st.capitalize()) string_opertaion('AwesOME',None) # Write a program to get 3rd and last character of a given string string="Good Night" print("\nSlicing characters between " + "3rd and last character: ") print(string[3:-1]) # Write a program to delete a 3rd character from a given string String='welcome' new_str = "" for i in range(len(String)): if i != 2: new_str = new_str + String[i] print(new_str) # Write a program to replace a string by a given string #in a sentence string = 'This is beautiful picture' string.replace('beautiful','good') # Write a program to reverse a string string = 'Today is bad day' string[::-1] # Write a python function to append or extend two lists def list_op(l1,l2,op): if(op=='append'): return(l1.append(l2)) else: return(l1.extend(l2)) a = ['Hey', 'you', 'there!'] b = [1,2,3] op='e' list_op(a,b,op) print(a) #!/usr/bin/env python # coding: utf-8 # In[28]: # write python function get the unique number of elements from the user given list mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow'] def get_unique_elements(list): unique = [x for i, x in enumerate(mylist) if i == mylist.index(x)] return unique get_unique_elements(mylist) # In[86]: # write a python function get the maximum number in passed list def max_check(x): max_val = x[0] for check in x: if check > max_val: max_val = check return max_val print(f'{max_check([2,4,5,7,98])}') # In[88]: # write a python function to get the minimum number in passed list def min_check(x): min_val = x[0] for check in x: if check < min_val: min_val = check return min_val print(f'{min_check([2,4,5,7,98])}') # In[1]: # write a program to reverse the list elemnets list_ = [40,0,1,29,3] rev_list = list_[::-1] print(f'reversed list: {rev_list}') # In[7]: # write a progarm to sort the list in assending order data_list = [-5, -23, 5, 0, 23, -6, 23, 67] new_list = [] while data_list: minimum = data_list[0] # arbitrary number in list for x in data_list: if x < minimum: minimum = x new_list.append(minimum) data_list.remove(minimum) print(f'assending_order_list: {new_list}') # In[8]: # write a program to sort the list in desending order data_list = [-5, -23, 5, 0, 23, -6, 23, 67] new_list = [] while data_list: minimum = data_list[0] # arbitrary number in list for x in data_list: if x > minimum: minimum = x new_list.append(minimum) data_list.remove(minimum) print(f'decending_order_list: {new_list}') # In[11]: # write a python function to sort a list of tuples by the second Item def Sort_Tuple(tup): # getting length of list of tuples lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Driver Code tup =[('for', 24), ('is', 10), ('to', 28), ('goal', 1), ('portal', 20), ('a', 15)] Sort_Tuple(tup) # In[12]: # write a program to insert elemnet in the list after every nth element letters = ['a','b','c','d','e','f','g','h','i','j'] i = 3 while i < len(letters): letters.insert(i, 'x') i += 4 letters # In[22]: # write a program to find sum of elements in list total = 0 print(f'sum: {sum([total + x for x in [1, 2, 3, 4, 5]])}') # In[23]: # write a program to get th ematched elemnets from two list a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] [i for i, j in zip(a, b) if i == j] # In[24]: # write a program to get the matched elements from two list a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] [i for i, j in zip(a, b) if i != j] # In[31]: # write a python program to create dictionary from the lists L1 = ['a','b','c','d'] L2 = [1,2,3,4] d = dict(zip(L1,L2)) print(f'dictionary:{d}') # In[45]: # write a program to convert given dictonary to list of list key value pairs d = {'Food':'Fish&Chips','2012':'Olympics','Capital':'London'} list_key_value = [ [k,v] for k, v in d.items() ] print(f'lsit_key_value:{list_key_value}') # In[53]: # write program to Compare two dictionaries and check how many (key, value) pairs are equal x = {"a":2,"b":2,"c":3,"d":4} y = {"b":2,"c":3, "d":4} shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]} length = len(shared_items) print(f'count:{length}') # In[63]: # write a python function get the random number from the given range and square the number import random min_value = 10 max_value = 20 def square(x): return x*x def get_square_of_random_number(min_value,max_value): return square(random.randint(min_value,max_value)) get_square_of_random_number(min_value,max_value) # In[67]: # write a python function to identify the total counts of chars, digits,and symbols for given input string def findDigitsCharsSymbols(inputString): charCount = 0 digitCount = 0 symbolCount = 0 for char in inputString: if char.islower() or char.isupper(): charCount+=1 elif char.isnumeric(): digitCount+=1 else: symbolCount+=1 print("Chars = ", charCount, "Digits = ", digitCount, "Symbol = ", symbolCount) inputString = "P@#yn26at^&i5ve" print("total counts of chars, digits,and symbols \n") findDigitsCharsSymbols(inputString) # In[71]: # write a python function to find all occurrences of user given substring in user provided input string ignoring the case def count_word_occurrences(inputstring,substring): inputstring = inputstring tempString = inputString.lower() count = tempString.count(substring.lower()) return print(f'Given substring count is :{count}') inputString = "Welcome to USA. usa awesome, isn't it?" substring = "USA" count_word_occurrences(inputString,substring) # In[74]: # write a program that prints the sum and average of the digits that appear in the string, ignoring all other characters import re inputStr = "English = 78 Science = 83 Math = 68 History = 65" markList = [int(num) for num in re.findall(r'\b\d+\b', inputStr)] totalMarks = 0 for mark in markList: totalMarks+=mark percentage = totalMarks/len(markList) print(f'Total Marks is:{totalMarks},Percentage is:{percentage}') # In[75]: # write a python funaction to create a new string by appending second string in the middle of first string def appendMiddle(s1, s2): middleIndex = int(len(s1) /2) print("Original Strings are", s1, s2) middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:] print("After appending new string in middle", middleThree) appendMiddle("bananna", "monkey") # In[81]: # write a program to find the last position of a given substring in a given string str1 = "Emma is a data scientist who knows Python. Emma works at google." print(f"Original String is: {str1}") index = str1.rfind("Emma") print(f"Last occurrence of Emma starts at {index}") # In[82]: # write a program to remove the empty list from the given list str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""] print(str_list) # use built-in function filter to filter empty value new_str_list = list(filter(None, str_list)) print("After removing empty strings") print(new_str_list) # In[85]: # write a program from given string replace each punctuation with # from string import punctuation str1 = '/*Jon is @developer & musician!!' print(f"The original string is :{str1}") # Replace punctuations with # replace_char = '#' for char in punctuation: str1 = str1.replace(char, replace_char) print(f"The strings after replacement : {str1}") # In[90]: # write a program to convert all the sentances present in the list to upper mylis = ['this is test', 'another test'] print(f'{[item.upper() for item in mylis]}') # In[96]: # write a progarm to adds every 3rd number in a list from functools import reduce input_list = [x for x in range(10)] reduce((lambda x, y: x + y), [val for idx, val in enumerate(input_list) if (idx+1)%3==0]) # In[97]: # write a program to strips every vowel from a string provided vowels = ('a', 'e', 'i', 'o', 'u') input_string = "awesome" ' '.join([x for x in input_string.lower() if x not in vowels]) # Given a string, find the length of the longest substring without repeating characters. str = "piyushjain" def longest_non_repeat(str): i=0 max_length = 1 for i,c in enumerate(str): start_at = i sub_str=[] while (start_at < len(str)) and (str[start_at] not in sub_str): sub_str.append(str[start_at]) start_at = start_at + 1 if len(sub_str) > max_length: max_length = len(sub_str) print(sub_str) return max_length longest_non_repeat(str) # Given an array of integers, return indices of the two numbers such that they add up to a specific target. input_array = [2, 7, 11, 15] target = 26 result = [] for i, num in enumerate(input_array): for j in range(i+1, len(input_array)): print(i,j) # Given a sorted integer array without duplicates, return the summary of its ranges. input_array = [0,1,2,4,5,7] start=0 result = [] while start < len(input_array): end = start while end+1{1}".format(input_array[start], input_array[end])) print(result) else: result.append("{0}".format(input_array[start])) print(result) start = end+1 print(result) # Rotate an array of n elements to the right by k steps. org = [1,2,3,4,5,6,7] result = org[:] steps = 3 for idx,num in enumerate(org): if idx+steps < len(org): result[idx+steps] = org[idx] else: result[idx+steps-len(org)] = org[idx] print(result) # Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. first_array = [1,2,3,4,5,6,7] second_array = [3,7,2,1,4,6] def finder(first_array, second_array): return(sum(first_array) - sum(second_array)) missing_number = finder(first_array, second_array) print(missing_number) # Given a collection of intervals which are already sorted by start number, merge all overlapping intervals. org_intervals = [[1,3],[2,6],[5,10],[11,16],[15,18],[19,22]] i = 0 while i < len(org_intervals)-1: if org_intervals[i+1][0] < org_intervals[i][1]: org_intervals[i][1]=org_intervals[i+1][1] del org_intervals[i+1] i = i - 1 i = i + 1 print(org_intervals) # Given a list slice it into a 3 equal chunks and revert each list sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89] length = len(sampleList) chunkSize = int(length/3) start = 0 end = chunkSize for i in range(1, 4, 1): indexes = slice(start, end, 1) listChunk = sampleList[indexes] mylist = [i for i in listChunk] print("After reversing it ", mylist) start = end if(i != 2): end +=chunkSize else: end += length - chunkSize # write a program to calculate exponents of an input input = 9 exponent = 2 final = pow(input, exponent) print(f'Exponent Value is:{final}') # write a program to multiply two Matrix # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] print(f"Final Result is{result}") # write a program to find and print the remainder of two number num1 = 12 num2 = 10 ratio = num1 % num2 print(f'remainder:{ratio}') # reverse a number in Python number = 1367891 revs_number = 0 while (number > 0): remainder = number % 10 revs_number = (revs_number * 10) + remainder number = number // 10 print("The reverse number is : {}".format(revs_number)) # Python program to compute sum of digits in number def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) n = 1234511 print(sumDigits(n)) # Find the middle element of a random number list my_list = [4,3,2,9,10,44,1] print("mid value is ",my_list[int(len(my_list)/2)]) # Sort the list in ascending order my_list = [4,3,2,9,10,44,1] my_list.sort() print(f"Ascending Order list:,{my_list}") # Sort the list in descending order my_list = [4,3,2,9,10,44,1] my_list.sort(reverse=True) print(f"Descending Order list:,{my_list}") # Concatenation of two List my_list1 = [4,3,2,9,10,44,1] my_list2 = [5,6,2,8,15,14,12] print(f"Sum of two list:,{my_list1+my_list2}") # Removes the item at the given index from the list and returns the removed item my_list1 = [4,3,2,9,10,44,1,9,12] index = 4 print(f"Sum of two list:,{my_list1.pop(index)}") # Adding Element to a List animals = ['cat', 'dog', 'rabbit'] animals.append('guinea pig') print('Updated animals list: ', animals) # Returns the number of times the specified element appears in the list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] count = vowels.count('i') print('The count of i is:', count) # Count Tuple Elements Inside List random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] count = random.count(('a', 'b')) print("The count of ('a', 'b') is:", count) # Removes all items from the list list = [{1, 2}, ('a'), ['1.1', '2.2']] list.clear() print('List:', list) # access first characters in a string word = "Hello World" letter=word[0] print(f"First Charecter in String:{letter}") # access Last characters in a string word = "Hello World" letter=word[-1] print(f"First Charecter in String:{letter}") # Generate a list by list comprehension list = [x for x in range(10)] print(f"List Generated by list comprehension:{list}") # Sort the string list alphabetically thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(f"Sorted List:{thislist}") # Join Two Sets set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set2.union(set1) print(f"Joined Set:{set3}") # keep only the items that are present in both sets x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(f"Duplicate Value in Two set:{x}") # Keep All items from List But NOT the Duplicates x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(f"Duplicate Value in Two set:{x}") # Create and print a dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Sample Dictionary:{thisdict}") # Calculate the length of dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Length of Dictionary:{len(thisdict)}") # Evaluate a string and a number print(bool("Hello")) print(bool(15)) # Calculate length of a string word = "Hello World" print(f"Length of string: {len(word)}") # Count the number of spaces in a sring s = "Count, the number of spaces" lenx = s.count(' ') print(f"number of spaces in sring: {lenx}") # Split Strings word = "Hello World" ksplit = word.split(' ') print(f"Splited Strings: {ksplit}") # Prints ten dots ten = "." * 10 print(f"Ten dots: {ten}") # Replacing a string with another string word = "Hello World" replace = "Bye" input = "Hello" after_replace = word.replace(input, replace) print(f"String ater replacement: {after_replace}") #removes leading characters word = " xyz " lstrip = word.lstrip() print(f"String ater removal of leading characters:{lstrip}") #removes trailing characters word = " xyz " rstrip = word.rstrip() print(f"String ater removal of trailing characters:{rstrip}") # check if all char are alphanumeric word = "Hello World" check = word.isalnum() print(f"All char are alphanumeric?:{check}") # check if all char in the string are alphabetic word = "Hello World" check = word.isalpha() print(f"All char are alphabetic?:{check}") # test if string contains digits word = "Hello World" check = word.isdigit() print(f"String contains digits?:{check}") # Test if string contains upper case word = "Hello World" check = word.isupper() print(f"String contains upper case?:{check}") # Test if string starts with H word = "Hello World" check = word.startswith('H') print(f"String starts with H?:{check}") # Returns an integer value for the given character str = "A" val = ord(str) print(f"Integer value for the given character?:{val}") # Fibonacci series up to 100 n = 100 result = [] a, b = 0 , 1 while b < n: result. append( b) a, b = b, a + b final = result print(f"Fibonacci series up to 100:{final}") # Counting total Digits in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isdigit()): digitCount += 1 print('Number of digits: ',digitCount) # Counting total alphanumeric in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isalpha()): digitCount += 1 print('Number of alphanumeric: ',digitCount) # Counting total Upper Case in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.upper()): digitCount += 1 print('Number total Upper Case: ',digitCount) # Counting total lower Case in a string str1 = "abc4234AFdeaa" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.lower()): digitCount += 1 print('Number total lower Case: ',digitCount) # Bubble sort in python list1 = [1, 5, 3, 4] for i in range(len(list1)-1): for j in range(i+1,len(list1)): if(list1[i] > list1[j]): temp = list1[i] list1[i] = list1[j] list1[j] = temp print("Bubble Sorted list: ",list1) # Compute the product of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a*b for a in list1 for b in list2] print(f"Product of every pair of numbers from two lists:{final}") # Calculate the sum of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a+b for a in list1 for b in list2] print(f"sum of every pair of numbers from two lists:{final}") # Calculate the pair-wise product of two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [list1[i]*list2[i] for i in range(len(list1))] print(f"pair-wise product of two lists:{final}") # Remove the last element from the stack s = [1,2,3,4] print(f"last element from the stack:{s.pop()}") # Insert a number at the beginning of the queue q = [1,2,3,4] q.insert(0,5) print(f"Revised List:{q}") # Addition of two vector v1 = [1,2,3] v2 = [1,2,3] s1 = [0,0,0] for i in range(len(v1)): s1[i] = v1[i] + v2[i] print(f"New Vector:{s1}") # Replace negative prices with 0 and leave the positive values unchanged in a list original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] print(f"Final List:{prices}") # Convert dictionary to JSON import json person_dict = {'name': 'Bob', 'age': 12, 'children': None } person_json = json.dumps(person_dict) print(person_json) # Writing JSON to a file import json person_dict = {"name": "Bob", "languages": ["English", "Fench"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file) # Pretty print JSON import json person_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}' person_dict = json.loads(person_string) print(json.dumps(person_dict, indent = 4, sort_keys=True)) # Check if the key exists or not in JSON import json studentJson ="""{ "id": 1, "name": "Piyush Jain", "class": null, "percentage": 35, "email": "piyushjain220@gmail.com" }""" print("Checking if percentage key exists in JSON") student = json.loads(studentJson) if "percentage" in student: print("Key exist in JSON data") print(student["name"], "marks is: ", student["percentage"]) else: print("Key doesn't exist in JSON data") # Check if there is a value for a key in JSON import json studentJson ="""{ "id": 1, "name": "Piyush Jain", "class": null, "percentage": 35, "email": "piyushjain220@gmail.com" }""" student = json.loads(studentJson) if not (student.get('email') is None): print("value is present for given JSON key") print(student.get('email')) else: print("value is not present for given JSON key") # Sort JSON keys in Python and write it into a file import json sampleJson = {"id" : 1, "name" : "value2", "age" : 29} with open("sampleJson.json", "w") as write_file: json.dump(sampleJson, write_file, indent=4, sort_keys=True) print("Done writing JSON data into a file") # Given a Python list. Turn every item of a list into its square aList = [1, 2, 3, 4, 5, 6, 7] aList = [x * x for x in aList] print(aList) # Remove empty strings from the list of strings list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"] resList = [i for i in (filter(None, list1))] print(resList) # Write a program which will achieve given a Python list, remove all occurrence of an input from the list list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, 20) print(resList) # Generate 3 random integers between 100 and 999 which is divisible by 5 import random print("Generating 3 random integer number between 100 and 999 divisible by 5") for num in range(3): print(random.randrange(100, 999, 5), end=', ') # Pick a random character from a given String import random name = 'pynative' char = random.choice(name) print("random char is ", char) # Generate random String of length 5 import random import string def randomString(stringLength): """Generate a random string of 5 charcters""" letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) print ("Random String is ", randomString(5) ) # Generate a random date between given start and end dates import random import time def getRandomDate(startDate, endDate ): print("Printing random date between", startDate, " and ", endDate) randomGenerator = random.random() dateFormat = '%m/%d/%Y' startTime = time.mktime(time.strptime(startDate, dateFormat)) endTime = time.mktime(time.strptime(endDate, dateFormat)) randomTime = startTime + randomGenerator * (endTime - startTime) randomDate = time.strftime(dateFormat, time.localtime(randomTime)) return randomDate print ("Random Date = ", getRandomDate("1/1/2016", "12/12/2018")) # Write a program which will create a new string by appending s2 in the middle of s1 given two strings, s1 and s2 def appendMiddle(s1, s2): middleIndex = int(len(s1) /2) middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:] print("After appending new string in middle", middleThree) appendMiddle("Ault", "Kelly") # Arrange string characters such that lowercase letters should come first str1 = "PyNaTive" lower = [] upper = [] for char in str1: if char.islower(): lower.append(char) else: upper.append(char) sorted_string = ''.join(lower + upper) print(sorted_string) # Given a string, return the sum and average of the digits that appear in the string, ignoring all other characters import re inputStr = "English = 78 Science = 83 Math = 68 History = 65" markList = [int(num) for num in re.findall(r'\b\d+\b', inputStr)] totalMarks = 0 for mark in markList: totalMarks+=mark percentage = totalMarks/len(markList) print("Total Marks is:", totalMarks, "Percentage is ", percentage) # Given an input string, count occurrences of all characters within a string str1 = "Apple" countDict = dict() for char in str1: count = str1.count(char) countDict[char]=count print(countDict) # Reverse a given string str1 = "PYnative" print("Original String is:", str1) str1 = str1[::-1] print("Reversed String is:", str1) # Remove special symbols/Punctuation from a given string import string str1 = "/*Jon is @developer & musician" new_str = str1.translate(str.maketrans('', '', string.punctuation)) print("New string is ", new_str) # Removal all the characters other than integers from string str1 = 'I am 25 years and 10 months old' res = "".join([item for item in str1 if item.isdigit()]) print(res) # From given string replace each punctuation with # from string import punctuation str1 = '/*Jon is @developer & musician!!' replace_char = '#' for char in punctuation: str1 = str1.replace(char, replace_char) print("The strings after replacement : ", str1) # Given a list iterate it and count the occurrence of each element and create a dictionary to show the count of each elemen sampleList = [11, 45, 8, 11, 23, 45, 23, 45, 89] countDict = dict() for item in sampleList: if(item in countDict): countDict[item] += 1 else: countDict[item] = 1 print("Printing count of each item ",countDict) # Given a two list of equal size create a set such that it shows the element from both lists in the pair firstList = [2, 3, 4, 5, 6, 7, 8] secondList = [4, 9, 16, 25, 36, 49, 64] result = zip(firstList, secondList) resultSet = set(result) print(resultSet) # Given a two sets find the intersection and remove those elements from the first set firstSet = {23, 42, 65, 57, 78, 83, 29} secondSet = {57, 83, 29, 67, 73, 43, 48} intersection = firstSet.intersection(secondSet) for item in intersection: firstSet.remove(item) print("First Set after removing common element ", firstSet) # Given a dictionary get all values from the dictionary and add it in a list but donā€™t add duplicates speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54} speedList = [] for item in speed.values(): if item not in speedList: speedList.append(item) print("unique list", speedList) # Convert decimal number to octal print('%o,' % (8)) # Convert string into a datetime object from datetime import datetime date_string = "Feb 25 2020 4:20PM" datetime_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p') print(datetime_object) # Subtract a week from a given date from datetime import datetime, timedelta given_date = datetime(2020, 2, 25) days_to_subtract = 7 res_date = given_date - timedelta(days=days_to_subtract) print(res_date) # Find the day of week of a given date? from datetime import datetime given_date = datetime(2020, 7, 26) print(given_date.strftime('%A')) # Add week (7 days) and 12 hours to a given date from datetime import datetime, timedelta given_date = datetime(2020, 3, 22, 10, 00, 00) days_to_add = 7 res_date = given_date + timedelta(days=days_to_add, hours=12) print(res_date) # Calculate number of days between two given dates from datetime import datetime date_1 = datetime(2020, 2, 25).date() date_2 = datetime(2020, 9, 17).date() delta = None if date_1 > date_2: delta = date_1 - date_2 else: delta = date_2 - date_1 print("Difference is", delta.days, "days") # Write a recursive function to calculate the sum of numbers from 0 to 10 def calculateSum(num): if num: return num + calculateSum(num-1) else: return 0 res = calculateSum(10) print(res) # Generate a Python list of all the even numbers between two given numbers num1 = 4 num2 = 30 myval = [i for i in range(num1, num2, 2)] print(myval) # Return the largest item from the given list aList = [4, 6, 8, 24, 12, 2] print(max(aList)) # Write a program to extract each digit from an integer, in the reverse order number = 7536 while (number > 0): digit = number % 10 number = number // 10 print(digit, end=" ") # Given a Python list, remove all occurrence of a given number from the list num1 = 20 list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, num1) print(resList) # Shuffle a list randomly import random list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list) # Generate a random n-dimensional array of float numbers import numpy random_float_array = numpy.random.rand(2, 2) print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n") # Generate random Universally unique IDs import uuid safeId = uuid.uuid4() print("safe unique id is ", safeId) # Choose given number of elements from the list with different probability import random num1 =5 numberList = [111, 222, 333, 444, 555] print(random.choices(numberList, weights=(10, 20, 30, 40, 50), k=num1)) # Generate weighted random numbers import random randomList = random.choices(range(10, 40, 5), cum_weights=(5, 15, 10, 25, 40, 65), k=6) print(randomList) # generating a reliable secure random number import secrets print("Random integer number generated using secrets module is ") number = secrets.randbelow(30) print(number) # Calculate memory is being used by an list in Python import sys list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith'] print("size of list = ",sys.getsizeof(list1)) # Find if all elements in a list are identical listOne = [20, 20, 20, 20] print("All element are duplicate in listOne:", listOne.count(listOne[0]) == len(listOne)) # Merge two dictionaries in a single expression currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"} formerEmployee = {2: 'Eric', 4: "Emma"} allEmployee = {**currentEmployee, **formerEmployee} print(allEmployee) # Convert two lists into a dictionary ItemId = [54, 65, 76] names = ["Hard Disk", "Laptop", "RAM"] itemDictionary = dict(zip(ItemId, names)) print(itemDictionary) # Alternate cases in String test_str = "geeksforgeeks" res = "" for idx in range(len(test_str)): if not idx % 2 : res = res + test_str[idx].upper() else: res = res + test_str[idx].lower() print(res) # write a python function to check if a given string is a palindrome def isPalindrome(s): return s == s[::-1] # write a python function to check if a given string is symmetrical def symmetry(a): n = len(a) flag = 0 if n%2: mid = n//2 +1 else: mid = n//2 start1 = 0 start2 = mid while(start1 < mid and start2 < n): if (a[start1]== a[start2]): start1 = start1 + 1 start2 = start2 + 1 else: flag = 1 break return flag # write a function to reverse words of string def rev_sentence(sentence): words = sentence.split(' ') reverse_sentence = ' '.join(reversed(words)) return reverse_sentence # write a program to check if a substring is present in a given string string = "how are you?" substring = "are" if (string.find(substring) == -1): print("NO") else: print("YES") # write a program to print length of a string str1 = "great way to learn!" print(len(str1)) # write a program to print words frequncy in a given string test_str = "It is a great meal at a great restaurant on a great day" print("Original String: " + str(test_str)) res = {key: test_str.count(key) for key in test_str.split()} print("The words frequency: " + str(res)) # write a program to print even length words in a string str1 = "I am doing fine" s = str1.split(' ') for word in s: if len(word)%2==0: print(word) # write a program to accept the strings which contains all vowels str1 = "__main__" if len(set(str1).intersection("AEIOUaeiou"))>=5: print('accepted') else: print("not accepted") # write a program to print count of number of unique matching characters in a pair of strings str1="ababccd12@" str2="bb123cca1@" matched_chars = set(str1) & set(str2) print("No. of matching characters are : " + str(len(matched_chars)) ) # write a program to remove all duplicate characters from a string str1 = "what a great day!" print("".join(set(str1))) # write a program to print least frequent character in a string str1="watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print("Minimum of all characters is: " + str(res)) # write a program to print maximum frequency character in a string str1 = "watch the match" all_freq = {} for i in str1: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = max(all_freq, key = all_freq.get) print("Maximum of all characters is: " + str(res)) # write a program to find and print all words which are less than a given length in a string str1 = "It is wonderful and sunny day for a picnic in the park" str_len = 5 res_str = [] text = str1.split(" ") for x in text: if len(x) < str_len: res_str.append(x) print("Words that are less than " + str(str_len) + ": " + str(res_str)) # write a program to split and join a string with a hyphen delimiter str1 = "part of speech" delimiter = "-" list_str = str1.split(" ") new_str = delimiter.join(list_str) print("Delimited String is: " + new_str) # write a program to check if a string is binary or not str1="01110011 a" set1 = set(str1) if set1 == {'0','1'} or set1 == {'0'} or set1 == {'1'}: print("string is binary") else: print("string is not binary") # write a function to remove i-th indexed character in a given string def remove_char(string, i): str1 = string[ : i] str2 = string[i + 1: ] return str1 + str2 # write a function to find all urls in a given string import re def find_urls(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?Ā«Ā»ā€œā€ā€˜ā€™]))" url = re.findall(regex,string) return [x[0] for x in url] # write a function to find uncommon words from two strings def UncommonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] == 1] # write a function to find common words from two strings def commonWords(str1, str2): count = {} for word in str1.split(): count[word] = count.get(word, 0) + 1 for word in str2.split(): count[word] = count.get(word, 0) + 1 return [word for word in count if count[word] > 1] # write a program to replace duplicate word occurence in String str1 = "IISC is the best. IISC has Classes in the evening for professionals. Classes help to learn new things." repl_dict = {'IISC':'It', 'Classes': 'They'} str_list = str1.split(' ') res = set() for idx, ele in enumerate(str_list): if ele in repl_dict: print(str(idx) + ' '+ele) if ele in res: str_list[idx] = repl_dict[ele] else: res.add(ele) res = ' '.join(str_list) print("Replaced String: " + str(res)) # write a program to replace multiple words with a single word str1 = 'CoffeeDay is best for coffee and having long conversations' word_list = ["best", 'long'] repl_word = 'good' res = ' '.join([repl_word if idx in word_list else idx for idx in str1.split()]) print("String after multiple replace : " + str(res)) # write a function to rotate string left by a given length def rotate_left(input,d): Lfirst = input[0 : d] Lsecond = input[d :] return (Lsecond + Lfirst) # write a function to rotate string right by a given length def rotate_right(input,d): Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] return (Rsecond + Rfirst) # write a function to replace all occurances of a substring in a string str1 = "Hello! It is a Good thing" substr1 = "Good" substr2 = "bad" replaced_str = str1.replace(substr1, substr2) print("String after replace :" + str(replaced_str)) # write a program to move numbers to the end of a string str1 = 'hi 123 how are you doing? 567 is with you. Take care of 89' res = '' dig = '' for ele in str1: if ele.isdigit(): dig += ele else: res += ele res += dig print("Strings after digits at end : " + str(res)) # write a program to count characters surrounding vowels str1 = 'week after week the numbers are increasing' res = 0 vow_list = ['a', 'e', 'i', 'o', 'u'] for idx in range(1, len(str1) - 1): if str1[idx] not in vow_list and (str1[idx - 1] in vow_list or str1[idx + 1] in vow_list): res += 1 if str1[0] not in vow_list and str1[1] in vow_list: res += 1 if str1[-1] not in vow_list and str1[-2] in vow_list: res += 1 print("Characters around vowels count : " + str(res)) # write a function that return space count def count_space(str1): count = 0 for i in range(0, len(str1)): if str1[i] == " ": count += 1 return count # write a program to break up string into individual elements str1 = "whatisthis" split_string = list(''.join(str1)) print(split_string) # write a program to extract string of N size and having K distict characters str1 = 'GoodisalwaysGoood' N = 3 K = 2 res = [] for idx in range(0, len(str1) - N + 1): if (len(set(str1[idx: idx + N])) == K): res.append(str1[idx: idx + N]) print("Extracted Strings : " + str(res)) # write a program to increment number which is at end of string import re str1 = 'count001' res = re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", str1) print("Incremented numeric String : " + str(res)) # write a program to calculate and print number of letters and digits in a string str1 = "python1234" total_digits = 0 total_letters = 0 for s in str1: if s.isnumeric(): total_digits += 1 else: total_letters += 1 print("Total letters found : ", total_letters) print("Total digits found : ", total_digits) # write a function to check if a lower case letter exists in a given string def check_lower(str1): for char in str1: k = char.islower() if k == True: return True if(k != 1): return False # write a function to check if a upper case letter exists in a given string def check_upper(str1): for char in str1: k = char.isupper() if k == True: return True if(k != 1): return False # write a program to print number of words in a string str1 = 'It is a glorious day' res = len(str1.split()) print("The number of words in string are : " + str(res)) # write a program to print number of characters in a string str1 = 'It is a glorious day' res = len(str1) print("The number of characters in string are : ", str(res)) # write a funtion that accepts two lists of equal length and converts them into a dictioinary def list_to_dict(list1, list2): return dict(zip(list1, list2)) # write a python function that accepts a list of dictionaries and sorts it by a specified key def sort_dict_list(dict_list, sort_key): dict_list.sort(key=lambda item: item.get(sort_key)) # write a program to print the longest key in a dictioinary dict_1 = {"key1": 10, "keeeey2": 2, "ky3": 30} max_key='' for key in dict_1: if len(key)>len(max_key): max_key=key print(max_key) # write a program to capitalize the first and last character of each key in a dictionary input_dict = {'key_a': 10, 'kEy': 2, 'Key_B': 13} for key in list(input_dict.keys()): new_key = key[0].upper() + key[1:-1] + key[-1].upper() input_dict[new_key] = input_dict[key] if key != new_key: del input_dict[key] # write a program that iterates over a dictionary and prints "Bingo!" if length of value is greater than the length of key. Otherwise print "no bingo" key_val_map = {"key1": "length1", "key2": "len2", "Hello": "hi", "bingo": "print bingo"} for key, val in key_val_map.items(): if len(val) > len(key): print("Bingo!") else: print("no bingo") # write a python function that accepts a dictionary that has unique values and returns its inversion def invert_dict(input_dict): my_inverted_dict = {value: key for key, value in input_dict.items()} return my_inverted_dict # write a function that inverts a dictionary with non-unique values. Keys that map to the same values should be appended to a list in the inverted dictionary def invert_dict_non_unique(my_dict): my_inverted_dict = dict() for key, value in my_dict.items(): my_inverted_dict.setdefault(value, list()).append(key) return my_inverted_dict # write a program to merge a list of dictionaries into a single dictionary using dictionary comprehension input = [{"foo": "bar", "Hello": "World"}, {"key1": "val1", "key2": "val2"}, {"sample_key": "sample_val"}] merged_dict = {key: value for d in input for key, value in d.items()} # write a function to return the mean difference in the length of keys and values of dictionary comprising of strings only. def mean_key_val_diff(input_dict): sum_diff = 0 for key, val in input_dict.items(): sum_diff += abs(len(val) - len(key)) return sum_diff/len(input_dict) # write a program that prints the number of unique keys in a list of dictionaries. list_of_dicts = [{"key1": "val1", "Country": "India"}, {"Country": "USA", "foo": "bar"}, {"foo": "bar", "foo2":"bar2"}] unique_keys = [] for d in list_of_dicts: for key in d: if key not in unique_keys: unique_keys.append(key) print(f"Number of unique keys: {len(unique_keys)}") # write a Python program to replace the value of a particular key with nth index of value if the value of the key is list. test_list = [{'tsai': [5, 3, 9, 1], 'is': 8, 'good': 10}, {'tsai': 1, 'for': 10, 'geeks': 9}, {'love': 4, 'tsai': [7, 3, 22, 1]}] N = 2 key = "tsai" for sub in test_list: if isinstance(sub[key], list): sub[key] = sub[key][N] # write a program to convert a dictionary value list to dictionary list and prints it. test_list = [{'END' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}] res =[{} for idx in range(len(test_list))] idx = 0 for sub in test_list: for key, val in sub.items(): for ele in val: res[idx][key] = ele idx += 1 idx = 0 print("Records after conversion : " + str(res)) # write a program to convert a list of dictionary to list of tuples and print it. ini_list = [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] temp_dict = {} result = [] for ini_dict in ini_list: for key in ini_dict.keys(): if key in temp_dict: temp_dict[key] += ini_dict[key] else: temp_dict[key] = ini_dict[key] for key in temp_dict.keys(): result.append(tuple([key] + temp_dict[key])) print("Resultant list of tuples: {}".format(result)) # write a program that categorizes tuple values based on second element and prints a dictionary value list where each key is a category. test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)] res = {} for i, j in test_list: res.setdefault(j, []).append(i) print("The dictionary converted from tuple list : " + str(res)) # write a Python3 program that prints a index wise product of a Dictionary of Tuple Values test_dict = {'END Program' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)} prod_list=[] for x in zip(*test_dict.values()): res = 1 for ele in x: res *= ele prod_list.append(res) res = tuple(prod_list) print("The product from each index is : " + str(res)) # write a program to Pretty Print a dictionary with dictionary values. test_dict = {'tsai' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}} print("The Pretty Print dictionary is : ") for sub in test_dict: print(f"\n{sub}") for sub_nest in test_dict[sub]: print(sub_nest, ':', test_dict[sub][sub_nest]) # write a program to sort a nested dictionary by a key and print the sorted dictionary test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17}, 'Akshat' : {'roll' : 54, 'marks' : 12}, 'Akash' : { 'roll' : 12, 'marks' : 15}} sort_key = 'marks' res = sorted(test_dict.items(), key = lambda x: x[1][sort_key]) print("The sorted dictionary by marks is : " + str(res)) # write a python function to combine three lists of equal lengths into a nested dictionary and return it def lists_to_dict(test_list1, test_list2, test_list3): res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)] return res # write a program to print keys in a dictionary whose values are greater than a given input. test_dict = {'tsai' : 4, 'random_key' : 2, 'foo' : 3, 'bar' : 'END'} K = 3 res = {key : val for key, val in test_dict.items() if type(val) != int or val > K} print("Values greater than K : ", res.keys()) # write a function that converts a integer dictionary into a list of tuples. def dict_to_tuple(input_dict): out_tuple = [(a, b) for a,b in input_dict.items()] return out_tuple # write a python function to return a flattened dictionary from a nested dictionary input def flatten_dict(dd, separator ='_', prefix =''): flattened = { prefix + separator + k if prefix else k : v for kk, vv in dd.items() for k, v in flatten_dict(vv, separator, kk).items() } if isinstance(dd, dict) else { prefix : dd } return flattened # write a program that prints dictionaries having key of the first dictionary and value of the second dictionary test_dict1 = {"tsai" : 20, "is" : 36, "best" : 100} test_dict2 = {"tsai2" : 26, "is2" : 19, "best2" : 70} keys1 = list(test_dict1.keys()) vals2 = list(test_dict2.values()) res = dict() for idx in range(len(keys1)): res[keys1[idx]] = vals2[idx] print("Mapped dictionary : " + str(res)) # write a program to combine two dictionaries using a priority dictionary and print the new combined dictionary. test_dict1 = {'Gfg' : 1, 'is' : 2, 'best' : 3} test_dict2 = {'Gfg' : 4, 'is' : 10, 'for' : 7, 'geeks' : 12} prio_dict = {1 : test_dict2, 2: test_dict1} res = prio_dict[2].copy() for key, val in prio_dict[1].items(): res[key] = val print("The dictionary after combination : " + str(res)) # write a Python program to combine two dictionary by adding values for common keys dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass # write a Python program that sorts dictionary keys to a list using their values and prints this list. test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3} res = list(sum(sorted(test_dict.items(), key = lambda x:x[1]), ())) print("List after conversion from dictionary : ", res) # write a program to concatenate values with same keys in a list of dictionaries. Print the combined dictionary. test_list = [{'tsai' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, {'tsai' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, {'tsai' : [7, 5], 'best' : [5, 7]}] res = dict() for inner_dict in test_list: for inner_list in inner_dict: if inner_list in res: res[inner_list] += (inner_dict[inner_list]) else: res[inner_list] = inner_dict[inner_list] print("The concatenated dictionary : " + str(res)) # write a python program to print the top N largest keys in an integer dictionary. test_dict = {6 : 2, 8: 9, 3: 9, 10: 8} N = 4 res = [] for key, val in sorted(test_dict.items(), key = lambda x: x[0], reverse = True)[:N]: res.append(key) print("Top N keys are: " + str(res)) # write a program to print the values of a given extraction key from a list of dictionaries. test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}] K = 'Best' res = [sub[K] for sub in test_list if K in sub][0] print("The extracted value : " + str(res)) # write a program to convert date to timestamp and print the result import time import datetime str1 = "20/01/2020" element = datetime.datetime.strptime(str1,"%d/%m/%Y") timestamp = datetime.datetime.timestamp(element) print(timestamp) # write a program to print the product of integers in a mixed list of string and numbers test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2] res = 1 for ele in test_list: try: res *= int(ele) except : pass print("Product of integers in list : " + str(res)) # write a python program to add an element to a list. Print the final list. lst = ["Jon", "Kelly", "Jessa"] lst.append("Scott") print(lst) # write a python function to append all elements of one list to another def extend_list(list1, list2): list1 = [1, 2] list2 = [3, 4] return list1.extend(list2) # write a python function to add elements of two lists def add_two_lists(list1, list2): list1 = [1, 2, 3] list2 = [4, 5, 6] sum_list = [] for (item1, item2) in zip(list1, list2): sum_list.append(item1+item2) return sum_list # Write a python program to print the last element of a list list1 = ['p','r','o','b','e'] print(list1[-1]) # Write a python program to print positive Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num >= 0: print(num, end = " ") # Write a python function to multiply all values in a list def multiplyList(myList) : result = 1 for x in myList: result = result * x return result # Write a python program to print the smallest number in a list list1 = [10, 20, 1, 45, 99] print("Smallest element is:", min(list1)) # Write a python program to remove even numbers from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] for ele in list1: if ele % 2 == 0: list1.remove(ele) print("New list after removing all even numbers: ", list1) # Write a python program to print a list after removing elements from index 1 to 4 list1 = [11, 5, 17, 18, 23, 50] del list1[1:5] print(*list1) # Write a python program to remove 11 and 18 from a list. Print the final list. list1 = [11, 5, 17, 18, 23, 50] unwanted_num = {11, 18} list1 = [ele for ele in list1 if ele not in unwanted_num] print("New list after removing unwanted numbers: ", list1) # Write a python program to Remove multiple empty spaces from List of strings. Print the original and final lists. test_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] print("The original list is : " + str(test_list)) res = [ele for ele in test_list if ele.strip()] print("List after filtering non-empty strings : " + str(res)) # Write a python function to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Write a python program to print if a string "hello" is present in the list l = [1, 2.0, 'hello','have', 'a', 'good', 'day'] s = 'hello' if s in l: print(f'{s} is present in the list') else: print(f'{s} is not present in the list') # Write a python program to print the distance between first and last occurrence of even element. test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11] indices_list = [idx for idx in range( len(test_list)) if test_list[idx] % 2 == 0] res = indices_list[-1] - indices_list[0] print("Even elements distance : " + str(res)) # Write a python fuction to create an empty list def emptylist(): return list() # Write a python program to print a list with all elements as 5 and of length 10 list1 = [5] * 10 print(list1) # Write a python program to reverse a list and print it. def Reverse(lst): return [ele for ele in reversed(lst)] lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst)) # Write a python program to print odd numbers in a List list1 = [10, 21, 4, 45, 66, 93, 11] odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) # Write a python program to print negative Numbers in a List list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num < 0: print(num, end = " ") # Write a python program print the the number of occurrences of 8 in a list def countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print('{} has occurred {} times'.format(x, countX(lst, x))) # Write a python program to swap first and last element of a list . Print the final list def swapList(newList): size = len(newList) # Swapping temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList newList = [12, 35, 9, 56, 24] print(swapList(newList)) # Write a python program to convert each list element to key-value pair. Print the final dictionary test_list = [2323, 82, 129388, 234, 95] print("The original list is : " + str(test_list)) res = dict() for ele in test_list: mid_idx = len(str(ele)) // 2 key = int(str(ele)[:mid_idx]) val = int(str(ele)[mid_idx:]) res[key] = val print("Constructed Dictionary : " + str(res)) # Write a python program for print all elements with digit 7. test_list = [56, 72, 875, 9, 173] K = 7 res = [ele for ele in test_list if str(K) in str(ele)] print("Elements with digit K : " + str(res)) # Write a python program for printing number of unique elements in a list input_list = [1, 2, 2, 5, 8, 4, 4, 8] l1 = [] count = 0 for item in input_list: if item not in l1: count += 1 l1.append(item) print("No of unique items are:", count) # Write a python program to find the sum and average of the list. Print the sum and average L = [4, 5, 1, 2, 9, 7, 10, 8] count = 0 for i in L: count += i avg = count/len(L) print("sum = ", count) print("average = ", avg) # Write a python program to Remove Tuples of Length 1 from a list of tuples. Print the final list. test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] K = 1 res = [ele for ele in test_list if len(ele) != K] print("Filtered list : " + str(res)) # Write a python program to print a list of tuples from given list having number and its cube in each tuple list1 = [1, 2, 5, 6] res = [(val, pow(val, 3)) for val in list1] print(res) # Write a python program to print the combination of tuples in list of tuples test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] res = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] print("The list tuple combination : " + str(res)) # Write a python program to swap tuple elements in list of tuples. Print the output. test_list = [(3, 4), (6, 5), (7, 8)] res = [(sub[1], sub[0]) for sub in test_list] print("The swapped tuple list is : " + str(res)) # Write a python function to sort a list of tuples by the second Item def Sort_Tuple(tup): lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Write a python program to print all pair combinations of 2 tuples. test_tuple1 = (4, 5) test_tuple2 = (7, 8) res = [(a, b) for a in test_tuple1 for b in test_tuple2] res = res + [(a, b) for a in test_tuple2 for b in test_tuple1] print("The filtered tuple : " + str(res)) # Write a python program to print positive Tuples in List. test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] print("The original list is : " + str(test_list)) res = [sub for sub in test_list if all(ele >= 0 for ele in sub)] print("Positive elements Tuples : " + str(res)) # Write a python program to join Tuples from a list of tupels if they have similar initial element. Print out the output test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)] print("The original list is : " + str(test_list)) res = [] for sub in test_list: if res and res[-1][0] == sub[0]: res[-1].extend(sub[1:]) else: res.append([ele for ele in sub]) res = list(map(tuple, res)) print("The extracted elements : " + str(res)) # Write a python program to print the uncommon elements in List test_list1 = [ [1, 2], [3, 4], [5, 6] ] test_list2 = [ [3, 4], [5, 7], [1, 2] ] res_list = [] for i in test_list1: if i not in test_list2: res_list.append(i) for i in test_list2: if i not in test_list1: res_list.append(i) print ("The uncommon of two lists is : " + str(res_list)) # write a Function to convert the time from 12 hour format to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] # write a python program to multiply three numbers num1 = 1.5 num2 = 6.3 num3 = -2.3 product = num1 * num2 * num3 print(f'Product: {product}') # write a python function that when given two numbers, would divide the first number by second number and return the quotient and remainder def divide_first_number_by_second(num1, num2): return (num1 // num2), (num1 % num2) # write a python function to return the largest and smallest numbers in the given list and return None if the list is empty def largest_and_smallest(list_of_nums): if list_of_nums: return max(list_of_nums), min(list_of_nums) else: return # write a python function that would read the given input file path and print its contents def read_and_print_file(filepath): with open(filepath, "r") as infile: print( infile.read() ) # write a python program that would print the first n positive integers using a for loop n = 62 for num in range(n): print(num) # write a python function that returns the input list sorted in ascending order def sort_ascending(list_to_be_sorted): return sorted(list_to_be_sorted) # write a python function that returns the input list sorted in descending order def sort_descending(list_to_be_sorted): return sorted(list_to_be_sorted, reverse=True) # write a python function that would return the sum of first n natural numbers, where n is the input def sum_first_n(n): return ( n * (n+1) ) // 2 # write a recursive python function that would return the sum of first n natural numbers, where n is the input def sum_first_n_recursive(n): if n == 0: return 0 return sum_first_n_recursive(n-1) + n # write a python function that would filter a list of dictionaries where a specified key equals given value, list_of_dictionaries, key and value are inputs to this function. def filter_with_key_value(list_of_dicts, key, value): return list( filter( lambda x: x.get(key) == value, list_of_dicts ) ) # write a recursive python function that takes either a list or tuple as input and reverses the order of its elements def reverse(seq): SeqType = type(seq) emptySeq = SeqType() if seq == emptySeq: return emptySeq restrev = reverse(seq[1:]) first = seq[0:1] result = restrev + first return result # write a python function that returns the square of a given input number def square(x): return x**2 # write a python function that performs selection sort on the given list or tuple or string and returns the new sorted sequence def selection_sort(list_to_be_sorted): sorted_list = list_to_be_sorted[:] for i in range(len(sorted_list)): new_min = sorted_list[i] new_min_old_place = i for j in range(i+1, len(sorted_list)): if new_min > sorted_list[j]: new_min = sorted_list[j] new_min_old_place = j old_val = sorted_list[i] sorted_list[i] = new_min sorted_list[new_min_old_place] = old_val return sorted_list # write a python program that asks for user input and prints the given input a = input("User Input") print(a) # write a python function shifts and scales all numbers in the given list by the given mean and standard deviation def shift_and_scale(list_of_nums, mean, std): return [ (x-mean) / std for x in list_of_nums ] # write a python function that takes in a list of sequences and zips each corresponding element from the list into a tuple and returns the list of such tuples def zip_(list_of_seq): return list(zip(*list_of_seq)) # write a python program that asks user to guess a number between 1 and 5 and guess it within 3 guesses print("Please guess a number between 1 and 5 and I will guess within 3 chances!") guess1 = input("Is it <= 3? enter y/n \n") if guess1 == "y": guess2 = input("Is it <= 2? enter y/n \n") if guess2 == "y": guess3 = input("Is it 1? enter y/n \n") if guess3 == "y": print("Yay! found the number, its 1") else: print("Yay! found the number, its 2") else: print("Yay! found the number, its 3") else: guess2 = input("Is it 4? enter y/n \n") if guess2 == "y": print("Yay! found the number, its 4") else: print("Yay! found the number, its 5") # write python program that would merge two dictionaries by adding the second one into the first a = {"a": 1, "b": 3} b = {"c": 1, "d": 3} a.update(b) # write a python function that would reverse the given string def reverse_string(str_to_be_reversed): return str_to_be_reversed[::-1] # write a python program that would print "Hello World" print("Hello World") # write a python program that would swap variable values a = 10 b = 15 a, b = b, a # write a python program that iterates over a dictionary and prints its keys and values a = {"a":1, "b":2, "c":3, "d":4} for k, v in a.items(): print(k, v) # write a python function that would print the ASCII value of a given character def print_ascii(char): print(ord(char)) # write a python function that takes in two numbers and returns their HCF def hcf(num1, num2): smaller = num1 if num1 < num2 else num2 for i in range(1, smaller+1): if (num1 % i == 0) and (num2 % i == 0): hcf = i return hcf # write a python function that takes in two numbers and returns their LCM def lcm(num1, num2): bigger = num1 if num1 > num2 else num2 while True: if (bigger % num1 == 0) and (bigger % num2 == 0): break bigger += 1 return bigger # write a recursive python function to calculate sum of natural numbers upto n, where n is an argument def recursive_sum(n): if n <= 1: return n else: return n + recursive_sum(n-1) # write a python function that deletes the last element of a list and returns the list and the deleted element def delete_last_element(list_to_be_processed): deleted_element = list_to_be_processed.pop() return list_to_be_processed, deleted_element # write a python function that takes in a list and returns a list containing the squares of the elements of the input list def square_list_elements(list_to_be_squared): return list( map(lambda x: x**2, list_to_be_squared) ) # write a python function that finds square roots of a given number, if the square root is an integer, else returns the message "Error - the square root is not an integer" def find_integer_square_roots(num): found = False for k in range(1, (num//2)+1): if ((k**2)==num): found = True break if not found: return "Error - the square root is not an integer" return -k, k # write a python program that prints out natural numbers less than or equal to the given number using a while loop input_num = 27 while input_num: print(input_num) input_num -= 1 # write a python function that takes two numbers. The function divides the first number by the second and returns the answer. The function returns None, if the second number is 0 def divide(num1, num2): if num2 == 0: return else: return num1 / num2 # write a python program uses else with for loop seq = "abcde" for k in seq: if k == "f": break else: print("f Not Found!") # write a recursive python function that performs merge sort on the given list or tuple or string and returns the new sorted sequence def sort_and_merge(l1, l2): new_list = [] i = 0 j = 0 l1_len = len(l1) l2_len = len(l2) while (i <= l1_len-1) and (j <= l2_len-1): if l1[i] < l2[j]: new_list.append(l1[i]) i +=1 else: new_list.append(l2[j]) j +=1 if i <= (l1_len-1): new_list += l1[i:] if j <= (l2_len-1): new_list += l2[j:] return new_list def recursive_merge_sort(list_to_be_sorted): final_list = [] first = 0 last = len(list_to_be_sorted) if last <= 1: final_list.extend( list_to_be_sorted ) else: mid = last // 2 l1 = recursive_merge_sort( list_to_be_sorted[:mid] ) l2 = recursive_merge_sort( list_to_be_sorted[mid:] ) final_list.extend( sort_and_merge( l1, l2 ) ) return final_list # Write a function to return the mean of numbers in a list def cal_mean(num_list:list)->float: if num_list: return sum(num_list)/len(num_list) else: return None # Write a function to return the median of numbers in a list def cal_median(num_list:list)->float: if num_list: if len(num_list)%2 != 0: return sorted(num_list)[int(len(num_list)/2) - 1] else: return (sorted(num_list)[int(len(num_list)/2) - 1] + sorted(num_list)[int(len(num_list)/2)])/2 else: return None # Write a function to return the area of triangle by heros formula def cal_triangle_area(a:float,b:float,c:float)->float: if a or b or c: s = (a+b+c)/2 if s>a and s>b and s>c: area = (s*(s-a)*(s-b)*(s-c))**(1/2) return round(area,2) else: return None return None # Write a function to return the area of a equilateral triangle def cal_eq_triangle_area(a:float)->float: if a: return (3**(1/2))*(a**2)/4 else: return None # Write a function to return the area of a right angle triangle def cal_rt_triangle_area(base:float,height:float)->float: if base and height: return (base*height)/2 else: return None # Write a function to return the cartisian distance of a point from origin def cal_dist_from_orign(x:float,y:float)->float: return (x**2+y**2)**(1/2) # Write a function to return the cartisian distance between two points def cal_cart_distance(x1:float,y1:float,x2:float,y2:float)->float: return ((x1-x2)**2+(y1-y2)**2)**(1/2) # Write a function to return the type roots of a quadratic equation ax**2 + bx + c = 0 def root_type(a:float,b:float,c:float): if b**2-4*a*c >= 0: return 'real' else: return 'imaginary' # Write a function to return the sum of the roots of a quadratic equation ax**2 + bx + c = 0 def sum_of_roots(a:float,c:float): if a: return c/a else: return None # Write a function to return the product of the roots of a quadratic equation ax**2 + bx + c = 0 def prod_of_roots(a:float,b:float): if a: return -b/a else: return None # Write a function to return the real of the roots of a quadratic equation else return None ax**2 + bx + c = 0 def roots_of_qad_eq(a:float,b:float,c:float): d = b**2-4*a*c if d >= 0: return (-b+(d)**(1/2))/2*a,(-b-(d)**(1/2))/2*a else: return None # Write a function to return the profit or loss based on cost price and selling price def find_profit_or_loss(cp,sp): if cp > sp: return 'loss', cp-sp elif cp < sp: return 'profit', sp-cp else: return 'no profit or loss', 0 # Write a function to return the area of a rectangle def cal_area_rect(length, breadth): return length*breadth # Write a function to return the area of a square def cal_area_square(side): return side**2 # Write a function to return the area of a rhombus with diagonals q1 and q2 def cal_area_rhombus(q1,q2): return (q1*q2)/2 # Write a function to return the area of a trapezium with base a base b and height h between parallel sides def cal_area_trapezium(a,b,h): return h*(a+b)/2 # Write a function to return the area of a circle of raidus r def cal_area_circle(r): pi = 3.14 return pi*r**2 # Write a function to return the circumference of a circle def cal_circumference(r): pi = 3.14 return 2*pi*r # Write a function to return the perimeter of a rectangle def cal_perimeter_rect(length, bredth): return 2*(length+bredth) # Write a function to return the perimeter of a triangle def cal_perimeter_triangle(s1,s2,s3): return s1+s2+s3 # Write a function to return the perimeter of a square def cal_perimeter_square(side): return 4*side # Write a function to return the perimeter of an equilateral triangle def cal_perimeter_eq_triangle(a): return 3*a # Write a function to return the perimeter of a isoscales triangle def cal_perimeter_iso_triangle(s1,s2): return 2*s1+s2 # Write a function to return the area of an ellipse def cal_area_ellipse(minor, major): pi = 3.14 return pi*(minor*major) # Write a function to return the lateral surface area of a cylinder def cal_cylinder_lat_surf_area(height,radius): pi=3.14 return 2*pi*radius*height # Write a function to return the curved surface area of a cone def cal_cone_curved_surf_area(slant_height,radius): pi=3.14 return pi*radius*slant_height # Write a function to return the total surface area of a cube of side a def cal_surface_area_cube(a): return 6*(a**2) # Write a function to return the total surface area of a cuboid of length l, bredth b and height h def cal_surface_area_cuboid(l,b,h): return 2*(l*b+b*h+h*l) # Write a function to return the surface area of a sphere def cal_area_sphere(radius): pi = 3.14 return 4*pi*(radius**2) # Write a function to return the surface area of a hemi-sphere def cal_area_hemisphere(radius): pi = 3.14 return 2*pi*(radius**2) # Write a function to return the total surface area of a cylinder def cal_cylinder_surf_area(height,radius): pi=3.14 return 2*pi*radius**2*+2*pi*radius*height # Write a function to return the lateral surface area of a cone def cal_cone_lateral_surf_area(height,radius): pi=3.14 return pi*radius*(((height**2)+(radius**2))**(1/2)) # Write a function to return the volume of a cylinder def cal_cylinder_volume(height, radius): pi=3.14 return pi*(radius**2)*height # Write a function to return the volume of a cone def cal_cone_volume(height,radius): pi=3.14 return pi*(radius**2)*height/3 # Write a function to return the volume of a hemi sphere def cal_hemisphere_volume(radius:float)->float: pi=3.14 return (2/3)*pi*(radius**3) # Write a function to return the volume of a sphere def cal_sphere_volume(radius:float)->float: pi=3.14 return (4/3)*pi*(radius**3) # Write a function to return the volume of a cuboid def cal_cuboid_volume(length:float, breadth:float, height:float)->float: return length*breadth*height # Write a function to return the volume of a cube def cal_cube_volume(side:float)->float: return side**3 # Write a function to return the speed of moving object based of distance travelled in given time def cal_speed(distance:float,time:float)->float: return distance/time # Write a function to return the distance covered by a moving object based on speend and given time def cal_distance(time:float,speed:float)->float: return time*speed # Write a function to return the time taken by a given of moving object based of distance travelled in given time def cal_time(distance:float,speed:float)->float: return distance/speed # Write a function to return the torque when a force f is applied at angle thea and distance for axis of rotation to place force applied is r def cal_torque(force:float,theta:float,r:float)->float: import math return force*r*math.sin(theta) # Write a function to return the angualr veolcity based on augualr distance travelled in radian unit and time taken def cal_angular_velocity(angular_dist:float,time:float)->float: return angular_dist/time # Write a function to calculate the focal length of a lense buy the distance of object and distance of image from lense def cal_focal_length_of_lense(u:float,v:float)->float: return (u*v)/(u+v) # Write a function to calculate the gravitational force between two objects of mass m1 and m2 and distance of r between them def cal_gforce(mass1:float,mass2:float, distance:float)->float: g = 6.674*(10)**(-11) return (g*mass1*mass2)/(distance**2) # Write a function to calculate the current in the curcit where the resistance is R and voltage is V def cal_current(resistance:float, voltage:float)->float: return voltage/resistance # Write a function to calculate the total capacitance of capacitors in parallel in a given list def cal_total_cap_in_parallel(cap_list:list)->float: return sum(cap_list) # Write a function to calculate the total resistance of resistances in parallel in a given list def cal_total_res_in_parallel(res_list:list)->float: return sum([1/r for r in res_list]) # Write a function to calculate the total resistance of resistances in series in a given list def cal_total_res_in_series(res_list:list)->float: return sum(res_list) # Write a function to calculate the moment of inertia of a ring of mass M and radius R def cal_mi_ring(mass:float,radius:float)->float: return mass*(radius**2) # Write a function to calculate the moment of inertia of a sphere of mass M and radius R def cal_mi_sphere(mass:float,radius:float)->float: return (7/5)*mass*(radius**2) # Write a function to calculate the pressure P of ideal gas based on ideal gas equation - Volume V, and Temperatue T are given def find_pressure_of_ideal_gas(volume:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/volume # Write a function to calculate the volume V of ideal gas based on ideal gas equation Pressure P and Tempreature T given def find_volume_of_ideal_gas(pressure:float, temp:float,n:float)->float: r = 8.3145 # gas constant R return (n*r*temp)/pressure # Write a function to calculate the Temprature T of ideal gas based on ideal gas equation Pressure P and Volume V given def find_temp_of_ideal_gas(pressure:float, volume:float,n:float)->float: r = 8.3145 # gas constant R return (pressure*volume)/n*r # Write a function to calculate the velocity of an object with initial velocity u, time t and acceleration a def cal_final_velocity(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity + accelration*time # Write a function to calculate the displacement of an object with initial velocity u, time t and acceleration a def cal_displacement(initial_velocity:float,accelration:float,time:float)->float: return initial_velocity*time + .5*accelration*(time)**2 # Write a function to calculate amount of radioactive element left based on initial amount and half life def cal_half_life(initail_quatity:float, time_elapsed:float, half_life:float)->float: return initail_quatity*((1/2)**(time_elapsed/half_life)) # Write a function to calculate the new selling price based on discount percentage def cal_sp_after_discount(sp:float,discount:float)->float: return sp*(1 - discount/100) # Write a function to calculate the simple interest for principal p, rate r and time in years y def get_si(p:float, r:float, t:float)->float: return (p*r*t)/100 # Write a function to calculate the compound interest for principal p, rate r and time in years y def get_ci(p:float, r:float, t:float, n:float)->float: return round(p*((1+(r/(n*100)))**(n*t)) - p,2) # Write a function to calculate the energy released by converting mass m in kg to energy def cal_energy_by_mass(mass:float)->float: c = 300000 return mass * (c**2) # Write a function to calculate the kinetic energy of an object of mass m and velocity v def cal_ke(mass:float,velocity:float)->float: return (mass*(velocity)**2)/2 # Write a function to calculate the potential energy of an object of mass m at height h def cal_pe(mass:float,height:float)->float: g = 9.8 return (mass*g*height) # Write a function to calculate the electrostatic force between two charged particles with charge q1 and q2 at a distance d apart def cal_electrostatic_force(q1,q2,d): k = 9*(10**9) return (k*q1*q2)/(d**2) # Write a function to calculate the density given mass and volume def cal_density(mass,volume): return (mass/volume) # Write a function to convert the temprature celsius 'c' to fahrenheit 'f' or fahrenheit to celsius def temp_converter(temp,temp_given_in = 'f'): # Return the converted temprature if temp_given_in.lower() == 'f': # Convert to C return (temp - 32) * (5/9) else: # Convert to F return (temp * 9/5) + 32 # Write a function to merge dictionaries def merge1(): test_list1 = [{"a": 1, "b": 4}, {"c": 10, "d": 15}, {"f": "gfg"}] test_list2 = [{"e": 6}, {"f": 3, "fg": 10, "h": 1}, {"i": 10}] print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) for idx in range(0, len(test_list1)): id_keys = list(test_list1[idx].keys()) for key in test_list2[idx]: if key not in id_keys: test_list1[idx][key] = test_list2[idx][key] print("The Merged Dictionary list : " + str(test_list1)) # Write a function for vertical concatenating of a matrix def vertical_concatenation(): test_list = [["this","is"], ["program", "for"], ["vertical","concatenation"]] print("The original list : " + str(test_list)) res = [] N = 0 while N != len(test_list): temp = '' for idx in test_list: try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] print("List after column Concatenation : " + str(res)) vertical_concatenation() # Write a function to Get Kth Column of Matrix def kth_column(test_list=[[4, 5, 6], [8, 1, 10], [7, 12, 5]],k=2): print("The original list is : " + str(test_list)) K =k res = list(zip(*test_list))[K] print("The Kth column of matrix is : " + str(res)) # Write a function to print all possible subarrays using recursion def printSubArrays(arr, start, end): if end == len(arr): return elif start > end: return printSubArrays(arr, 0, end + 1) else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) arr = [1, 2, 3] printSubArrays(arr, 0, 0) # Write a function to find sum of nested list using Recursion total = 0 def sum_nestedlist(l): global total for j in range(len(l)): if type(l[j]) == list: sum_nestedlist(l[j]) else: total += l[j] sum_nestedlist([[1, 2, 3], [4, [5, 6]], 7]) print(total) #Write a function to find power of number using recursion def power(N, P): if (P == 0 or P == 1): return N else: return (N * power(N, P - 1)) print(power(5, 2)) # Write a function to Filter String with substring at specific position def f_substring(): test_list = ['program ', 'to', 'filter', 'for', 'substring'] print("The original list is : " + str(test_list)) sub_str = 'geeks' i, j = 0, 5 res = list(filter(lambda ele: ele[i: j] == sub_str, test_list)) print("Filtered list : " + str(res)) # Write a function to remove punctuation from the string def r_punc(): test_str = "end, is best : for ! Nlp ;" print("The original string is : " + test_str) punc = r'!()-[]{};:\, <>./?@#$%^&*_~' for ele in test_str: if ele in punc: test_str = test_str.replace(ele, "") print("The string after punctuation filter : " + test_str) # Write a function to implement Gnome Sort def gnomeSort(arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index = index - 1 return arr arr = [34, 2, 10, -9] n = len(arr) arr = gnomeSort(arr, n) print("Sorted seqquence after applying Gnome Sort :") for i in arr: print(i) # Write a function to implement Pigeonhole Sort */ def pigeonhole_sort(a): my_min = min(a) my_max = max(a) size = my_max - my_min + 1 holes = [0] * size for x in a: assert type(x) is int, "integers only please" holes[x - my_min] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3, 2, 7, 4, 6, 8] print("Sorted order is : ", end=" ") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end=" ") #Write a function to implement stooge sort def stoogesort(arr, l, h): if l >= h: return if arr[l] > arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t if h - l + 1 > 2: t = (int)((h - l + 1) / 3) stoogesort(arr, l, (h - t)) stoogesort(arr, l + t, (h)) stoogesort(arr, l, (h - t)) arr = [2, 4, 5, 3, 1] n = len(arr) stoogesort(arr, 0, n - 1) for i in range(0, n): print(arr[i], end = '') #Write a function to find the difference between two times def difference(h1, m1, h2, m2): t1 = h1 * 60 + m1 t2 = h2 * 60 + m2 if (t1 == t2): print("Both are same times") return else: diff = t2 - t1 h = (int(diff / 60)) % 24 m = diff % 60 print(h, ":", m) difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) #Write a function to convert time from 12 hour to 24 hour format def convert24(str1): if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] elif str1[-2:] == "AM": return str1[:-2] elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: return str(int(str1[:2]) + 12) + str1[2:8] print(convert24("08:05:45 PM")) #Write a function to find time for a given angle. def calcAngle(hh, mm): hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm angle = abs(hour_angle - minute_angle) angle = min(360 - angle, angle) return angle #Write a function to print all time when angle between hour hand and minute def printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm) == theta): print(hh, ":", mm, sep="") return print("Input angle not valid.") return theta = 90.0 printTime(theta) # Team Members: Santu Hazra, Manu Chauhan, Ammar Adil and Prakash Nishtala import os import nltk import string from collections import Counter from itertools import permutations, combinations, combinations_with_replacement letters = string.ascii_lowercase # write a python function to print pyramid pattern def pyramid_pattern(symbol='*', count=4): for i in range(1, count + 1): print(' ' * (count - i) + symbol * i, end='') print(symbol * (i - 1) + ' ' * (count - i)) # write a python function to count the occurrence of a given word in a given file def check_word_count(word, file): if not os.path.isfile(file): raise FileNotFoundError if not isinstance(word, str): raise TypeError with open(file, 'r') as f: lines = f.readlines() words = [l.strip().split(' ') for l in lines] words = [word for sublist in words for word in sublist] c = Counter(words) return c.get(word, 0) # write a python function to make permutations from a list with given length def get_permutations(data_list, l=2): return list(permutations(data_list, r=l)) # write a python program to get all possible permutations of size of the string in lexicographic sorted order. def get_ordered_permutations(word, k): [print(''.join(x)) for x in sorted(list(permutations(word, int(k))))] # write a python program to get all possible combinations, up to size of the string in lexicographic sorted order. def get_ordered_combinations(string, k): [print(''.join(x)) for i in range(1, int(k) + 1) for x in combinations(sorted(string), i)] # write a python function to get all possible size replacement combinations of the string in lexicographic sorted order. def get_ordered_combinations_with_replacement(string, k): [print(''.join(x)) for x in combinations_with_replacement(sorted(string), int(k))] # write a python function for Caesar Cipher, with given shift value and return the modified text def caesar_cipher(text, shift=1): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[shift:] + alphabet[:shift] table = str.maketrans(alphabet, shifted_alphabet) return text.translate(table) # write a python function for a string to swap the case of all letters. def swap_case(s): return ''.join(x for x in (i.lower() if i.isupper() else i.upper() for i in s)) # write a python function to get symmetric difference between two sets from user. def symmetric_diff_sets(): M, m = input(), set(list(map(int, input().split()))) N, n = input(), set(list(map(int, input().split()))) s = sorted(list(m.difference(n)) + list(n.difference(m))) for i in s: print(i) # write a python function to check if given set is subset or not def check_subset(): for _ in range(int(input())): x, a, z, b = input(), set(input().split()), input(), set(input().split()) print(a.issubset(b)) # write a python program for basic HTML parser from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for attr in attrs: print("->", attr[0], ">", attr[1]) parser = MyHTMLParser() for i in range(int(input())): parser.feed(input()) # write a python function for Named Entity Recognizer using NLTK def ner_checker(texts): all_set = set() def nltk_ner_check(texts): for i, text in texts: for entity in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(text))): if isinstance(entity, nltk.tree.Tree): etext = " ".join([word for word, tag in entity.leaves()]) # label = entity.label() all_set.add(etext) nltk_ner_check(texts=texts) return all_set #write a function to compress a given string. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X, c) in the string. def compress(text): from itertools import groupby for k, g in groupby(text): print("({}, {})".format(len(list(g)), k), end=" ") # write a python function to count 'a's in the repetition of a given string 'n' times. def repeated_string(s, n): return s.count('a') * (n // len(s)) + s[:n % len(s)].count('a') # write a python function to find all the substrings of given string that contains 2 or more vowels. Also, these substrings must lie in between 2 consonants and should contain vowels only. def find_substr(): import re v = "aeiou" c = "qwrtypsdfghjklzxcvbnm" m = re.findall(r"(?<=[%s])([%s]{2,})[%s]" % (c, v, c), input(), flags=re.I) print('\n'.join(m or ['-1'])) # write a python function that given five positive integers and find the minimum and maximum values that can be calculated by summing exactly four of the five integers. def min_max(): nums = [int(x) for x in input().strip().split(' ')] print(sum(nums) - max(nums), sum(nums) - min(nums)) # write a python function to find the number of (i, j) pairs where i 1: data.pop(item) count -= 1 return data # write a python function to get the most common word in text def most_common(text): c = Counter(text) return c.most_common(1) # write a python function to do bitwise multiplication on a given bin number by given shifts def bit_mul(n, shift): return n << shift # write a python function for bitwise division with given number of shifts def bit_div(n, shift): return n >> shift # write a python program to implement Queue from collections import deque class Queue(): ''' Thread-safe, memory-efficient, maximally-sized queue supporting queueing and dequeueing in worst-case O(1) time. ''' def __init__(self, max_size = 10): ''' Initialize this queue to the empty queue. Parameters ---------- max_size : int Maximum number of items contained in this queue. Defaults to 10. ''' self._queue = deque(maxlen=max_size) def enqueue(self, item): ''' Queues the passed item (i.e., pushes this item onto the tail of this queue). If this queue is already full, the item at the head of this queue is silently removed from this queue *before* the passed item is queued. ''' self._queue.append(item) def dequeue(self): ''' Dequeues (i.e., removes) the item at the head of this queue *and* returns this item. Raises ---------- IndexError If this queue is empty. ''' return self._queue.pop() # write a python function to get dot product between two lists of numbers def dot_product(a, b): return sum(e[0] * e[1] for e in zip(a, b)) # write a python function to strip punctuations from a given string def strip_punctuations(s): return s.translate(str.maketrans('', '', string.punctuation)) # write a python function that returns biggest character in a string from functools import reduce def biggest_char(string): if not isinstance(string, str): raise TypeError return reduce(lambda x, y: x if ord(x) > ord(y) else y, string) # write a python function to Count the Number of Digits in a Number def count_digits(): n = int(input("Enter number:")) count = 0 while n > 0: count = count + 1 n = n // 10 return count # write a python function to count number of vowels in a string def count_vowels(text): v = set('aeiou') for i in v: print(f'\n {i} occurs {text.count(i)} times') # write a python function to check external IP address def check_ip(): import re import urllib.request as ur url = "http://checkip.dyndns.org" with ur.urlopen(url) as u: s = str(u.read()) ip = re.findall(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", s) print("IP Address: ", ip[0]) return ip[0] # write a python function for some weird hypnosis text. def weird(): import random def getlength(script): return sum((i['length'] for i in script)) def truncate(target_length, script): if getlength(script) > target_length: script = sorted(script, key=lambda k: (k['priority'], -k['length']))[:-1] return truncate(target_length, script) return sorted(script, key=lambda k: k['index']) def as_text(script): return "\n".join([i['text'] for i in script]) priorities_and_sentences = [ (1, "...now... sitting comfortably in the chair"), (2, "...with your feet still flat on the ground"), (3, "...back straight and head up right"), (2, "...make these adjustments now if you need to"), (3, "... pause.............................."), (1, "...your eyes ...still ...comfortably closed"), (2, "...nice and relaxed...comfortable and relaxed..."), (3, "... pause......................................."), (1, "...now...I want you to notice...how heavy your head is starting to feel..."), (1, "how heavy your head feels..."), (3, "... pause......................................."), (2, "really noticing the weight... of your head..."), (3, "and how much more ...comfortable...it will feel when you let your neck relaxes ...and your head begins to fall forward ...into a much more comfortable"), ] scriptlist = [{'priority': j[0], 'text': j[1], 'length': len(j[1]), 'index': i} for i, j in enumerate(priorities_and_sentences)] print(as_text(truncate(500, scriptlist))) print(as_text(truncate(300, scriptlist))) print(as_text(truncate(200, scriptlist))) # write a python function for dice roll asking user for input to continue and randomly give an output. def dice(): import random min = 1 max = 6 roll_again = 'y' while roll_again == "yes" or roll_again == "y": print("Rolling the dice...") print(random.randint(min, max)) roll_again = input("Roll the dices again?") from cryptography.fernet import Fernet # write a python program to Encrypt and Decrypt features within 'Secure' class with key generation, using cryptography module class Secure: def __init__(self): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("secret.key", "wb") as key_file: key_file.write(key) @staticmethod def load_key(): """ Load the previously generated key """ return open("secret.key", "rb").read() def encrypt_message(self, message): """ Encrypts a message """ key = self.load_key() encoded_message = message.encode() f = Fernet(key) encrypted_message = f.encrypt(encoded_message) print("\nMessage has been encrypted: ", encrypted_message) return encrypted_message def decrypt_message(self, encrypted_message): """ Decrypts an encrypted message """ key = self.load_key() f = Fernet(key) decrypted_message = f.decrypt(encrypted_message) print("\nDecrypted message:", decrypted_message.decode()) s = Secure() encrypted = s.encrypt_message("My deepest secret!") s.decrypt_message(encrypted) # write a python function to generate SHA256 for given text def get_sha256(text): import hashlib return hashlib.sha256(text).hexdigest() # write a python function to check if SHA256 hashed value is valid for given data or not def check_sha256_hash(hashed, data): import hashlib return True if hashed == hashlib.sha256(data.encode()).hexdigest() else False # write a python function to get HTML code for a given URL def get_html(url="http://www.python.org"): import urllib.request fp = urllib.request.urlopen(url) mybytes = fp.read() mystr = mybytes.decode("utf8") fp.close() print(mystr) # write a python function to get Bitcoin prices after every given 'interval' seconds def get_btc_price(interval=5): import requests import json from time import sleep def getBitcoinPrice(): URL = "https://www.bitstamp.net/api/ticker/" try: r = requests.get(URL) priceFloat = float(json.loads(r.text)["last"]) return priceFloat except requests.ConnectionError: print("Error querying Bitstamp API") while True: print("Bitstamp last price: US $ " + str(getBitcoinPrice()) + "/BTC") sleep(interval) # write a python function to get stock prices for a company from 2015 to 2020-12 def get_stock_prices(tickerSymbol='TSLA'): import yfinance as yf # get data on this ticker tickerData = yf.Ticker(tickerSymbol) # get the historical prices for this ticker tickerDf = tickerData.history(period='1d', start='2015-1-1', end='2020-12-20') # see your data print(tickerDf) # write a python function to get 10 best Artists playing on Apple iTunes def get_artists(): import requests url = 'https://itunes.apple.com/us/rss/topsongs/limit=10/json' response = requests.get(url) data = response.json() for artist_dict in data['feed']['entry']: artist_name = artist_dict['im:artist']['label'] print(artist_name) # write a python function to get prominent words from user test corpus using TFIDF vectorizer def get_words(corpus, new_doc, top=2): import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(stop_words='english') if not corpus: corpus = [ 'I would like to check this document', 'How about one more document', 'Aim is to capture the key words from the corpus', 'frequency of words in a document is called term frequency' ] X = tfidf.fit_transform(corpus) feature_names = np.array(tfidf.get_feature_names()) if not new_doc: new_doc = ['can key words in this new document be identified?', 'idf is the inverse document frequency calculated for each of the words'] responses = tfidf.transform(new_doc) def get_top_tf_idf_words(response, top_n=top): sorted_nzs = np.argsort(response.data)[:-(top_n + 1):-1] return feature_names[response.indices[sorted_nzs]] print([get_top_tf_idf_words(response, 2) for response in responses]) # write a python function to generate wordcloud on given text or file import os def get_word(data): if not (isinstance(data, str) or os.path.isfile(data)): raise TypeError("Text must be string or a File object.") from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt stopwords = set(STOPWORDS) if os.path.isfile(data): with open(data, 'r') as f: data = f.read() data = ' '.join(data.lower().split(' ')) wordcloud = WordCloud(width=400, height=400, background_color='white', stopwords=stopwords, min_font_size=15).generate(data) # plot the WordCloud image plt.figure(figsize=(8, 8), facecolor=None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad=0) plt.show() # get_word(data="./christmas_carol.txt") # write a python function to sort each item in a data structure on one of the keys def sort_list_with_key(): animals = [ {'type': 'lion', 'name': 'Mr. T', 'age': 7}, {'type': 'tiger', 'name': 'scarface', 'age': 3}, {'type': 'puma', 'name': 'Joe', 'age': 4}] print(sorted(animals, key=lambda animal: -animal['age'])) # write a python function with generator for an infinite sequence def infinite_sequence(): n = 0 while True: yield n n += 1 import uuid # write a python function to generate a Unique identifier across space and time in this cosmos. def get_uuid(): return uuid.uuid4() import secrets # write a python function to generate cryptographically strong pseudo-random data def get_cryptographically_secure_data(n=101): return secrets.token_bytes(n), secrets.token_hex(n) # write a python function to convert byte to UTF-8 def byte_to_utf8(data): return data.decode("utf-8") print(byte_to_utf8(data=b'r\xc3\xa9sum\xc3\xa9')) def hanoi(disks, source, auxiliary, target): if disks == 1: print('Move disk 1 from peg {} to peg {}.'.format(source, target)) return hanoi(disks - 1, source, target, auxiliary) print('Move disk {} from peg {} to peg {}.'.format(disks, source, target)) hanoi(disks - 1, auxiliary, source, target) # Write a python program to implement a Stack using One Queue class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self, data): self.q.enqueue(data) def pop(self): for _ in range(self.q.get_size() - 1): dequeued = self.q.dequeue() self.q.enqueue(dequeued) return self.q.dequeue() class Queue: def __init__(self): self.items = [] self.size = 0 def is_empty(self): return self.items == [] def enqueue(self, data): self.size += 1 self.items.append(data) def dequeue(self): self.size -= 1 return self.items.pop(0) def get_size(self): return self.size s = Stack() print('Menu') print('push ') print('pop') print('quit') while True: do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': s.push(int(do[1])) elif operation == 'pop': if s.is_empty(): print('Stack is empty.') else: print('Popped value: ', s.pop()) elif operation == 'quit': break # Write a python program to implement Dequeue class Dequeue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def append(self, data): self.items.append(data) def append_left(self, data): self.items.insert(0, data) def pop(self): return self.items.pop() def pop_left(self): return self.items.pop(0) q = Dequeue() print('Menu') print('append ') print('appendleft ') print('pop') print('popleft') print('quit') while True: do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'append': q.append(int(do[1])) elif operation == 'appendleft': q.append_left(int(do[1])) elif operation == 'pop': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from right: ', q.pop()) elif operation == 'popleft': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from left: ', q.pop_left()) elif operation == 'quit': break # Write a python program to Check and print if string is palindrome using Stack class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() s = Stack() text = "ABA" for character in text: s.push(character) reversed_text = '' while not s.is_empty(): reversed_text = reversed_text + s.pop() if text == reversed_text: print('The string is a palindrome.') else: print('The string is not a palindrome.') # Write a python program to Check and print if Expression is Correctly Parenthesized using Stack class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() s = Stack() exp = "(x+y" for c in exp: if c == '(': s.push(1) elif c == ')': if s.is_empty(): is_balanced = False break s.pop() else: if s.is_empty(): is_balanced = True else: is_balanced = False if is_balanced: print('Expression is correctly parenthesized.') else: print('Expression is not correctly parenthesized.') # Write a python program to Implement Linear Search and print the key element if found def linear_search(alist, key): """Return index of key in alist. Return -1 if key not present.""" for i in range(len(alist)): if alist[i] == key: return i return -1 alist = [2, 3, 5, 6, 4, 5] key = 6 index = linear_search(alist, key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Binary Search without Recursion and print the key element if found def binary_search(alist, key): """Search key in alist[start... end - 1].""" start = 0 end = len(alist) while start < end: mid = (start + end)//2 if alist[mid] > key: end = mid elif alist[mid] < key: start = mid + 1 else: return mid return -1 alist = [2, 3, 5, 6, 4, 5] key = 6 index = binary_search(alist, key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Binary Search with Recursion and print the key element if found def binary_search_rec(alist, start, end, key): """Search key in alist[start... end - 1].""" if not start < end: return -1 mid = (start + end)//2 if alist[mid] < key: return binary_search_rec(alist, mid + 1, end, key) elif alist[mid] > key: return binary_search_rec(alist, start, mid, key) else: return mid alist = [2, 3, 5, 6, 4, 5] key = 6 index = binary_search_rec(alist, 0, len(alist), key) if index < 0: print(f'{key} was not found.') else: print(f'{key} was found at index {index}.') # Write a python program to Implement Bubble sort and print the sorted list for the below list def bubble_sort(alist): for i in range(len(alist) - 1, 0, -1): no_swap = True for j in range(0, i): if alist[j + 1] < alist[j]: alist[j], alist[j + 1] = alist[j + 1], alist[j] no_swap = False if no_swap: return alist = [2, 3, 5, 6, 4, 5] bubble_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Selection sort and print the sorted list for the below list def selection_sort(alist): for i in range(0, len(alist) - 1): smallest = i for j in range(i + 1, len(alist)): if alist[j] < alist[smallest]: smallest = j alist[i], alist[smallest] = alist[smallest], alist[i] alist = [2, 3, 5, 6, 4, 5] selection_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Insertion sort and print the sorted list for the below list def insertion_sort(alist): for i in range(1, len(alist)): temp = alist[i] j = i - 1 while (j >= 0 and temp < alist[j]): alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = temp alist = [2, 3, 5, 6, 4, 5] insertion_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Merge sort and print the sorted list for the below list def merge_sort(alist, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: mid = (start + end)//2 merge_sort(alist, start, mid) merge_sort(alist, mid, end) merge_list(alist, start, mid, end) def merge_list(alist, start, mid, end): left = alist[start:mid] right = alist[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): alist[k] = left[i] i = i + 1 else: alist[k] = right[j] j = j + 1 k = k + 1 if start + i < mid: while k < end: alist[k] = left[i] i = i + 1 k = k + 1 else: while k < end: alist[k] = right[j] j = j + 1 k = k + 1 alist = [2, 3, 5, 6, 4, 5] merge_sort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Quicksort and print the sorted list for the below list def quicksort(alist, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: p = partition(alist, start, end) quicksort(alist, start, p) quicksort(alist, p + 1, end) def partition(alist, start, end): pivot = alist[start] i = start + 1 j = end - 1 while True: while (i <= j and alist[i] <= pivot): i = i + 1 while (i <= j and alist[j] >= pivot): j = j - 1 if i <= j: alist[i], alist[j] = alist[j], alist[i] else: alist[start], alist[j] = alist[j], alist[start] return j alist = [2, 3, 5, 6, 4, 5] quicksort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Heapsort and print the sorted list for the below list def heapsort(alist): build_max_heap(alist) for i in range(len(alist) - 1, 0, -1): alist[0], alist[i] = alist[i], alist[0] max_heapify(alist, index=0, size=i) def parent(i): return (i - 1)//2 def left(i): return 2*i + 1 def right(i): return 2*i + 2 def build_max_heap(alist): length = len(alist) start = parent(length - 1) while start >= 0: max_heapify(alist, index=start, size=length) start = start - 1 def max_heapify(alist, index, size): l = left(index) r = right(index) if (l < size and alist[l] > alist[index]): largest = l else: largest = index if (r < size and alist[r] > alist[largest]): largest = r if (largest != index): alist[largest], alist[index] = alist[index], alist[largest] max_heapify(alist, largest, size) alist = [2, 3, 5, 6, 4, 5] heapsort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Counting sort and print the sorted list for the below list def counting_sort(alist, largest): c = [0]*(largest + 1) for i in range(len(alist)): c[alist[i]] = c[alist[i]] + 1 c[0] = c[0] - 1 for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for x in reversed(alist): result[c[x]] = x c[x] = c[x] - 1 return result alist = [2, 3, 5, 6, 4, 5] k = max(alist) sorted_list = counting_sort(alist, k) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Radix sort and print the sorted list for the below list def radix_sort(alist, base=10): if alist == []: return def key_factory(digit, base): def key(alist, index): return ((alist[index]//(base**digit)) % base) return key largest = max(alist) exp = 0 while base**exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist def counting_sort(alist, largest, key): c = [0]*(largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 c[0] = c[0] - 1 for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result alist = [2, 3, 5, 6, 4, 5] sorted_list = radix_sort(alist) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Bucket sort and print the sorted list for the below list def bucket_sort(alist): largest = max(alist) length = len(alist) size = largest/length buckets = [[] for _ in range(length)] for i in range(length): j = int(alist[i]/size) if j != length: buckets[j].append(alist[i]) else: buckets[length - 1].append(alist[i]) for i in range(length): insertion_sort(buckets[i]) result = [] for i in range(length): result = result + buckets[i] return result def insertion_sort(alist): for i in range(1, len(alist)): temp = alist[i] j = i - 1 while (j >= 0 and temp < alist[j]): alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = temp alist = [2, 3, 5, 6, 4, 5] sorted_list = bucket_sort(alist) print('Sorted list: ', end='') print(sorted_list) # Write a python program to Implement Gnome sort and print the sorted list for the below list def gnome_sort(alist): for pos in range(1, len(alist)): while (pos != 0 and alist[pos] < alist[pos - 1]): alist[pos], alist[pos - 1] = alist[pos - 1], alist[pos] pos = pos - 1 alist = [2, 3, 5, 6, 4, 5] gnome_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Cocktail Shaker sort and print the sorted list for the below list def cocktail_shaker_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i] upper = len(alist) - 1 lower = 0 no_swap = False while (not no_swap and upper - lower > 1): no_swap = True for j in range(lower, upper): if alist[j + 1] < alist[j]: swap(j + 1, j) no_swap = False upper = upper - 1 for j in range(upper, lower, -1): if alist[j - 1] > alist[j]: swap(j - 1, j) no_swap = False lower = lower + 1 alist = [2, 3, 5, 6, 4, 5] cocktail_shaker_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Comb sort and print the sorted list for the below list def comb_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i] gap = len(alist) shrink = 1.3 no_swap = False while not no_swap: gap = int(gap/shrink) if gap < 1: gap = 1 no_swap = True else: no_swap = False i = 0 while i + gap < len(alist): if alist[i] > alist[i + gap]: swap(i, i + gap) no_swap = False i = i + 1 alist = [2, 3, 5, 6, 4, 5] comb_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python program to Implement Shell sort and print the sorted list for the below list def gaps(size): length = size.bit_length() for k in range(length - 1, 0, -1): yield 2**k - 1 def shell_sort(alist): def insertion_sort_with_gap(gap): for i in range(gap, len(alist)): temp = alist[i] j = i - gap while (j >= 0 and temp < alist[j]): alist[j + gap] = alist[j] j = j - gap alist[j + gap] = temp for g in gaps(len(alist)): insertion_sort_with_gap(g) alist = [2, 3, 5, 6, 4, 5] shell_sort(alist) print('Sorted list: ', end='') print(alist) # Write a python Class to calculate area of a rectangle and print the area class rectangle(): def __init__(self,breadth,length): self.breadth=breadth self.length=length def area(self): return self.breadth*self.length a=6 b=4 obj=rectangle(a,b) print("Area of rectangle:",obj.area()) # Write a python Class to calculate area of a circle and print the vale for a radius class CircleArea(): def __init__(self,radius): self.radius=radius def area(self): return 3.14 * self.radius * self.radius a=6 obj=CircleArea(a) print("Area of rectangle:",obj.area()) # Write a python Class to calculate Perimeter of a circle and print the vale for a radius class CirclePerimeter(): def __init__(self,radius): self.radius=radius def perimeter(self): return 2 * 3.14 * self.radius a=6 obj=CirclePerimeter(a) print("Perimeter of rectangle:",obj.perimeter()) # Write a python Class to print All Possible Subsets from a Set of Distinct Integers class sub: def f1(self, s1): return self.f2([], sorted(s1)) def f2(self, curr, s1): if s1: return self.f2(curr, s1[1:]) + self.f2(curr + [s1[0]], s1[1:]) return [curr] a=[2, 3, 5, 6, 4, 5] print("Subsets: ") print(sub().f1(a)) # Write a python program to Read and print the Contents of a File a=str(input("Enter file name .txt extension:")) file2=open(a,'r') line=file2.readline() while(line!=""): print(line) line=file2.readline() file2.close() # Write a python program to Count and print the Number of Words in a Text File fname = input("Enter file name: ") num_words = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print("Number of words:") print(num_words) # Write a python program to Count the Number of Lines in a Text File fname = input("Enter file name: ") num_lines = 0 with open(fname, 'r') as f: for line in f: num_lines += 1 print("Number of lines:") print(num_lines) # Write a python program to Count the Occurrences of a Word in a Text File fname = input("Enter file name: ") word='the' k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==word): k=k+1 print(f"Frequency of Occurrences of the word {a} is:") print(k) # Write a python function to Copy the Contents of One File into Another def copy(from_file, to_file): with open(from_file) as f: with open(to_file, "w") as f1: for line in f: f1.write(line) # Write a python function that Counts the Number of Times a Certain Letter Appears in the Text File def count_letter(fname, l): k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter==l): k=k+1 return k # Write a python function that Print all the Numbers Present in the Text File def print_number(fname): with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter.isdigit()): print(letter) # Write a python function that Counts the Number of Blank Spaces in a Text File def count_blank_space(fname): k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter.isspace): k=k+1 return k # Write a python function that Capitalize the First Letter of Every Word in the File def capitalize(fname): with open(fname, 'r') as f: for line in f: l=line.title() print(l) # Write a python function that prints the Contents of a File in Reverse Order def reverse_content(filename): for line in reversed(list(open(filename))): print(line.rstrip()) # Write a python Program to Flatten and print a List a=[[1,[[2]],[[[3]]]],[[4],5]] flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l] print(flatten(a)) # Write a Python Program to print the LCM of Two Numbers def lcm(a,b): lcm.multiple=lcm.multiple+b if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)): return lcm.multiple else: lcm(a, b) return lcm.multiple lcm.multiple=0 a=4 b=7 if(a>b): LCM=lcm(b,a) else: LCM=lcm(a,b) print(LCM) # Write a Python function to print the GSD of Two Numbers def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) # Write a Python function to Find if a Number is Prime or Not Prime def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print("Number not prime") return False else: return check(n, div-1) else: print("Number is prime") return 'True' # Write a Python function to Find the Power of a Number Using Recursion def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) # Write a Python function to Find the Total Sum of a Nested List Using Recursion def sum1(lst): total = 0 for element in lst: if (type(element) == type([])): total = total + sum1(element) else: total = total + element return total # Write a Python function to Count and print the Number of Vowels Present in a String using Sets def count_vowels(s): count = 0 vowels = set("aeiou") for letter in s: if letter in vowels: count += 1 return count # Write a Python Program to prints Common Letters in Two Input Strings s1='python' s2='schoolofai' a=list(set(s1)&set(s2)) print("The common letters are:") for i in a: print(i) # Write a Python Program that Prints which Letters are in the First String but not in the Second s1='python' s2='schoolofai' a=list(set(s1)-set(s2)) print("The letters are:") for i in a: print(i) # Write a Python Program to Concatenate Two Dictionaries Into One def concat_dic(d1, d2): return d1.update(d2) # Write a Python Program to Multiply All the Items in a Dictionary def mul_dict(d): tot=1 for i in d: tot=tot*d[i] return tot # Write a Python Program to Remove the Given Key from a Dictionary def remove_item_dict(d, key): if key in d: del d[key] else: print("Key not found!") exit(0) # Write a Python Program to Map Two Lists into a Dictionary def map_dict(keys, values): return dict(zip(keys,values)) # Write a Python Program to Remove the nth Index Character from a Non-Empty String def remove(string, n): first = string[:n] last = string[n+1:] return first + last # Write a Python Program to Detect if Two Strings are Anagrams def anagram_check(s1, s2): if(sorted(s1)==sorted(s2)): return True else: return False # Write a Python Program to Form a New String where the First Character and the Last Character have been Exchanged def change(string): return string[-1:] + string[1:-1] + string[:1] # Write a Python Program to Remove the Characters of Odd Index Values in a String def modify(string): final = "" for i in range(len(string)): if i % 2 == 0: final = final + string[i] return final # Write a Python Program to Take in Two Strings and Print the Larger String string1='python' string2='theschoolofai' count1=0 count2=0 for i in string1: count1=count1+1 for j in string2: count2=count2+1 if(count1a[j+1][1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp # Write a Python Program to Find the Second Largest Number in a List Using Bubble Sort a=[2, 3, 8, 9, 2, 4, 6] for i in range(0,len(a)): for j in range(0,len(a)-i-1): if(a[j]>a[j+1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp # Write a Python Program to Find the Intersection of Two Lists def main(alist, blist): def intersection(a, b): return list(set(a) & set(b)) return intersection(alist, blist) # Write a Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number using list comprehension l_range=2 u_range=5 a=[(x,x**2) for x in range(l_range,u_range+1)] # Write a Python Program to print all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10 l=6 u=9 a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10] print(a) # Write a Python Program to Swap the First and Last Value of a List a=[2, 3, 8, 9, 2, 4, 6] n = len(a) temp=a[0] a[0]=a[n-1] a[n-1]=temp print("New list is:") print(a) # Write a Python Program to Remove and print the Duplicate Items from a List a=[2, 3, 8, 9, 2, 4, 6] b = set() unique = [] for x in a: if x not in b: unique.append(x) b.add(x) print("Non-duplicate items:") print(unique) # Write a Python Program to Read a List of Words and Return the Length of the Longest One a=['the', 'tsai', 'python'] max1=len(a[0]) temp=a[0] for i in a: if(len(i)>max1): max1=len(i) temp=i print("The word with the longest length is:") print(temp) # Write a Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat a=['the', 'tsai', 'python' ,'a' ,'the', 'a'] c=[] count=0 b='a' n=3 for i in a: if(i==b): count=count+1 if(count!=n): c.append(i) else: c.append(i) if(count==0): print("Item not found ") else: print("The number of repetitions is: ",count) print("Updated list is: ",c) print("The distinct elements are: ",set(a)) # Write a Python function to Find Element Occurring Odd Number of Times in a List def find_odd_occurring(alist): """Return the element that occurs odd number of times in alist. alist is a list in which all elements except one element occurs an even number of times. """ ans = 0 for element in alist: ans ^= element return ans # Write a Python Program to Check if a Date is Valid and Print the Incremented Date if it is date="20/04/2021" dd,mm,yy=date.split('/') dd=int(dd) mm=int(mm) yy=int(yy) if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12): max1=31 elif(mm==4 or mm==6 or mm==9 or mm==11): max1=30 elif(yy%4==0 and yy%100!=0 or yy%400==0): max1=29 else: max1=28 if(mm<1 or mm>12): print("Date is invalid.") elif(dd<1 or dd>max1): print("Date is invalid.") elif(dd==max1 and mm!=12): dd=1 mm=mm+1 print("The incremented date is: ",dd,mm,yy) elif(dd==31 and mm==12): dd=1 mm=1 yy=yy+1 print("The incremented date is: ",dd,mm,yy) else: dd=dd+1 print("The incremented date is: ",dd,mm,yy) # Write a Python function to Check Whether a Given Year is a Leap Year def leapyear_check(year): if(year%4==0 and year%100!=0 or year%400==0): return True else: return False # Write a Python Program to print Prime Factors of an Integer n=24 print("Factors are:") i=1 while(i<=n): k=0 if(n%i==0): j=1 while(j<=i): if(i%j==0): k=k+1 j=j+1 if(k==2): print(i) i=i+1 # Write a Python Program to print all the Divisors of an Integer n=60 print("The divisors of the number are:") for i in range(1,n+1): if(n%i==0): print(i) # Write a Python Program to Check if a Number is an Armstrong Number def amstrong_check(n): a=list(map(int,str(n))) b=list(map(lambda x:x**3,a)) if(sum(b)==n): return True else: return False # Write a Python Program to Print the Pascalā€™s triangle for n number of rows given by the user n=10 a=[] for i in range(n): a.append([]) a[i].append(1) for j in range(1,i): a[i].append(a[i-1][j-1]+a[i-1][j]) if(n!=0): a[i].append(1) for i in range(n): print(" "*(n-i),end=" ",sep=" ") for j in range(0,i+1): print('{0:6}'.format(a[i][j]),end=" ",sep=" ") print() # Write a Python Program to Check if a Number is a Perfect Number def perfect_no_check(n): sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): return True else: return False # Write a Python Program to Check if a Number is a Strong Number def strong_no_check(num): sum1=0 temp=num while(num): i=1 f=1 r=num%10 while(i<=r): f=f*i i=i+1 sum1=sum1+f num=num//10 if(sum1==temp): return True else: return False # Write a Python Program to Check If Two Numbers are Amicable Numbers def amicable_no_check(x, y): sum1=0 sum2=0 for i in range(1,x): if x%i==0: sum1+=i for j in range(1,y): if y%j==0: sum2+=j if(sum1==y and sum2==x): return True else: return False # Write a Python Program to Check if a Number is a Prime Number def prime_no_check(a): k=0 for i in range(2,a//2+1): if(a%i==0): k=k+1 if(k<=0): return True else: return False # Write a Python Program to print the Sum of First N Natural Numbers n=7 sum1 = 0 while(n > 0): sum1=sum1+n n=n-1 print("The sum of first n natural numbers is",sum1) # Write a Python Program to Print all Pythagorean Triplets in the Range limit=10 c=0 m=2 while(climit): break if(a==0 or b==0 or c==0): break print(a,b,c) m=m+1 # Write a Python Program to print the Number of Times a Particular Number Occurs in a List a=[2, 3, 8, 9, 2, 4, 6] k=0 num=int(input("Enter the number to be counted:")) for j in a: if(j==num): k=k+1 print("Number of times",num,"appears is",k) # Write a Python Program to test and print Collatz Conjecture for a Given Number def collatz(n): while n > 1: print(n, end=' ') if (n % 2): # n is odd n = 3*n + 1 else: # n is even n = n//2 print(1, end='') # Write a Python function to Count Set Bits in a Number def count_set_bits(n): count = 0 while n: n &= n - 1 count += 1 return count # Write a Python Program to Generate Gray Codes using Recursion def get_gray_codes(n): """Return n-bit Gray code in a list.""" if n == 0: return [''] first_half = get_gray_codes(n - 1) second_half = first_half.copy() first_half = ['0' + code for code in first_half] second_half = ['1' + code for code in reversed(second_half)] return first_half + second_half # Write a Python Program to Convert Gray Code to Binary def gray_to_binary(n): """Convert Gray codeword to binary and return it.""" n = int(n, 2) mask = n while mask != 0: mask >>= 1 n ^= mask return bin(n)[2:] # Write a Python Program to Convert Binary to Gray Code def binary_to_gray(n): """Convert Binary to Gray codeword and return it.""" n = int(n, 2) n ^= (n >> 1) return bin(n)[2:] # Write a Python Program to print the Reverse a Given Number n=1023 rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 print("Reverse of the number:",rev) # Write a Python Program to Accept Three Digits and Print all Possible Combinations from the Digits a=2 b=9 c=5 d=[] d.append(a) d.append(b) d.append(c) for i in range(0,3): for j in range(0,3): for k in range(0,3): if(i!=j&j!=k&k!=i): print(d[i],d[j],d[k]) # Write a Python function to Print an Identity Matrix def print_identity_matrix(n): for i in range(0,n): for j in range(0,n): if(i==j): print("1",sep=" ",end=" ") else: print("0",sep=" ",end=" ") print() # Write a Python Program Print Restaurant Menu using Class given menu and cost as list class Food(object): def __init__(self, name, price): self.name = name self.price = price def getprice(self): return self.price def __str__(self): return self.name + ' : ' + str(self.getprice()) def buildmenu(names, costs): menu = [] for i in range(len(names)): menu.append(Food(names[i], costs[i])) return menu names = ['Coffee', 'Tea', 'Pizza', 'Burger', 'Fries', 'Apple', 'Donut', 'Cake'] costs = [250, 150, 180, 70, 65, 55, 120, 350] Foods = buildmenu(names, costs) n = 1 for el in Foods: print(n,'. ', el) n = n + 1 # Write a Python Program to print a list of fibonacci series for a given no using closer def fib(): cache = {1:1, 2:1} def calc_fib(n): if n not in cache: print(f'Calculating fib({n})') cache[n] = calc_fib(n - 1) + calc_fib(n - 2) return cache[n] return calc_fib # Write a Python Program to print a list of fibonacci series for a given no using class class Fib: def __init__(self): self.cache = {1:1, 2:1} def fib(self, n): if n not in self.cache: print(f'Calculating fib({n})') self.cache[n] = self.fib(n-1) + self.fib(n-2) return self.cache[n] # Write a Python function to calculate factorial of a given no using closer def fact(): cache = {0:1, 1:1} def calc_fib(n): if n not in cache: print(f'Calculating fact({n})') cache[n] = calc_fib(n - 1) * n return cache[n] return calc_fib # Write a Python function to calculate factorial of a given no using class class Fact: def __init__(self): self.cache = {0:1, 1:1} def fact(self, n): if n not in self.cache: self.cache[n] = self.fact(n-1) * n return self.cache[n] # Write a Python function to calculate dot product of two given sequence def dot_product(a, b): return sum( e[0]*e[1] for e in zip(a, b)) # Write a Python function to Find the Sum of Sine Series import math def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i pi=22/7 y=x*(pi/180) sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine # Write a Python function to Find the Sum of Cosine Series def cosine(x,n): cosx = 1 sign = -1 for i in range(2, n, 2): pi=22/7 y=x*(pi/180) cosx = cosx + (sign*(y**i))/math.factorial(i) sign = -sign return cosx # Write a Python function to strip vowels from a string def vowel_stripping(string): '''This function takes a string as an input strips out vowels and returns stripted out string''' return "".join([x for x in string if x not in('a','e','i','o','u')]) # Write a Python function that shifts the character of strings def char_shift(string, shift_count): '''This function takes a string as an input and shifts each character by 5 and returns shifted string''' return "".join([chr(ord(x)+shift_count) if (ord(x)+shift_count) <= 122 else chr(96 + (ord(x)+shift_count) - 122) for x in string]) # Write a Python function that returns biggest character in a string from functools import reduce def biggest_char(string): '''This function takes an input as a string and returns the biggest output character in the string''' biggest_chr = lambda x, y: x if ord(x) > ord(y) else y return reduce(biggest_chr, string) # Write a Python function that calculate interior angle of a equilateral polygon def interior_angle(no_of_sides): return (no_of_sides - 2) * 180 / no_of_sides # Write a Python function that calculate side length of a equilateral polygon import math def side_length(no_of_sides, circumradius): return 2 * circumradius * math.sin(math.pi / no_of_sides) # Write a Python function that calculate area of a equilateral polygon import math def area(no_of_sides, circumradius): side_length = 2 * circumradius * math.sin(math.pi / no_of_sides) apothem = circumradius * math.cos(math.pi / no_of_sides) return no_of_sides / 2 * side_length * apothem # write a python function to print every alternate number in the user provided list def print_alternate_numbers(list1): print(list1[::2]) # write a python function to convert a list of string list to a string list def convert_to_string_list(list_of_string_list): res = [''.join(str(b) for b in eval(a)) for a in list_of_string_list] return res # write a python program to clear a list given_list - = [6, 0, 4, 1] given_list.clear() # write a python program to sort and print a list given_list - = [6, 0, 4, 1] sorted_list = sorted(given_list) print(f'sorted list is {sorted_list}') # write a python program to add every alternate elements in a list of even elements and print the final list given_list = [8, 6, 0, 4, 1, 6, 7, 8, 9, 10, 4, 5] if len(given_list) % 2 == 0: res_list = [] for i in range(len(given_list)-2): res_list.append(given_list[i] + given_list[i + 2]) print(f'Resultant list is {res_list}') # write a Python program to print all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # Write a Python Program to print the Factorial of a Number num = 7 factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) # Write a Python Program to Check and print if a given year is a Leap Year year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") # Write Python Program to print if a Number is Odd or Even num = 102 if (num % 2) == 0: print(f"{num} is Even") else: print(f"{num} is Odd") # Write a python function to Compute LCM of two input number def compute_lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # write a python Program to print the ASCII value of the given character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) # write Python Program to print the Sum of 10 Natural Numbers num = 10 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) # write a Python Program to Swap Two Variables and print them x = 5 y = 10 temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) # Write a Python Program to Convert Kilometers to Miles kilometers = 10000 conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) # Write Python Program to Convert Celsius To Fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) # Write Python Program to print the Square Root of a number num = 8 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) # Write python function to count number of 1s in binary representation of an integer. def countSetBits(n): count = 0 while (n): count += n & 1 n >>= 1 return count # Write Python function to check if a string is palindrome or not def isPalindrome(s): return s == s[::-1] # Write a python program to reverse a string s = "i like this program very much" words = s.split(' ') string =[] for word in words: string.insert(0, word) print("Reversed String:") print(" ".join(string)) # Write a python function to merge two Dictionaries def Merge(dict1, dict2): return(dict2.update(dict1)) # Write a python program to print sum of number digits in List test_list = [12, 67, 98, 34] res = [] for ele in test_list: sum = 0 for digit in str(ele): sum += int(digit) res.append(sum) print ("List Integer Summation : " + str(res)) # Write a Python function to count number of lists in a list of lists def countList(lst): count = 0 for el in lst: if type(el)== type([]): count+= 1 return count # Write a Python program to print largest element in an array arr = [10, 324, 45, 90, 9808] print(f'the largest element in the array is {max(arr)}') # Write a Python function to interchange first and last elements in a list def swapList(newList): size = len(newList) temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList # Write a Python function to multiply all values in the list def multiplyList(myList) : result = 1 for x in myList: result = result * x return result # Write a Python program to Multiply two list and print the resultant list test_list1 = [1, 3, 4, 6, 8] test_list2 = [4, 5, 6, 2, 10] res_list = [] for i in range(0, len(test_list1)): res_list.append(test_list1[i] * test_list2[i]) print ("Resultant list is : " + str(res_list)) #write a Python program to print positive numbers in a list list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num >= 0: print(num, end = " ") # Write a Python program to print negative numbers in a list list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num < 0: print(num, end = " ") # Write a python program to Count occurrences of given element in a list def countX(lst, x): return lst.count(x) # Write a python function to remove numeric digits from given string def removedigits(ini_string): res = ''.join([i for i in ini_string if not i.isdigit()]) return res # Write a Python program to print the number words in a sentence test_string = "India is my country" res = len(test_string.split()) print (f"The number of words in string are : {res}") # Write Python function to check if a string has at least one letter and one number def checkString(str): flag_l = False flag_n = False for i in str: if i.isalpha(): flag_l = True if i.isdigit(): flag_n = True return flag_l and flag_n # Write a python function to Check whether triangle is valid or not if three points are given def checkTriangle(x1, y1, x2, y2, x3, y3): a = (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) if a == 0: return False else: return True # Write a python function to Check whether triangle is valid or not if sides are given def checkValidity(a, b, c): if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True # Write a Python Program to print words starting with Vowel From A list test_list = ["all", "love", "and", "get", "educated", "by", "gfg"] print("The original list is : " + str(test_list)) res = [] vow = "aeiou" for sub in test_list: flag = False for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) print("The extracted words : " + str(res)) # Write a python function to extract odd length words in String def findoddlenthwords(test_str): res = [] for ele in test_str.split(): if len(ele) % 2 : res.append(ele) return res # Write a python function to extract even length words in String def findevenlenthwords(test_str): res = [] for ele in test_str.split(): if len(ele) % 2 == 0: res.append(ele) return res # Write a python program to print Words lengths in String test_string = "India is my country" res = list(map(len, test_string.split())) print ("The list of words lengths is : " + str(res)) # Write a python program to check if a number is positive or negative num = 15 if num > 0: print(f"Positive number") elif num == 0: print(f"Zero") else: print(f"Negative number") # write a Python Program to Display the multiplication Table of given number num = 12 for i in range(1, 11): print(num, 'x', i, '=', num*i) # write a Python function to Convert Decimal to Binary def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2,end = '') # write a Python Program to Count and print the Number of Each Vowel in the input string vowels = 'aeiou' ip_str = 'India is my country' ip_str = ip_str.casefold() count = {}.fromkeys(vowels,0) for char in ip_str: if char in count: count[char] += 1 print(count) # write a Python Program to Check Whether a String is Palindrome or Not my_str = 'aIbohPhoBiA' my_str = my_str.casefold() rev_str = reversed(my_str) if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") # Write Python Program to Remove Punctuations From a String and print the cleaned string. punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) # Write a Python program to print unique triplets whose three elements gives the sum of zero from an array of n integers. num = [1, -6, 4, 2, -1, 2, 0, -2, 0 ] len_list = len(num) trips = [] for i in range(len_list): if i+3 > len_list: break triplets = num[i:i+3] if len(set(triplets))==3: if sum(triplets) == 0: trips.append(triplets) print(trips) # Write a Python program to remove and print every third number from a list of numbers until the list becomes empty. num = [10,20,30,40,50,60,70,80,90] len_list = len(num) position = 3 - 1 idx = 0 while len_list > 0: idx = (idx+position) % len_list print(num.pop(idx)) len_list-=1 # Write a Python function to compute simple interest def simple_interest(p,t,r): si = (p * t * r)/100 return si # Write a Python function to compute compound interest def compound_interest(principle, rate, time): Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle return CI # Write a Python function for Program to find area of a circle def findArea(r): PI = 3.142 return PI * (r*r) # Write a python function to find Area Of Rectangle def areaRectangle(a, b): return (a * b) # Write a python function to find perimeter Of Rectangle def perimeterRectangle(a, b): return (2 * (a + b)) # write a python function to convert string in to binary def convertstringtobinary(text): for chr in text: bin = '' asciiVal = int(ord(chr)) while asciiVal > 0: if asciiVal % 2 == 0: bin = bin + '0' else: bin = bin + '1' asciiVal = int(asciiVal/2) return(bin + " : " + bin[::-1]) # Write a python program to print the Sum of digits of a number n = 12345 q = 0 while(n>0): r=n%10 q=q+r n=n//10 print("Sum of digits is: "+str(q)) # Write a python program to sort alphabetically the words form a string provided by the user def sortwords(my_str): words = my_str.split() words.sort() return ' '.join(words) # Write a python function to replace all the spaces in an entered string with a hyphen "-" def replacetext(string): string = string.replace(" ", "-") return string # write a python program to rotate a list 10 times and print it list = [11,22,33,44,55,66,77,88,99] n = 10 finalList = [] for i in range(0, N): finalList.append(list[(i+d)%N]) print(finalList) # write a Python Program to Add two binary numbers and print the sum num1 = '00001' num2 = '10001' sum = bin(int(num1,2) + int(num2,2)) print(sum) # write a Python Program to Calculate and print the Average of Numbers in a Given List a= [11,22,33,44,55,66,77,88,99] avg=sum(a)/len(a) print("Average of elements in the list",round(avg,2)) # write a Python Program to check if a number is a Perfect number and print the result n = 7 sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): print("The number is a Perfect number!") else: print("The number is not a Perfect number!") # write a Python function to convert binary to Gray codeword def binary_to_gray(n): n = int(n, 2) n ^= (n >> 1) return bin(n)[2:] # write a Python function to convert Gray code to binary def gray_to_binary(n): n = int(n, 2) # convert to int mask = n while mask != 0: mask >>= 1 n ^= mask return bin(n)[2:] # write a Python Program to Replace all Occurrences of ā€˜aā€™ with $ in a String def replacestring(txt): return txt.replace('A','$') # write a python program to Print Quotient and Remainder of two numbers a = 15 b = 4 quotient=a//b remainder=a%b print("Quotient is:",quotient) print("Remainder is:",remainder) # write a python program to print the Area of a Triangle Given All Three Sides a = 15 b = 9 c = 7 s=(a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c)) ** 0.5 print("Area of the triangle is: ",round(area,2)) # write a Python function to Determine all Pythagorean Triplets in the Range def findpythagoreantriplets(limit): c=0 m=2 while(climit): break if(a==0 or b==0 or c==0): break print(a,b,c) m=m+1 # write a Python Program to print all the Divisors of an Integer n = 20 print("The divisors of the number are:") for i in range(1,n+1): if(n%i==0): print(i) # Write a python program to print dimension in centimeter to inches cm = 50 inches=0.394*cm print("The dimension in inches ",round(inches,2)) # Write a python program to print dimension in centimeter to feet cm = 50 feet=0.0328*cm print("The dimension in feet ",round(feet,2)) # write Python Program to print the Union of two Lists l1 = [11,22,33,44] l2 = [55,66,77,88] union = list(set().union(l1,l2)) print('The Union of two lists is:',union) # write a python function to Check if a Substring is Present in a Given String def checksubstring(string,sub_string): if(string.find(sub_str)==-1): return False else: return True # Write a Python Program to Multiply All the Items in a Dictionary and print the result d={'A':10,'B':10,'C':239} tot=1 for i in d: tot=tot*d[i] print(tot) # Write Python Program to print Common Letters in Two Input Strings s1="Trump was the American President" s2="Who is the American President now?" a=list(set(s1)&set(s2)) print("The common letters are:") for i in a: print(i) # Write a Python function to Find Whether a Number is a Power of Two def is_power_of_two(n): if n <= 0: return False else: return n & (n - 1) == 0 # Write a Python Program to Search the Number of Times a Particular Number Occurs in a List a = [2,3,2,3,4,4,5,5,6,6,6] k=0 num=6 for j in a: if(j==num): k=k+1 print("Number of times",num,"appears is",k) # write Python function to Clear the Rightmost Set Bit of a Number def clear_rightmost_set_bit(n): return n & (n - 1) # write a Python function to Find HCF of two numbers def hcf(x, y): if x > y: smaller = y else: smaller = x for i in range(1,smaller + 1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf # Write a Python Program to Add Two Matrices and print result. X = [[1,2,3], [4,5,6], [7,8,9]] Y = [[10,11,12], [13,14,15], [16,17,18]] result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) # write Python Program to Multiply Two Matrices and print result. X = [[1,2,3], [4,5,6], [7,8,9]] Y = [[10,11,12], [13,14,15], [16,17,18]] result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) # Write a Python Program to Transpose a Matrix and print result. X = [[1,2], [4,5], [7,8]] Result = [[0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) # Write a Python function to Find the Intersection of Two Lists def intersection(a, b): return list(set(a) & set(b)) # write a Python function to Sort a List According to the Length of the Elements. def sortlistwithlen(list): list.sort(key=len) return list # Write a Python Program to Print an Identity Matrix n = 3 for i in range(0,n): for j in range(0,n): if(i==j): print("1",sep=" ",end=" ") else: print("0",sep=" ",end=" ") # Write a Python Program to print Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers lower = 1 upper = 100 for i in range (lower,upper+1): if(i%7==0 and i%5==0): print(i) # write Python function to find the Length of the Longest One element in the list def findlongest(list): max1=len(list[0]) temp=list[0] for i in list: if(len(i)>max1): max1=len(i) temp=i return temp # write a Python function to Detect if Two Strings are Anagrams def check_if_anagram(s1,s2): if(sorted(s1)==sorted(s2)): return True else: return False # Write Python Program to print the Length of a String Without Using a Library Function string= "United States of America" count=0 for i in string: count=count+1 print("Length of the string is:") print(count) # Write Python Program to Find the Area of a Rectangle Using Classes class rectangle(): def __init__(self,breadth,length): self.breadth=breadth self.length=length def area(self): return self.breadth*self.length a=15 b=10 obj=rectangle(a,b) print("Area of rectangle:",obj.area()) # Write a Python Program to Find the Second Largest Number in a List a= [11,22,33,44,55,66,77,88,99] a.sort() print("Second largest element is:",a[n-2]) # Write a Python Program to Count Number of Lowercase Characters in a String and print the result string="SriNAtH" count=0 for i in string: if(i.islower()): count=count+1 print("The number of lowercase characters is:") print(count) # write a Python Program to Sum All the Items in a Dictionary and print the result d={'A':100,'B':540,'C':239} print("Total sum of values in the dictionary:") print(sum(d.values())) # write Python function to Count the Frequency of Words Appearing in a String Using a Dictionary def countword(test_string): l=[] l=test_string.split() wordfreq=[l.count(p) for p in l] return(dict(zip(l,wordfreq))) # write Python Program to Read the Contents of a File a=str(input("Enter the name of the file with .txt extension:")) file2=open(a,'r') line=file2.readline() while(line!=""): print(line) line=file2.readline() file2.close() # write Python Program to Count the Number of Lines in a Text File fname = input("Enter file name: ") num_lines = 0 with open(fname, 'r') as f: for line in f: num_lines += 1 print("Number of lines:") print(num_lines) # write Python Program to Count the Number of Words in a Text File fname = input("Enter file name: ") num_words = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print("Number of words:") print(num_words) # write a Python Program to Read a File and Capitalize the First Letter of Every Word in the File fname = input("Enter file name: ") with open(fname, 'r') as f: for line in f: l=line.title() print(l) # write Python Program to Read the Contents of a File in Reverse Order filename=input("Enter file name: ") for line in reversed(list(open(filename))): print(line.rstrip()) # write a Python function to Remove the Given Key from a Dictionary def deletekey(dict,key) if key in dict: del dict[key] return dict # Write a python function to remove an item from list def deleteelement(list, item): list.remove(item) return list # write a python function to Check if a given string is binary string or not def check(string) : s = {'0', '1'} if s == p or p == {'0'} or p == {'1'}: return True else : return False # write a python function to compute minimum number of rotations required to get the same string def findRotations(str): tmp = str + str n = len(str) for i in range(1, n + 1): substring = tmp[i: i+n] if (str == substring): return i return n # write a Python function to check if count of divisors is even or odd def NumOfDivisor(n): if n < 1: return root_n = n**0.5 if root_n**2 == n: print("Odd") else: print("Even") # Write a program to merge two python dictionaries and print merged dictionary d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(d) # write a python function to concatenate two integers like string concatenation and return concatenated number as integer def concat_two_numbers(num1, num2): combined_num = str(num1) + str(num2) return int(combined_num) # With a given integral number n, write a program to generate a dictionary that contains (i, i*i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. n = 8 d = dict() for i in range(1,n+1): d[i] = i*i*i print(d) # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. values=input() l=values.split(",") t=tuple(l) print(l) print(t) # Write a Python function that takes a sequence of numbers and determines whether all the numbers are different from each other def test_distinct(data): if len(data) == len(set(data)): return True else: return False # Write a Python function to find the number of notes (Sample of notes: 10, 20, 50, 100, 200 and 500 ) against a given amount. def no_notes(a): Q = [500, 200, 100, 50, 20, 10, 5, 2, 1] x = 0 for i in range(9): q = Q[i] x += int(a / q) a = int(a % q) if a > 0: x = -1 return x # Write a Python function to find the number of zeros at the end of a factorial of a given positive number. def factendzero(n): x = n // 5 y = x while x > 0: x /= 5 y += int(x) return y # Write a Python function for Binary Search def binary_search(l, num_find): ''' This function is used to search any number. Whether the given number is present in the list or not. If the number is present in list the list it will return TRUE and FALSE otherwise. ''' start = 0 end = len(l) - 1 mid = (start + end) // 2 found = False position = -1 while start <= end: if l[mid] == num_find: found = True position = mid break if num_find > l[mid]: start = mid + 1 mid = (start + end) // 2 else: end = mid - 1 mid = (start + end) // 2 return (found, position) # Write a Python function to remove leading zeros from an IP address import re regex = '\.[0]*' def remove_leading_zeros(ip): modified_ip = re.sub(regex, '.', ip) return modified_ip # Write a Python function to return binary value of a given integer def int_to_bin(a): return bin(a) # Write a Python function to return octal value of a given integer def int_to_oct(a): return oct(a) # Write a Python function to return hexadecimal value of a given integer def int_to_hex(a): return hex(a) # Write a Python program to typecast given input to integer num = int(input("Input a value: ")) print(num) # Write a Python program to typecast given input to float num = float(input("Input a value: ")) print(num) # Write a Python program to check/test multiple variables against a value a = 10 b = 20 c = 30 if 10 in {a, b, c}: print("True") else: print("False") # Write a Python class that will initiate a number, input a number and print the number class Number: def __init__(self, num): self.num = num def inputNum(self): self.num = int(input("Enter an integer number: ")) def printNum(self): print(self.num) # Write a Python function to find the simple interest in Python when principle amount, rate of interest and time is given def simple_interest(p,r,t): si = (p*r*t)/100 return si # Write a Python function to find the compound interest in Python when principle amount, rate of interest and time is given def compound_interest(p,r,t): ci = p * (pow((1 + r / 100), t)) return ci # Write a Python function to check whether a person is eligible for voting or not based on their age def vote_eligibility(age): if age>=18: status="Eligible" else: status="Not Eligible" return status # Write a Python function to find the BMI for given weight and height of a person def bmi_calculator(height, weight): bmi = weight/(height**2) return bmi # Write a Python function to check whether a given number is perfect number or not def perfect_number_checker(num): i = 2 sum = 1 while(i <= num//2 ) : if (num % i == 0) : sum += i i += 1 if sum == num : return f'{num} is a perfect number' else : return f'{num} is not a perfect number' # Write a Python function to find the maximum ODD number from a given list def odd_max_checker(list1): maxnum = 0 for num in list1: if num%2 != 0: if num > maxnum: maxnum = num return maxnum # Write a Python function to find the maximum EVEN number from a given list def even_max_checker(list1): maxnum = 0 for num in list1: if num%2 == 0: if num > maxnum: maxnum = num return maxnum # Write a Python function to print the root of the quadratic equation def quadratic_root(A,B,C): import math d=((B**2)-4*A*C) if d>=0: s=(-B+(d)**0.5)/(2*A) p=(-B-(d)**0.5)/(2*A) print(math.floor(s),math.floor(p)) else: print('The roots are imaginary') # Write a Python program to print the calendar of any given year import calendar year=2020 print(calendar.calendar(year)) # Write a Python function to print whether the given Date is valid or not def date_validator(d,m,y): import datetime try: s=datetime.date(y,m,d) print("Date is valid.") except ValueError: print("Date is invalid.") # Write a Python function to find the N-th number which is both square and cube def nth_sq_and_cube(N): R = N**6 return R # Write a Python function to check whether a number is a power of another number or not def power_checker(a,b): import math s=math.log(a,b) p=round(s) if (b**p)==a: return f'{a} is the power of {b}.' else: return f'{a} is NOT the power of {b}.' # Write a Python function to def binary_palindrome(n): s=int(bin(n)[2:]) r=str(s)[::-1] if int(r)==s: return "The binary representation of the number is a palindrome." else: return "The binary representation of the number is NOT a palindrome." # Write a Python program to print the list of all keywords import keyword print("Python keywords are...") print(keyword.kwlist) # Write a Python function to find the intersection of two arrays def array_intersection(A,B): inter=list(set(A)&set(B)) return inter # Write a Python function to find the union of two arrays def array_union(A,B): union=list(set(A)|set(B)) return union # Write a Python program to print shape of an array/ matrix import numpy as np A = np.array([[1,2,3],[2,3,5],[3,6,8],[323,623,823]]) print("Shape of the matrix A: ", A.shape) # Write a Python program to print rank of an array/ matrix import numpy as np A = np.array([[4,5,8], [7,1,4], [5,5,5], [2,3,6]]) print("Rank of the matrix A: ", np.linalg.matrix_rank(A)) # Write a Python program to print trace of an array/ matrix import numpy as np A = np.array([[4,5,8], [5,5,5], [2,3,6]]) print("Trace of the matrix A: ", np.trace(A)) # Write a Python program to print euclidean distance between two array/ vectors import numpy as np a = np.array([78, 84, 87, 91, 76]) b = np.array([92, 83, 91, 79, 89]) dist = np.linalg.norm(a-b) print('Differnce in performance between A and B : ', dist) # Write a Python function to print number with commas as thousands separators def formattedNumber(n): return ("{:,}".format(n)) # Write a Python program to find the total number of uppercase and lowercase letters in a given string str1='TestStringInCamelCase' no_of_ucase, no_of_lcase = 0,0 for c in str1: if c>='A' and c<='Z': no_of_ucase += 1 if c>='a' and c<='z': no_of_lcase += 1 print(no_of_lcase) print(no_of_ucase) # Write a Python program to find the total number of letters and digits in a given string str1='TestStringwith123456789' no_of_letters, no_of_digits = 0,0 for c in str1: no_of_letters += c.isalpha() no_of_digits += c.isnumeric() print(no_of_letters) print(no_of_digits) # Write a Python function to count occurrence of a word in the given text def text_searcher(text, word): count = 0 for w in text.split(): if w == word: count = count + 1 return count # Write a Python function to capitalizes the first letter of each word in a string def capitalize(text): return text.title() # Write a Python function to remove falsy values from a list def newlist(lst): return list(filter(None, lst)) # Write a Python function to to find the sum of all digits of a given integer def sum_of_digits(num): if num == 0: return 0 else: return num % 10 + sum_of_digits(int(num / 10)) # Write a Python function to check all elements of a list are the same or not def check_equal(a): return a[1:] == a[:-1] # Write a Python program to print Square root of matrix elements mat1 = np.array([[10,20,30],[40,50,60],[70,80,90]]) print(np.sqrt(mat1)) # Write a Python function that returns the integer obtained by reversing the digits of the given integer def reverse(n): s=str(n) p=s[::-1] return p # Write a Python program to convert the index of a series into a column of a dataframe import pandas as pd import numpy as np mylist = list('abcedfghijklmnopqrstuvwxyz') myarr = np.arange(26) mydict = dict(zip(mylist, myarr)) ser = pd.Series(mydict) df = ser.to_frame().reset_index() print(df.head()) # Write a Python program to keep only top 2 most frequent values as it is and replace everything else as ā€˜Otherā€™ in a series import pandas as pd import numpy as np np.random.RandomState(100) ser = pd.Series(np.random.randint(1, 5, [12])) ser[~ser.isin(ser.value_counts().index[:2])] = 'Other' print(ser) # Write a Python program to bin a numeric series to 10 groups of equal size import pandas as pd import numpy as np ser = pd.Series(np.random.random(20)) deciled = pd.qcut(ser, q=[0, .10, .20, .3, .4, .5, .6, .7, .8, .9, 1], labels=['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']) print(deciled) # Write a Python program to create a TimeSeries starting ā€˜2000-01-01ā€™ and 10 weekends (saturdays) after that having random numbers as values import pandas as pd import numpy as np ser = pd.Series(np.random.randint(1,10,10), pd.date_range('2000-01-01', periods=10, freq='W-SAT')) print(ser) # Write a Python program to fill an intermittent time series so all missing dates show up with values of previous non-missing date import pandas as pd import numpy as np ser = pd.Series([1,10,3, np.nan], index=pd.to_datetime(['2000-01-01', '2000-01-03', '2000-01-06', '2000-01-08'])) print(ser.resample('D').ffill()) # Write a Python program to fill an intermittent time series so all missing dates show up with values of next non-missing date import pandas as pd import numpy as np ser = pd.Series([1,10,3, np.nan], index=pd.to_datetime(['2000-01-01', '2000-01-03', '2000-01-06', '2000-01-08'])) print(ser.resample('D').bfill()) # Write a Python program to create one-hot encodings of a categorical variable import pandas as pd import numpy as np df = pd.DataFrame(np.arange(25).reshape(5,-1), columns=list('abcde')) df_onehot = pd.concat([pd.get_dummies(df['a']), df[list('bcde')]], axis=1) print(df_onehot) # Write a Python program to compute the autocorrelations for first 10 lags of a numeric series import pandas as pd import numpy as np ser = pd.Series(np.arange(20) + np.random.normal(1, 10, 20)) autocorrelations = [ser.autocorr(i).round(2) for i in range(11)] print(autocorrelations[1:]) # Write a Python program to find the positions of numbers that are multiples of 3 from a series import pandas as pd import numpy as np ser = pd.Series(np.random.randint(1, 10, 7)) print(np.argwhere(ser.values % 3 == 0)) # Write a Python function that Given a string, display only those characters which are present at an even index number def printEveIndexChar(str): for i in range(0, len(str)-1, 2): print("index[",i,"]", str[i] ) # Write a Python function that Given a string and an integer number n, remove characters from a string starting from zero up to n and return a new string def removeChars(str, n): return str[n:] # Write a Python function that Given a list of numbers, return True if first and last number of a list is same def isFirst_And_Last_Same(numberList): firstElement = numberList[0] lastElement = numberList[-1] if (firstElement == lastElement): return True else: return False # Write a Python function that Given a list of numbers, Iterate it and print only those numbers which are divisible of 5 def findDivisible(numberList): for num in numberList: if (num % 5 == 0): print(num) # Write a Python function that Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list def mergeList(list1, list2): thirdList = [] for num in list1: if (num % 2 != 0): thirdList.append(num) for num in list2: if (num % 2 == 0): thirdList.append(num) return thirdList # Write a Python program to return a set of all elements in either A or B, but not both set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.symmetric_difference(set2)) # Write a Python program to Subtract a week ( 7 days) from a given date in Python from datetime import datetime, timedelta given_date = datetime(2020, 2, 25) days_to_subtract = 7 res_date = given_date - timedelta(days=days_to_subtract) print(res_date) # Write a Python program to Find the day of week of a given date from datetime import datetime given_date = datetime(2020, 7, 26) print(given_date.strftime('%A')) # Write a Python program to Convert following datetime instance into string format from datetime import datetime given_date = datetime(2020, 2, 25) string_date = given_date.strftime("%Y-%m-%d %H:%M:%S") print(string_date) # Write a Python program to convert two equal length sets to dictionary keys = {'Ten', 'Twenty', 'Thirty'} values = {10, 20, 30} sampleDict = dict(zip(keys, values)) print(sampleDict) # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5 between 2000 and 3200 (both included). l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) # Write a program that will determine the object type def typeIdentifier(object): return f'object type : {type(object)}' # Write a Python class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. class IOString(object): def __init__(self): self.s = "" def getString(self): self.s = input() def printString(self): print(self.s.upper()) strObj = IOString() strObj.getString() strObj.printString() # Write a program that will determine the memory usage by python process import os, psutil print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2) # Write a function that will provide the ascii value of a character def charToASCII(chr): return f'ASCII value of {chr} is: {ord(chr)}' # Write a function to reverse a string def revStr(inp): inp = inp[::-1] return inp # Write a function to determine the bits used by any number def totalBits(n): return f'total number of bits used in {n} is : {len(bin(n)[2: ])}' # write a function to find the sum of Sine series import math def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i pi=22/7 y=x*(pi/180) sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine # Write a function to determine whether a given number is even or odd recursively def check(n): if (n < 2): return (n % 2 == 0) return (check(n - 2)) n=int(input("Enter number:")) if(check(n)==True): print("Number is even!") else: print("Number is odd!") # Write a program to swap two variables inplace a,b = b,a # Write a program that prints the words in a comma-separated sequence after sorting them alphabetically. items=[x for x in input().split(',')] items.sort() print(','.join(items)) # Write a function that takes a base and a power and finds the power of the base using recursion. def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) base=int(input("Enter base: ")) exp=int(input("Enter exponential value: ")) print("Result:",power(base,exp)) # Write a function to repeat M characters of a string N times def multTimes(str, m, n): front_len = m if front_len > len(str): front_len = len(str) front = str[:front_len] result = '' for i in range(n): result = result + front return result print (multTimes('Hello', 3, 7)) # Write a function that will convert a string into camelCase from re import sub def camelCase(string): string = sub(r"(_|-)+", " ", string).title().replace(" ", "") return string[0].lower() + string[1:] # Write a function to remove empty list from a list using list comprehension def removeEmptyList(li): res = [ele for ele in li if ele != []] return res # Write a function to Find the size of a Tuple in Python without garbage values Tuple = (10,20) def sizeOfTuple(tup): return f'Size of Tuple: {str(Tuple.__sizeof__())} bytes' # Write a function, which will find all such numbers between 1000 to 9999 that each digit of the number is an even number. values = [] for i in range(1000, 9999): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) # Write a function that finds a list is homogeneous def homoList(li): res = True for i in li: if not isinstance(i, type(li[0])): res = False break return res # Write a function to remove a given date type elements from a list. def removeDataType(li,dType): res = [] for i in li: if not isinstance(i, dType): res.append(i) return res # Write a python function to find out the occurence of "i" element before first "j" in the list def firstOccurence(arr, i,j): res = 0 for k in arr: if k == j: break if k == i: res += 1 return res # Write a program to check whether a file/path/direcory exists or not file_path = "path/here" import os.path os.path.exists(file_path) # Write a program to merge two python dictionaries x={'key1':'val1','key2':'val2'} y={'key3':'val3','key4':'val4'} z = {**x, **y} # z = x | y # Write a program to convert dictionary into JSON import json data = {"key1" : "value1", "key2" : "value2"} jsonData = json.dumps(data) print(jsonData) # Write a program to find common divisors between two numbers in a given pair def ngcd(x, y): i=1 while(i<=x and i<=y): if(x%i==0 and y%i == 0): gcd=i i+=1 return gcd def num_comm_div(x, y): n = ngcd(x, y) result = 0 z = int(n**0.5) i = 1 while( i <= z ): if(n % i == 0): result += 2 if(i == n/i): result-=1 i+=1 return result # Write a function to Check whether following json is valid or invalid import json def validateJSON(jsonData): try: json.loads(jsonData) except ValueError as err: return False return True # Write a function to remove and print every third number from a list of numbers until the list becomes empty def remove_nums(int_list): position = 3 - 1 idx = 0 len_list = (len(int_list)) while len_list>0: idx = (position+idx)%len_list print(int_list.pop(idx)) len_list -= 1 # Write a program to take a string and print all the words and their frequencies string_words = '''This assignment is of 900 marks. Each example if 9 marks. If your example is similar to someone else, then you score less. The formula we will use is 9/(repeated example). That means if 9 people write same example, then you get only 1. So think different! (if examples are mentioned here and in the sample file, you will score less)''' word_list = string_words.split() word_freq = [word_list.count(n) for n in word_list] print("Pairs (Words and Frequencies:\n {}".format(str(list(zip(word_list, word_freq))))) # Write a program to get a list of locally installed Python modules import pkg_resources installed_packages = pkg_resources.working_set installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) for m in installed_packages_list: print(m) # Write a function to create all possible permutations from a given collection of distinct numbers def permute(nums): result_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) result_perms = new_perms return result_perms # Write a function to add two positive integers without using the '+' operator def add_without_plus_operator(a, b): while b != 0: data = a & b a = a ^ b b = data << 1 return a # Write a program to find the median among three given number x=10 y=20 z=30 if y < x and x < z: print(x) elif z < x and x < y: print(x) elif z < y and y < x: print(y) elif x < y and y < z: print(y) elif y < z and z < x: print(z) elif x < z and z < y: print(z) # Write a function to count the number of carry operations for each of a set of addition problems def carry_number(x, y): ctr = 0 if(x == 0 and y == 0): return 0 z = 0 for i in reversed(range(10)): z = x%10 + y%10 + z if z > 9: z = 1 else: z = 0 ctr += z x //= 10 y //= 10 if ctr == 0: return "No carry operation." elif ctr == 1: return ctr else: return ctr # Write a program to compute the number of digits in multiplication of two given integers a,b = 312, 410 print(len(str(a*b))) # Write a function to return the area of a rhombus def area(d1, a): d2 = (4*(a**2) - d1**2)**0.5 area = 0.5 * d1 * d2 return(area) # Write a function that Given a number, find the most significant bit number which is set bit and which is in power of two def setBitNumber(n): if (n == 0): return 0 msb = 0 n = int(n / 2) while (n > 0): n = int(n / 2) msb += 1 return (1 << msb) # Write a function to calculate volume of Triangular Pyramid def volumeTriangular(a, b, h): return (0.1666) * a * b * h # Write a function to calculate volume of Square Pyramid def volumeSquare(b, h): return (0.33) * b * b * h # Write a function to calculate Volume of Pentagonal Pyramid def volumePentagonal(a, b, h): return (0.83) * a * b * h # Write a function to calculate Volume of Hexagonal Pyramid def volumeHexagonal(a, b, h): return a * b * h # Write a Python program to check a list is empty or not l = [] if not l: print("List is empty") # Write a Python program to remove duplicates from a list. a = [10,20,30,20,10,50,60,40,80,50,40] dup_items = set() uniq_items = [] for x in a: if x not in dup_items: uniq_items.append(x) dup_items.add(x) print(dup_items) # Write a Python function that takes two lists and returns True if they have at least one common member def common_data(list1, list2): result = False for x in list1: for y in list2: if x == y: result = True return result print(common_data([1,2,3,4,5], [5,6,7,8,9])) # Write a Python program to get the difference between the two lists list1 = [1, 2, 3, 4] list2 = [1, 2] print(list(set(list1) - set(list2))) # Write a Python program to find the second smallest number in a list def second_smallest(numbers): a1, a2 = float('inf'), float('inf') for x in numbers: if x <= a1: a1, a2 = x, a1 elif x < a2: a2 = x return a2 print(second_smallest([1, 2, -8, -2, 0])) # Write a Python program to find the second largest number in a list. def second_largest(numbers): count = 0 n1 = n2 = float('-inf') for x in numbers: count += 1 if x > n2: if x >= n1: n1, n2 = x, n1 else: n2 = x return n2 if count >= 2 else None print(second_largest([1, 2, -8, -2, 0])) # Write a Python program to get the frequency of the elements in a list import collections my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30] print("Original List : ",my_list) ctr = collections.Counter(my_list) print("Frequency of the elements in the List : ",ctr) # Write a Python program to convert a list of multiple integers into a single integer L = [11, 33, 50] x = int("".join(map(str, L))) print("Single Integer: ",x) # Write a Python program to check if all dictionaries in a list are empty or not. my_list = [{},{},{}] my_list1 = [{1,2},{},{}] print(all(not d for d in my_list)) print(all(not d for d in my_list1)) # Write a Python program to count the number of characters (character frequency) in a string def char_frequency(str1): dict = {} for n in str1: keys = dict.keys() if n in keys: dict[n] += 1 else: dict[n] = 1 return dict print(char_frequency('google.com')) #Write a python program to replace the first character occurence in the later part of the string def change_char(str1): char = str1[0] length = len(str1) str1 = str1.replace(char, '$') str1 = char + str1[1:] return str1 print(change_char('restart')) # Write a Python function that takes a list of words and returns the longest one def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][1] print(find_longest_word(["PHP", "python", "zekelabs"])) # Write a Python program to count the occurrences of each word in a given sentence def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][1] print(find_longest_word(["PHP", "python", "zekelabs"])) # Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters. def to_uppercase(str1): num_upper = 0 for letter in str1[:4]: if letter.upper() == letter: num_upper += 1 if num_upper >= 2: return str1.upper() return str1 print(to_uppercase('PyThon')) # Write a Python program to count and display the vowels of a given text def vowel(text): vowels = "aeiuoAEIOU" print(len([letter for letter in text if letter in vowels])) print([letter for letter in text if letter in vowels]) vowel('zekelabs') # Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x) n=int(input("Input a number: ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d) # Write a Python program to convert a list into a nested dictionary of keys. num_list = [1, 2, 3, 4] new_dict = current = {} for name in num_list: current[name] = {} current = current[name] print(new_dict) # Write a Python program to sort a list alphabetically in a dictionary. num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]} sorted_dict = {x: sorted(y) for x, y in num.items()} print(sorted_dict) # Write a Python program to match key values in two dictionaries. x = {'key1': 1, 'key2': 3, 'key3': 2} y = {'key1': 1, 'key2': 2} for (key, value) in set(x.items()) & set(y.items()): print('%s: %s is present in both x and y' % (key, value)) # Write a Python program to count the elements in a list until an element is a tuple num = [10,20,30,(10,20),40] ctr = 0 for n in num: if isinstance(n, tuple): break ctr += 1 print(ctr) # Write a Python program to convert a tuple to a string. tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's') str = ''.join(tup) print(str) # Write a Python program to find the repeated items of a tuple tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 count = tuplex.count(4) print(count) # Write a Python program to convert a tuple to a dictionary. tuplex = ((2, "w"),(3, "r")) print(dict((y, x) for x, y in tuplex)) # Write a Python program to sort a tuple by its float element. price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')] print( sorted(price, key=lambda x: float(x[1]), reverse=True)) # Write a Python program to add member(s) in a set color_set = set() color_set.add("Red") color_set.update(["Blue", "Green"]) print(color_set) # Write a Python program to create a symmetric difference setx = set(["apple", "mango"]) sety = set(["mango", "orange"]) setc = setx ^ sety print(setc) # Write a Python program to count the number of even and odd numbers from a series of numbers. numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 print("Number of even numbers :",count_even) print("Number of odd numbers :",count_odd) # Write a Python program that prints all the numbers from 0 to 6 except 3 and 6 for x in range(6): if (x == 3 or x==6): continue print(x,end=' ') print("\n") # Write a Python program to get the Fibonacci series between 0 to 50. x,y=0,1 while y<50: print(y) x,y = y,x+y # Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i* row_num = int(input("Input number of rows: ")) col_num = int(input("Input number of columns: ")) multi_list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): multi_list[row][col]= row*col print(multi_list) # Write a Python program to find numbers between 100 and 400 (both included) where each digit of a number is an even number. The numbers obtained should be printed in a comma-separated sequence items = [] for i in range(100, 401): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0): items.append(s) print( ",".join(items # Write a Python program to create the multiplication table (from 1 to 10) of a number. n = int(input("Input a number: ")) for i in range(1,11): print(n,'x',i,'=',n*i) # Write a Python function to find the Max of three numbers. def max_of_two( x, y ): if x > y: return x return y def max_of_three( x, y, z ): return max_of_two( x, max_of_two( y, z ) ) print(max_of_three(3, 6, -5)) # Write a Python function to sum all the numbers in a list def sum(numbers): total = 0 for x in numbers: total += x return total print(sum((8, 2, 3, 0, 7))) # Write a Python function to multiply all the numbers in a list def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8, 2, 3, -1, 7))) # 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 characters : ", d["UPPER_CASE"]) print ("No. of Lower case Characters : ", d["LOWER_CASE"]) string_test('The quick Brow Fox') # Write a Python function that takes a list and returns a new list with unique elements of the first list def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x print(unique_list([1,2,3,3,3,3,4,5])) # Write a Python program to print the even numbers from a given list def is_even_num(l): enum = [] for n in l: if n % 2 == 0: enum.append(n) return enum print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) # 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 program to access a function inside a function def test(a): def add(b): nonlocal a a += 1 return a+b return add func= test(4) print(func(4)) # Write a Python program to detect the number of local variables declared in a function. def abc(): x = 1 y = 2 str1= "w3resource" print(abc.__code__.co_nlocals) # Write a Python program to check number either positive , negative or zero num = int (input ("Enter Integer Number: ")) if num == 0: print ("Zero Entered") elif num > 0: print ("Positive Number Entered") elif num < 0: print ("Negative Number Entered") # Write a Python program to Check Divisibility of 2 numbers nominator = int (input ("Enter Nominator: ")) denominator = int (input ("Enter Denominator: ")) if nominator % denominator == 0: print("{} is completely Divisible by {}".format(nominator, denominator)) else: print ("{} is not completely Divisible by {}".format(nominator, denominator)) # Write a python program to check whether Entered caharacter is Vowel or not letter = input ("Enter a Single Character: ") if letter == "A" or letter == "a" or letter == "E" or letter == "e" or letter == "I" or letter == "i" or letter == "o" or letter =="O" or letter == "U" or letter == "u": print ("{} is Vowel".format(letter)) else: print ("{} is co nsonent (Not Vowel)".format(letter)) # Write a python program to Sum of n positive Integer n = int (input ("Enter Value of n: ")) sum = 0 x = 0 while x != n+1: #because we need to include n in sum sum += x x+=1 print("Sum of n positive Integer till {} is {}".format(n,sum)) # Write a python program to digit sum of a number Digits = input("Enter a number: ") sum = int(Digits[0]) number = Digits[0] for i in Digits[1::]: sum+= int(i) number +=" + {}".format(i) print("Sum of {} is {}".format(number,sum)) # Write a python program to convert decimal to binary Decimal = input("Enter Number: ") num = int(Decimal) Binary ="" while num>=1: i = num%2 num = num//2 Binary +=str(i) print ("Binary Equivalent of {} is {}".format(Decimal,Binary[::-1])) # Write a python program to Count Numbers, Alphabets, and Special Character Text = input ("Enter Text: ") letter, number, spaces , special = 0,0,0,0 for i in Text: if i.isalpha(): letter+=1 elif i.isspace(): spaces +=1 elif i.isnumeric(): number +=1 else: special+=1 print(" Alphabets = {} \n Numbers = {} \n Space = {} \n Special Chracter = {}".format(letter,number,spaces,special)) # Write a python class Shape and Sub class Square: class Shape(): def __init__(self,length = 0): self.length = length def Area(self): print("Area of Shape is 0") class Square (Shape): def __init__(self,length = 0): self.length = length def Area(self): self.area = self.length*self.length print("Area of a Square is: {}".format(self.area)) s1 = Square(2) s1.Area() # Write a python function to compute 5/0 using try except try: print("Division = {}".format(5/0)) except ZeroDivisionError: print ("5 cannot be divided by O") # Write a python program to Accept the String and print the words composed of digits only Text = input ("Enter Text: ") Digits = "" for i in Text: if i.isnumeric(): Digits +=i+" " print("Digits used in given strings are: {}".format(Digits)) # Write a python program to program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). num = int (input ("Enter Number: ")) sum = 0 for i in range(num+1): sum += float(i/(i+1)) print ("Sum: {:.2f}".format(sum)) # Write a python program to program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 def f(n): if n == 0 : return 0 else: return f(n-1)+100 n = int(input("Enter Number: ")) print("f(n-1)+100 = ", f(n)) # Write a python function Password match the required criteria: def PasswordMatchCriteria(pas): upper,lower,special,num = 0,0,0,0 for x in pas: if (len(pas) >= 6) and (len(pas) <=12): if x.isupper(): upper+=1 elif x.islower(): lower+=1 elif x.isnumeric(): num +=1 elif x.isspace(): j = 0 else: special += 1 if (upper > 0) and (lower > 0) and (special > 0) and (num > 0): return True else: False passwords = input("Enter Passwords which are seperated by \",\": ") password = passwords.split(",") for i in password: if PasswordMatchCriteria(i): print(i) # Write a python program to define a function with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. def Generator(n): for i in range(n+1): if i%7 == 0: yield i n = int(input("Enter Number: ")) for i in Generator(n): print(i,end = " ") # Write a python program to make a recursive function to get the sum def rec(n): if n == 0: return n return rec(n-1) + n n = int(input()) sum = rec(n) print(sum) # Write a python program to count the frequency of letters of the string and print the letters in descending order of frequency. word = input() dct = {} for i in word: dct[i] = dct.get(i,0) + 1 dct = sorted(dct.items(),key=lambda x: (-x[1],x[0])) for i in dct: print(i[0],i[1] # Write a python program using lambda funtion to square a number square2 = lambda num: num * num # Write a python program to uppercase strings using lambda and map people = ["Darcy", "Christina", "Diana"] peeps = list(map(lambda name: name.upper(), people)) print(peeps) # Write a python program to filter names not starting with "a" names = ['austin', 'penny', 'anthony', 'rihana', 'billy', 'angel'] a_names = list(filter(lambda name: name[0] == 'a', names)) print(a_names) # Write a python program to return dict with {student:highest score} USING MAP+LAMBDA midterms = [80, 91, 78] finals = [98, 89, 53] students = ['dan', 'ang', 'kate'] final_grades = dict(zip(students,map(lambda pair: max(pair),zip(midterms, finals)))) # Write a python function to sum variable number of arguments def sum_all(*args): total = 0 for num in args: total += num return total # Write a python program using kwargs def fav_colors(**kwargs): ''' kwargs comes as a dictionary ''' print(kwargs) for person, color in kwargs.items(): print(f"{person}'s favorite color is {color}") fav_colors(sriju="red", faizu="yellow", kabir="black") # Write a python program to print even length words in a string def printWords(s): s = s.split(' ') for word in s: if len(word)%2==0: print(word) s = "This is a python language" printWords(s) # Write a python program which can compute the factorial of a given number. ef fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print (fact(x)) # Write a python program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line. alues = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print (",".join(values)) # Write a python program that accepts a sentence and calculate the number of letters and digits. s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print ("LETTERS", d["LETTERS"]) print ("DIGITS", d["DIGITS"]) # Write a python program using a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print (",".join(numbers)) # Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. def putNumbers(n): i = 0 while i=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) # Write a python program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print(li) # Write a python program for selection sort for i in range(len(A)): min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j A[i], A[min_idx] = A[min_idx], A[i] # Write a python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) # Write a python program to check if a number is an Armstrong number. n=int(input("Enter any number: ")) a=list(map(int,str(n))) b=list(map(lambda x:x**3,a)) if(sum(b)==n): print("The number is an armstrong number. ") else: print("The number isn't an arsmtrong number. ") # Write a python program to check if a number is a Perfect number. n = int(input("Enter any number: ")) sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): print("The number is a Perfect number!") else: print("The number is not a Perfect number!") # Write a python program to Check if a Number is a Strong Number sum1=0 num=int(input("Enter a number:")) temp=num while(num): i=1 f=1 r=num%10 while(i<=r): f=f*i i=i+1 sum1=sum1+f num=num//10 if(sum1==temp): print("The number is a strong number") else: print("The number is not a strong number") # Write a python to find LCM of two numbers a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) if(a>b): min1=a else: min1=b while(1): if(min1%a==0 and min1%b==0): print("LCM is:",min1) break min1=min1+1 # Write python program to find whether-number-power-two def is_power_of_two(n): """Return True if n is a power of two.""" if n <= 0: return False else: return n & (n - 1) == 0 n = int(input('Enter a number: ')) if is_power_of_two(n): print('{} is a power of two.'.format(n)) else: print('{} is not a power of two.'.format(n)) #Write a python program to find length of list using recursion def length(lst): if not lst: return 0 return 1 + length(lst[1::2]) + length(lst[2::2]) a=[1,2,3] print("Length of the string is: ") print(a) # write a python program to shuffle the items in a list and print it from random import shuffle mylist = [1, 2, 3, 4, 5] shuffle(mylist) print(mylist) # write a python program that adds the elements of a list to a set and prints the set my_set = {1, 2, 3} my_list = [4, 5, 6] my_set.update(my_list) print(my_set) # write a python program that prints the circumference of a circle import math radius = 10 print(f'Area: {2 * math.pi * radius}') # write a python program that prints the area of a rectangle length = 10 width = 5 print(f'Area: {length * width}') # write a python program that prints the area of a square side = 5 print(f'Area: {side * side}') # write a python program to create a dictionary with numbers 1 to 5 as keys and the numbers in english as values number_dict = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' } # write a python program to remove words less than a specified length from a sentence sentence = 'this is my sentence and i will write it my way' minlength = 3 result = [word for word in sentence.split(' ') if len(word) >= minlength] # write a python program to keep words less than a specified length in a sentence sentence = 'this is my sentence and i will write it my way' maxlength = 3 result = [word for word in sentence.split(' ') if len(word) <= minlength] #### 93 # write a python function that takes a list as an input and converts all numbers to positive numbers and returns the new list def make_all_positive(nums): return [num if num > 0 else -num for num in nums] # write a python function that takes a list as an input and converts all numbers to negative numbers and returns the new list def make_all_negative(nums): return [num if num < 0 else -num for num in nums] # write a python function to return a set of all punctuation used in a string def get_punctuations(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' used_punctuation = set() for char in sentence: if char in punctuations: used_punctuation.add(char) return used_punctuation # write a python program to print the words in a sentence in reverse order sentence = 'the quick brown fox' words = sentence.split(' ') words.reverse() print(' '.join(words)) # write a python program to replace each word in a sentence with the length of the word and print it sentence = 'the quick brown fox jumps over the lazy dog' words = sentence.split(' ') lengths = [str(len(word)) for word in words] print(' '.join(lengths)) # write a python program to convert a set to a list myset = {1, 2, 4, 7} mylist = list(myset) # write a python program to convert a list to a dictionary where the key is the index and the value is the item in the list my_list = [1, 8, 1, 2, 2, 9] my_dict = {key: value for key, value in enumerate(my_list)} # write a python function that returns True if the sum of two provided numbers is even def is_prod_even(num1, num2): sum = num1 + num2 return not sum % 2 # write a python program to print the first 5 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[:5]) # write a python program to print the last 3 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[-3:]) # write a python program to subtract two numbers and print it num1 = 1.5 num2 = 6.3 difference = num1 - num2 print(f'Difference: {difference}') # write a python program to print 5 random integers between 10 and 20 import random print(random.sample(range(10, 20), 5)) # write a python program to delete a variable i = 10 del i # write a python program to perform multiple assignments a = b = c = 1 # write a python program to swap two numbers (x, y) = (1, 2) print(f'Before swapping: x: {x}, y: {y}') (y, x) = (x, y) print(f'After swapping: x: {x}, y: {y}') # write a python program to print bitwise AND operation a = 60 b = 13 a_and_b = a&b print(a_and_b) # write a python program to print bitwise OR operation a = 60 b = 13 a_or_b = a|b print(a_or_b) # write a python program to print bitwise XOR operation a = 60 b = 13 a_xor_b = a^b print(a_xor_b) # write a python program to print binary ones complement on a variable a = 60 ones_complement_a = ~a print(ones_complement_a) # write a python program to print binary left shift on a variable a = 60 binary_left_shift = a<<2 print(binary_left_shift) # write a python program to print binary right shift on a variable a = 60 binary_right_shift = a>>2 print(binary_right_shift) # write a python function to check if an item exists in a list and return the boolean value def item_exists(lst, item): if item in lst: return True else: return False # write a python function to get the type of a variable def get_type(var): return(type(var)) # write a python function to check if an object is an instance of a given class def check_instance(derived_class, base_class): return(isinstance(derived_class, base_class)) # write a python function to accept user input to continue def get_userinput(): while(1): do_continue = raw_input('Do you want to continue(y/n)?') if do_continue == 'y' or do_continue == 'n': return do_continue # write a python program to create a raw string str1 = r'hello\n' # write a python function to print prime numbers between two numbers def get_prime_numbers(range1, range2): for num in range(range1,range2): for i in range(2,num): if num%i == 0: j=num/i break else: print(num, 'is a prime number') # write a python function to get the value of maximum integer allowed on the system def get_max_integer(): import sys return sys.maxsize # write a python function to get the absolute value of a number def get_absolute_value(i): return(abs(i)) # write a python function to return the exponential of a number def get_exponential_value(i): import math return(math.exp(i)) # write a python function to return the natural logarithm of a number def get_natural_log_value(i): import math return(math.log(i)) # write a python function to return the base 10 logarithm of a number def get_natural_log_value(i): import math return(math.log10(i)) # write a python function to return the square root of a number def get_sqrt(i): import math return(math.sqrt(i)) # write a python program to print the maximum integer in a list of integers lst = [23, 10, 55, 43] lst.sort() max = lst[-1] # write a python program to print the minimum integer in a list of integers lst = [23, 10, 55, 43] lst.sort() min = lst[0] # write a python program to print a random number between 0 and 1 import random print(random.uniform(0, 1)) # write a python program to concatenate two strings and print str1 = 'hello' str2 = ' world!' print(str1 + str2) # write a python program to print the ascii value of a character str1 = 'a' print(ord(str1)) # write a python program to print current date and time import datetime print(datetime.datetime.now()) # write a python program to capitalize a string str1 = 'hello' print(str1.capitalize()) # write a python program to clone a list a = [1, 2, 3] b = a[:] # write a python program to print a list in reverse a = [1, 2, 3] print(a[::-1]) # write a python program to print a list in sorted order basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] print(sorted(basket)) # write a python function to return union of two sets def union_set(set1, set2): return set1|set2 # write a python program to print a set of all elements in either set1 or set2, but not both set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.symmetric_difference(set2)) # write a python program to print names of the entries in the directory given by path path = '/home' import os print(os.listdir(path)) # write a python program to create a directory named path path = 'test' import os os.mkdir(path) # write a python program to add two matrices and print them X = [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] result = [[X[i][j] + Y[i][j] for j in range (len(X[0]))] for i in range(len(X))] for r in result: print(r) # write a python function to check if a string is a palindrome or not def isPalindrome(s): return s == s[::-1] # write a python program to print the least frequent character in a string test_str = "this is test string" all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 res = min(all_freq, key = all_freq.get) print(res) # write a python program to print sum of elements in a list lst = range(5) print(sum(lst)) # write python code to merge two dictionaries def merge_dict(dict1, dict2): return(dict2.update(dict1)) dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} merge_dict(dict1, dict2) print(dict2) # write python code to print temperature in celsius to fahrenheit celsius = 37.5 fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) # write python function to detect if a number is even number def is_even(num): return((num % 2) == 0) # write python function to detect if a number is odd number def is_odd(num): return((num % 2) != 0) # write python function to detect if an year is leap year def is_leap_year(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False # write a python program to print the largest number among the three input numbers num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is", largest) # write a python program to find the factorial of a number provided by the user. num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) # write a python program to display the Fibonacci sequence up to n-th term nterms = int(input("How many terms? ")) n1, n2 = 0, 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1 # write a python program to print transpose a matrix and print X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) # write a python program to convert Kilometers to Miles kilometers = float(input("Enter value in kilometers: ")) conv_fac = 0.621371 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) # write a python program to check if a number is positive, negative or 0 num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # write a python program to check if a number is a prime number num = int(input("Enter a number: ")) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") # write a python function to find H.C.F of two numbers def compute_hcf(x, y): if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf # write a python python program to find the L.C.M. of two input number def compute_lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) # write a python function to find the factors of a number def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) # write a python program to remove punctuations from a string and print it punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = input("Enter a string: ") no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char print(no_punct) # write a python program to count the number of each vowel and print them vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' ip_str = ip_str.casefold() count = {}.fromkeys(vowels,0) for char in ip_str: if char in count: count[char] += 1 print(count) # write a python program to print week number from a date import datetime print(datetime.date(2015, 6, 16).isocalendar()[1]) from datetime import date, timedelta def all_sundays(year): dt = date(year, 1, 1) dt += timedelta(days = 6 - dt.weekday()) while dt.year == year: yield dt dt += timedelta(days = 7) for s in all_sundays(2020): print(s) # Write a Python program to get the last day of a specified year and month. import calendar year = 2020 month = 12 print(calendar.monthrange(year, month)[1]) # Write a Python program to convert a string to datetime. from datetime import datetime date_object = datetime.strptime('Jul 1 2014 2:43PM', '%b %d %Y %I:%M%p') print(date_object) # Write a Python program to subtract five days from current date from datetime import date, timedelta dt = date.today() - timedelta(5) print('Current Date :',date.today()) print('5 days before Current Date :',dt) # Write a Python program to convert Year/Month/Day to Day of Year. import datetime today = datetime.datetime.now() day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1 print(day_of_year) # Write a program to split strings using split function. string = "India is my country." string_list = string.split(' ') print(string_list) # write a Python program to multiply two numbers and print it num1 = 1.5 num2 = 6.3 product = num1 * num2 print(f'product: {product}') # Write a Python program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. #import datetime import datetime #asking name name = input('Type your name:') #asking age age = input('Type your age:') #get the current year now = datetime.datetime.now() #get difference between age x 100 years diff = 100 - int(age) #show exactly year that user will turn 100 years old print('Hi '+name+" you will complete 100 years in ",(now.year+diff)) # Write a Python program that asks the user to enter a number and Depending on whether the number is even or odd, print out an appropriate message to the user. number = int(input("Number: ")) if number%2 == 0 and number%4 != 0: print("Your number is even...") elif number%4 == 0: print("Your number is a multiple of 4") else: print("Your number is odd...") # Write a Python program to check and print whether a triangle is valid or not def triangle_check(l1,l2,l3): if (l1>l2+l3) or (l2>l1+l3) or (l3>l1+l2): print('No, the lengths wont form a triangle') elif (l1==l2+l3) or (l2==l1+l3) or (l3==l1+l2): print('yes, it can form a degenerated triangle') else: print('Yes, a triangle can be formed out of it') length1 = int(input('enter side 1\n')) length2 = int(input('enter side 2\n')) length3 = int(input('enter side 3\n')) triangle_check(length1,length2,length3) # Write a Python program that accepts a string and calculate the number of digits and letters and print them x = input("Enter a string! ") d=l=0 for c in x: if c.isdigit(): d = d + 1 elif c.isalpha(): l = l + 1 else: pass print("Letters: ", l) print("Digits: ", d) # write a Python program to count the number of even and odd numbers from a series of numbers and print the result x = (1, 2, 3, 4, 5, 6, 7, 8, 9) odd = even = 0 for i in x: if i % 2 == 0: even = even + 1 else: odd = odd + 1 print("Even Numbers are: ", even) print("Odd Numbers are: ", odd) # Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 and print the result. nl = [] for x in range(1500, 2700): if (x%7==0) and (x%5==0): nl.append(str(x)) print("\n".join(nl)) # Write a python program to generate a random number between 1 and 9 (including 1 and 9) and Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. import random import math x = math.floor((random.random() * 10) + 1) guess=0 while guess != x: guess = int(input("Guess a number: ")) if(guess == x): print("you got It!") print("Number is ", x) break elif(guess>x): print("You Guesses too high!") else: print("You guessed too low!") # Write a Python program to check a triangle is equilateral, isosceles or scalene.# Note :# An equilateral triangle is a triangle in which all three sides are equal.# A scalene triangle is a triangle that has three unequal sides.# An isosceles triangle is a triangle with (at least) two equal sides. print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x != y != z: print("Scalene triangle") else: print("isosceles triangle") # Write a Python program to check whether an alphabet is a vowel or consonant l = input("Input a letter of the alphabet: ") if l in ('a', 'e', 'i', 'o', 'u'): print("%s is a vowel." % l) elif l == 'y': print("Sometimes letter y stand for vowel, sometimes stand for consonant.") else: print("%s is a consonant." % l) # Write a python program to Convert a list of characters into a string and print it : Example : # Input ['a', 'b', 'c', 'd']# Output abcd s = ['a','b','c','d'] x = "".join(s) print(x) # Write a Python program to check whether a list contains a sublist and print True or False. def is_Sublist(l, s): sub_set = False if s == []: sub_set = True elif s == l: sub_set = True elif len(s) > len(l): sub_set = False else: for i in range(len(l)): if l[i] == s[0]: n = 1 while (n < len(s)) and (l[i+n] == s[n]): n += 1 if n == len(s): sub_set = True return sub_set a = [2,4,3,5,7] b = [4,3] c = [3,7] print(is_Sublist(a, b)) print(is_Sublist(a, c)) # Write a Python program to find common items from two lists. Example: # input# color1 = "Red", "Green", "Orange", "White"# color2 = "Black", "Green", "White", "Pink"# output# {'Green', 'White'} color1 = "Red", "Green", "Orange", "White" color2 = "Black", "Green", "White", "Pink" print(set(color1) & set(color2)) # Write a Python program to Calculate the sum of the digits of a random three-digit number and print the result. import random n = random() * 900 + 100 n = int(n) print(n) a = n // 100 b = (n // 10) % 10 c = n % 10 print(a + b + c) #Write a Python program to find the area and perimeter of a right-angled triangle and print the perimeter and area. import math AB = input("Length of the first leg: ") AC = input("Length of the second leg: ") AB = float(AB) AC = float(AC) BC = math.sqrt(AB 2 + AC 2) S = (AB * AC) / 2 P = AB + AC + BC print("Area of the triangle: %.2f" % S) print("Perimeter of the triangle: %.2f" % P) # Write a Python program to find the greatest common divisor (GCD)(Euclidean algorithm) and print the result. a = int(input()) b = int(input()) while a != 0 and b != 0: if a > b: a %= b else: b %= a gcd = a + b print(gcd) # Write a Python program to select integers from a string and print those integers s = input() l = len(s) i = 0 while i < l: num = '' symbol = s[i] while symbol.isdigit(): num += symbol i += 1 if i < l: symbol = s[i] else: break if num != '': print(num) i += 1 # Write a program to Expand and print a string like "a-z" #Example: enter first string :b # enter last string: e #Output : bcde first = input("The first: ") last = input("The last: ") while first <= last: print(first, end='') first = chr(ord(first) + 1) print() # Write a Python function that returns the values of the largest and second largest elements in the passed list. def max2(x): if x[0] > x[1]: m1,m2 = (x[0],x[1]) else: m1,m2 = (x[1],x[0]) for i in range(2, len(x)): if x[i] > m1: m2 = m1 m1 = x[i] elif x[i] > m2: m2 = x[i] return m1,m2 # Write a Python program to print the frequency of the elements in a list.Example:# input# my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]# output# {10: 4, 20: 4, 40: 2, 50: 2, 30: 1} import collections my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30] print("Original List : ",my_list) ctr = collections.Counter(my_list) print("Frequency of the elements in the List : ",ctr) # Write a Python program to generate all permutations of a list in Python. Example:# Input [1,2,3]# Output [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] import itertools print(list(itertools.permutations([1,2,3]))) # Write a Python program to remove duplicates from a list.Example:# Input a = [10,20,30,20,10,50,60,40,80,50,40]# Output [10, 20, 30, 50, 60, 40, 80] a = [10,20,30,20,10,50,60,40,80,50,40] dup_items = set() uniq_items = [] for x in a: if x not in dup_items: uniq_items.append(x) dup_items.add(x) print(uniq_items) # Write a Python function to return the second smallest number in a list and print it.Example:# input# second_smallest([1, 2, -8, -2, 0])# output# -2 def second_smallest(numbers): a1, a2 = float('inf'), float('inf') for x in numbers: if x <= a1: a1, a2 = x, a1 elif x < a2: a2 = x return a2 print(second_smallest([1, 2, -8, -2, 0])) # Write a python program to determine the percentage of lowercase and uppercase letters in a string. string = input() length = len(string) lower = upper = 0 for i in string: if i.islower(): lower += 1 elif i.isupper(): upper += 1 per_lower = lower / length * 100 per_upper = upper / length * 100 print("Lower: %.2f%%" % per_lower) print("Upper: %.2f%%" % per_upper) # Write a Python program to Separate positive numbers from negative and print the positive numbers and negative numbers separately from random import random a = [] for i in range(7): n = int(random() * 20) - 10 a.append(n) print(a) neg = [] pos = [] for i in a: if i < 0: neg.append(i) elif i > 0: pos.append(i) print(neg) print(pos) # Write a python program to swap cases in a string and print. In other words, convert all lowercase letters to uppercase letters and vice versa and print the result #Example:input:InDiAaa #Output: iNdIaAA s = input() print(s.swapcase()) # Write a python program to implement bubble sort and print the result from random import randint N = 7 a = [] for i in range(N): a.append(randint(1, 20)) print(a) for i in range(N-1): for j in range(N-i-1): if a[j] > a[j+1]: b = a[j] a[j] = a[j+1] a[j+1] = b print(a) # Write a python program to find whether a given number is perfect or not and print the result in boolean format(True or False) x = int(input("Enter any no. ")) def perfect_number(n): sum = 0 for x in range(1, n): if n % x == 0: sum += x return sum == n print(perfect_number(x)) # Write a python program to find and print the longest word in a sentence string = "python java c c++ javascript pascal php" print(string) words = string.split() id_longest = 0 for i in range(1, len(words)): if len(words[id_longest]) < len(words[i]): id_longest = i print(words[id_longest]) # Write a python program to print all the values in a dictionary. d = {'a':1,'b':2,'c':3,'d':4} print(d.values()) # Write a python program to print all the keys in a dictionary. d = {'a':1,'b':2,'c':3,'d':4} print(d.keys()) # Write a python program to print a given string without spaces s = "I love India now I will be printed without any space" for i in s: if i==' ': continue print(i,end='') # Write a python program to print only upto the letter 't' in a given string. s = "hi i love python" i=0 while s[i]!='t': print(s[i],end='') i+=1 # Write a python program to print the length of a given string. sample_str = "Python is good for datascience" print(len(sample_str)) # Write a python program to turn every item of a list into its square. sample_list = [1, 2, 3, 4, 5, 6, 7] square_list = [x * x for x in sample_list] print(square_list) # Write a python program to print a new set with all items from both sets by removing duplicates set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.union(set2)) # write a list comprehension in python to get a list of even numbers when a range is given N = 20 number_list = [ x for x in range(N) if x % 2 == 0] print(f'List of Even Numbers:', number_list) # write a list comprehension in python to get a list of odd numbers when a range is given N = 20 number_list = [ x for x in range(N) if x % 2 != 0] print(f'List of Odd Numbers:', number_list) # write a python function to display the Fibonacci series def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # write a python lambda function to get remainder when divisor and divident are given remainder = lambda Divident, Divisor: Divident % Divisor print(remainder(5,2)) # write a python function to print whether the given year is a leap year or not def leapYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) # write a python function to convert degree celsius to degree fahrenheit def fahrenheit(celsius): return (celsius * 1.8) + 32 # write a python function to convert degree fahrenheit to degree celsius def celsius(fahrenheit): return (fahrenheit - 32) / 1.8 # write a python function to get the factorial of a given number def factorial(n): if n == 1: return n else: return n*factorial(n-1) # write a python function to compute the HCF of two numbers def hcf(x, y): if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf # write a python function to compute the lcm of two numbers def lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # write a python function to check whether the number is an Armstrong number or not def Armstrong(num): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") # write a python function to check whether the string is a palindrome or not def palindrome(my_str): my_str = my_str.casefold() rev_str = reversed(my_str) if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") # write a python program to remove punctuations in a string punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' string = ''.join(e for e in d if e not in punctuations) # write a python program to print the ASCII value of a character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) # write a python program to swap two numbers a = 1 b = 2 a, b = b, a # write a python lambda function to add three numbers x = lambda a, b, c : a + b + c print(x(5, 6, 2)) # write a python function to check whether the number is a Magic number or not def isMagic(n): sum = 0 while (n > 0 or sum > 9): if (n == 0): n = sum; sum = 0; sum = sum + n % 10; n = int(n / 10); return True if (sum == 1) else False; # write a python program to convert a list of values in kilometers to feet kilometer = [39.2, 36.5, 37.3, 37.8] feet = map(lambda x: float(3280.8399)*x, kilometer) print(list(feet)) # write a python list comprehension to flatten a list of lists list_of_list = [[1,2,3],[4,5,6],[7,8]]` flatten = [y for x in list_of_list for y in x] # write a python list comprehension to transpose a 2D matrix (provided as list) matrix = [[1,2,3],[4,5,6],[7,8,9]] matrixT = [[row[i] for row in matrix] for i in range(len(matrix[0]))] # write a python list comprehension to print numbers in a given string string = "Hello 12345 World" numbers = [x for x in string if x.isdigit()] print (numbers) # write a python function for binary search def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) else: return -1 # write a python function to bubblesort an array def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # write a python program to do selection sort A = [64, 25, 12, 22, 11] for i in range(len(A)): min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j A[i], A[min_idx] = A[min_idx], A[i] print ("Sorted array") for i in range(len(A)): print("%d" %A[i]) # write a python function to do insertion sort def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # write a python program to print prime numbers within a range lower = 5 upper = 20 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # write a python program to check whether the number is prime num = 407 if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") # write a python function to linearly search an array for a given number and return its index else return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # write a python function to check whether the number is a lucky number def isLucky(n): isLucky.counter = 2 next_position = n if isLucky.counter > n: return 1 if n % isLucky.counter == 0: return 0 next_position = next_position - next_position /isLucky.counter isLucky.counter = isLucky.counter + 1 return isLucky(next_position) # write a python function to obtain the square root of a number def squareRoot(n): x = n y = 1 e = 0.000001 while(x - y > e): x = (x + y)/2 y = n / x return x # write a python function to convert a number from decimal to binary def decToBinary(n): binaryNum = [0] * n; i = 0; while (n > 0): binaryNum[i] = n % 2; n = int(n / 2); i += 1; for j in range(i - 1, -1, -1): print(binaryNum[j], end = ""); # write a python function to convert a number from binary to decimal def binaryToDecimal(n): num = n; dec_value = 0; base = 1; temp = num; while(temp): last_digit = temp % 10; temp = int(temp / 10); dec_value += last_digit * base; base = base * 2; return dec_value; # write a python function to convert a number from decimal to octal def decToOctal(n): octalNum = [0] * 100 i = 0 while (n != 0): octalNum[i] = n % 8 n = int(n / 8) i += 1 for j in range(i - 1, -1, -1): print(octalNum[j], end="") # write a python function to convert a number from octal to decimal def octalToDecimal(n): num = n; dec_value = 0; base = 1; temp = num; while (temp): last_digit = temp % 10; temp = int(temp / 10); dec_value += last_digit * base; base = base * 8; return dec_value; # write a dictionary comprehension in python so that the values are square of the key number square_dict = {num: num*num for num in range(1, 11)} print(square_dict) # write a python program to get indexes for each element in a list using enumerate l1 = ["eat","sleep","repeat"] for ele in enumerate(l1): print (ele) # write a python program to get indexes starting at a specified number for each element in a list using enumerate l1 = ["eat","sleep","repeat"] for count,ele in enumerate(l1,100): print (count,ele ) # write a python program to demonstarate working of map def addition(n): return n + n numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) # write a python function to calculate simple interest def simple_interest(p,t,r): si = (p * t * r)/100 return si # write a python function to calculate compound interest def compound_interest(principle, rate, time): Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle print("Compound interest is", CI) # write a python function to convert a list of characters to a string def convert(s): str1 = "" return(str1.join(s)) # write a python function to check whether a number is perfect def isPerfect( n ): sum = 1 i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n/i i += 1 return (True if sum == n and n!=1 else False) # write a python function to find the sum of digits in a number until one digit (no more than one digit) def digSum(n): sum = 0 while(n > 0 or sum > 9): if(n == 0): n = sum sum = 0 sum += n % 10 n = int(n/10) return sum # write a python function to get the sum of numbers in a given digit def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum # write a python function to find the largest number in an array def largest(arr,n): max = arr[0] for i in range(1, n): if arr[i] > max: max = arr[i] return max # write a python function to find the nth catalan number def catalan(n): if n <= 1: return 1 res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # write a python function to convert decimal to hexadecimal def decToHexa(n): hexaDeciNum = ['0'] * 100; i = 0; while(n != 0): temp = 0; temp = n % 16; if(temp < 10): hexaDeciNum[i] = chr(temp + 48); i = i + 1; else: hexaDeciNum[i] = chr(temp + 55); i = i + 1; n = int(n / 16); j = i - 1; while(j >= 0): print((hexaDeciNum[j]), end = ""); j = j - 1; # write a python program to convert hexadecimal to decimal def hexadecimalToDecimal(hexval): length = len(hexval) base = 1 dec_val = 0 for i in range(length - 1, -1, -1): if hexval[i] >= '0' and hexval[i] <= '9': dec_val += (ord(hexval[i]) - 48) * base base = base * 16 elif hexval[i] >= 'A' and hexval[i] <= 'F': dec_val += (ord(hexval[i]) - 55) * base base = base * 16 return dec_val # write a python program to add two hexadecimal numbers a = "B" b = "C" sum = hex(int(a, 16) + int(b, 16)) print(sum[2:]) # write a python program to add two octal numbers a = "123" b = "456" sum = oct(int(a, 8) + int(b, 8)) print(sum[2:]) # write a python program to add two binary numbers a = "1101" b = "100" sum = bin(int(a, 2) + int(b, 2)) print(sum[2:]) # write s python program to print the union of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) # write s python program to print the intersection of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A & B) # write s python program to print the difference of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A - B) # write s python program to print the symmetric difference of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A ^ B) # write a python function to find nCr def nCr(n, r): def fact(n): res = 1 for i in range(2, n+1): res = res * i return res return (fact(n) / (fact(r) * fact(n - r))) # write a python function to calculate nPr def nPr(n, r): def fact(n): if (n <= 1): return 1 return n * fact(n - 1) return int(fact(n) / fact(n - r)) # write a python function to calculate the volume of ellipsoid def volumeOfEllipsoid(r1, r2, r3): return 1.33 * 22 * r1 * r2 * r3/7 # write a python function to calculate the area of tetraheadron def area_of_tetrahedron(side): return (1.73205 * (side * side)); # write a python function to find the volume of tetraheadron def vol_tetra(side): volume = (side ** 3 / (6 * 1.414)) return round(volume, 2) # write a python function to determing the volume of a cube whose space diagonal measure is given def CubeVolume(d): Volume = (1.73205 * pow(d, 3)) / 9 return Volume # write a python function to calcuate the easter date using Gauss's Algorithm def gaussEaster(Y): A = Y % 19 B = Y % 4 C = Y % 7 P = int(Y / 100) Q = int((13 + 8 * P) / 25) M = (15 - Q + P - P // 4) % 30 N = (4 + P - P // 4) % 7 D = (19 * A + M) % 30 E = (2 * B + 4 * C + 6 * D + N) % 7 days = (22 + D + E) if ((D == 29) and (E == 6)): print(Y, "-04-19") return elif ((D == 28) and (E == 6)): print(Y, "-04-18") return else: if (days > 31): print(Y, "-04-", (days - 31)) return else: print(Y, "-03-", days) return #write a python function to print the pascal's triangle def printPascal(n): for line in range(1, n + 1): C = 1; for i in range(1, line + 1): print(C, end = " "); C = int(C * (line - i) / i); print(""); #write a python function to print Hosoya's triangle of height 'n' def printHosoya(n): dp = [[0 for i in range(n)] for i in range(n)] dp[0][0] = dp[1][0] = dp[1][1] = 1 for i in range(2, n): for j in range(n): if (i > j): dp[i][j] = (dp[i - 1][j] + dp[i - 2][j]) else: dp[i][j] = (dp[i - 1][j - 1] + dp[i - 2][j - 2]) for i in range(n): for j in range(i + 1): print(dp[i][j], end = ' ') print() #write a python function to print Floyd's triangle def loydTriangle(n): val = 1 for i in range(1, n + 1): for j in range(1, i + 1): print(val, end = " ") val += 1 print("") #write a python function to print reverese Floyd's triangle def printReverseFloyd(n): curr_val = int(n*(n + 1)/2) for i in range(n + 1, 1, -1): for j in range(i, 1, -1): print(curr_val, end =" ") curr_val -= 1 print("") # write a python function to print fibonacci series in the reverse order def reverseFibonacci(n): a = [0] * n a[0] = 0 a[1] = 1 for i in range(2, n): a[i] = a[i - 2] + a[i - 1] for i in range(n - 1, -1 , -1): print(a[i],end=" ") # write a python function to print Leibniz Harmonic triangle def LeibnizHarmonicTriangle(n): C = [[0 for x in range(n + 1)] for y in range(n + 1)]; for i in range(0, n + 1): for j in range(0, min(i, n) + 1): if (j == 0 or j == i): C[i][j] = 1; else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]); for i in range(1, n + 1): for j in range(1, i + 1): print("1/", end = ""); print(i * C[i - 1][j - 1], end = " "); print(); # write a python function to check whether the given series is in Arithematic progression def checkIsAP(arr, n): if (n == 1): return True arr.sort() d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True # write a python function to check whether the given series is in harmonic progression def is_geometric(li): if len(li) <= 1: return True ratio = li[1]/float(li[0]) for i in range(1, len(li)): if li[i]/float(li[i-1]) != ratio: return False return True # write a python function to find the area of a circumscribed circle of an equilateral triangle def area_cicumscribed(a): return (a * a * (3.14159265 / 3)) # write a python function to find the side of a octogon inscribed in a square def octaside(a): if a < 0: return -1 s = a / (1.414 + 1) return s # write a python program to find the area of enneagon length = 6 Nonagon_area = 6.1818 * (length ** 2) print("Area of regular Nonagon is = ", Nonagon_area) # write a python function to find the day of the week given the date def dayofweek(d, m, y): t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] y -= m < 3 return (( y + int(y / 4) - int(y / 100) + int(y / 400) + t[m - 1] + d) % 7) # write a python function to calculate the MDAS factorial of a number def MDAS_Factorial( N ): if N <= 2: return N if N <= 4: return N + 3 if (N - 4) % 4 == 0: return N + 1 elif (N - 4) % 4 <= 2: return N + 2 else: return N - 1 # write a python function to find the nth pronic number def findRectNum(n): return n*(n + 1) #write a python function to find the sum of N pronic numbers def calculateSum(N): return (N * (N - 1) // 2 + N * (N - 1) * (2 * N - 1) // 6); #write a python function to find the sum of first N even numbers def evensum(n): curr = 2 sum = 0 i = 1 while i <= n: sum += curr curr += 2 i = i + 1 return sum # write a python function to check whether a number can be written as a sum of 3 primes (Goldbach Weak Coonjecture) def check(n): if n % 2 == 1 and n > 5: print('YES') else: print('NO') # write a python function to find the nth perrin number def per(n): if (n == 0): return 3; if (n == 1): return 0; if (n == 2): return 2; return per(n - 2) + per(n - 3); # write a python function to find the betrothed numbers smaller than n def BetrothedNumbers(n) : for num1 in range (1,n) : sum1 = 1 i = 2 while i * i <= num1 : if (num1 % i == 0) : sum1 = sum1 + i if (i * i != num1) : sum1 += num1 / i i =i + 1 if (sum1 > num1) : num2 = sum1 - 1 sum2 = 1 j = 2 while j * j <= num2 : if (num2 % j == 0) : sum2 += j if (j * j != num2) : sum2 += num2 / j j = j + 1 if (sum2 == num1+1) : print ('('+str(num1)+', '+str(num2)+')') # write a python function to implement linear extrapolation def extrapolate(d, x): y = (d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1])); return y; # write a python function to print the collatz sequence def printCollatz(n): while n != 1: print(n, end = ' ') if n & 1: n = 3 * n + 1 else: n = n // 2 print(n) # write a python function to print the newman-conway sequence def sequence(n): f = [0, 1, 1] print(f[1], end=" "), print(f[2], end=" "), for i in range(3,n+1): f.append( f[f[i - 1]] + f[i - f[i - 1]]) print(f[i], end=" "), #write a python function to find the nth term in a padovan's sequence # Function to calculate padovan number P(n) def padovan(n): pPrevPrev, pPrev, pCurr, pNext = 1, 1, 1, 1 for i in range(3, n+1): pNext = pPrevPrev + pPrev pPrevPrev = pPrev pPrev = pCurr pCurr = pNext return pNext; # write a python function to print the raceman sequence def recaman(n): arr = [0] * n arr[0] = 0 print(arr[0], end=", ") for i in range(1, n): curr = arr[i-1] - i for j in range(0, i): if ((arr[j] == curr) or curr < 0): curr = arr[i-1] + i break arr[i] = curr print(arr[i], end=", ") # write a python function to print the sylvester's sequence def printSequence(n) : a = 1 ans = 2 N = 1000000007 i = 1 while i <= n : print ans, ans = ((a % N) * (ans % N)) % N a = ans ans = (ans + 1) % N i = i + 1 # write a python function to find the sum of two numbers without using arithematic operators def Add(x, y): while (y != 0): carry = x & y x = x ^ y y = carry << 1 return x # write a python function to subtract two numbers without using arithemmatic operators def subtract(x, y): while (y != 0): borrow = (~x) & y x = x ^ y y = borrow << 1 return x # write a python function to find the smallest number to be subtracted from a given number to make the given number palindrome def minSub(N): count = 0 while (N >= 0): num = N rev = 0 while (num != 0): digit = num % 10 rev = (rev * 10) + digit num = num // 10 if (N == rev): break count += 1 N -= 1 print(count) # write a python function to check whether the number is a perfect square without finding square root def isPerfectSquare(n) : i = 1 while(i * i<= n): if ((n % i == 0) and (n / i == i)): return True i = i + 1 return False # write a python function to find the square root of a number using babylonian method def squareRoot(n): x = n y = 1 e = 0.000001 while(x - y > e): x = (x + y)/2 y = n / x return x # write a python function to convert bcd to decimal def bcdToDecimal(s): length = len(s); check = 0; check0 = 0; num = 0; sum = 0; mul = 1; rev = 0; for i in range(length - 1, -1, -1): sum += (ord(s[i]) - ord('0')) * mul; mul *= 2; check += 1; if (check == 4 or i == 0): if (sum == 0 and check0 == 0): num = 1; check0 = 1; else: num = num * 10 + sum; check = 0; sum = 0; mul = 1; while (num > 0): rev = rev * 10 + (num % 10); num //= 10; if (check0 == 1): return rev - 1; return rev; # write a python function to find all the sexy primes in a given range def sexyprime(l, r) : prime=[True] * (r + 1) p = 2 while(p * p <= r) : if (prime[p] == True) : for i in range( p * 2, r+1 ,p) : prime[i] = False p = p + 1 for i in range( l,r - 6 + 1) : if (prime[i] and prime[i + 6]) : print("(", i , ",", i + 6,")", end="") # write a python function to check whether the number is a duck number or not def check_duck(num) : n = len(num) i = 0 while (i < n and num[i] == '0') : i = i + 1 while (i < n) : if (num[i] == "0") : return True i = i + 1 return False # write a python function to check whether the given number is a Buzz number or not def isBuzz(num) : return (num % 10 == 7 or num % 7 == 0) # write a python function to check whether the number is a nude number or not def checkDivisbility(num): digit = 0 N = num while (num != 0): digit = num % 10 num = num // 10 if (digit == 0 or N % digit != 0): return False return True # write a python function to check whether the number is a ugly number or not def isUgly(n): if (n == 1): return 1 if (n <= 0): return 0 if (n % 2 == 0): return (isUgly(n // 2)) if (n % 3 == 0): return (isUgly(n // 3)) if (n % 5 == 0): return (isUgly(n // 5)) return 0 # write a python function to write a prime number as the sum of two composite numbers def findNums(n): if (n <= 11): if (n == 8): print("4 4", end = " ") if (n == 10): print("4 6", end = " ") else: print("-1", end = " ") if (n % 2 == 0): print("4 ", (n - 4), end = " ") else: print("9 ", n - 9, end = " ") # write a python function to print two composite numbers whose difference is N def find_composite_nos(n) : print(9 * n, 8 * n); # write a python function to print N-bonacci series def bonacciseries(n, m) : a = [0] * m a[n - 1] = 1 for i in range(n, m) : for j in range(i - n, i) : a[i] = a[i] + a[j] for i in range(0, m) : print (a[i], end = " ") # write a python function to return count of number of vowels in a sentence def count_vowels(sentence): count = 0 for letter in sentence: if letter in "aeiouAEIOU": count += 1 return count # write a python function to check if a given string is a palindrome def is_palindrome(string): return string == string[::-1] # write a program to print the nth fibonacci number n1 = 1 n2 = 1 n = 5 for _ in range(n): n1, n2 = n2, n1 + n2 print(n2) # write a function to return the square of first N numbers def get_squares(n): return [i*i for i in range(n)] # write a python function to return only even numbers in a list def filter_even(nums): return list(filter(lambda num: num % 2 == 0, nums)) # write a python function to return only odd numbers in a list def filter_odd(nums): return list(filter(lambda num: num % 2 == 1, nums)) # write a python program to calculate the sum of numbers using reduce and print it from functools import reduce nums = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50] total_sum = reduce(lambda a, b: a + b, nums) print(f'Sum: {total_sum}') # write a python program to print unique numbers in a list numbers = [1, 2, 2, 3, 4, 4, 5, 6] unique = set(numbers) print(f'Unique numbers: {list(unique)}') # write a python program to count how many times each letter occurs in a string string = 'The quick brown fox jumps over the lazy dog' countmap = {} for letter in string: if letter in countmap: countmap[letter] += 1 else: countmap[letter] = 1 print(f'Count of letters: {countmap}') # write a python function to repeat a given string n times def repeat_string(string, frequency): return string * frequency # write a program to capitalize the first letter of every word in a string and print it string = 'The quick brown fox jumps over the lazy dog' print(string.title()) # write a function that merges two dictionaries def merge_dictionaries(dict1, dict2): return {**dict1, **dict2} # write a program to merge two lists into a dictionary keys = [1, 2, 3] values = ['aye', 'bee', 'sea'] dictionary = dict(zip(keys, values)) # write a python function that inverts the key and values in a dict and returns it def invert_dict(dictionary): inverted_dict = {value: key for key, value in dictionary.items()} return inverted_dict # write a python program to print the difference in days between two dates from datetime import date date1 = date(2020, 10, 25) date2 = date(2020, 12, 25) print(f'Difference between dates: {(date2 - date1).days}') # write a python function that returns the weighted average of numbers def get_weighted_average(numbers, weightage): return sum(x * y for x, y in zip(numbers, weightage)) / sum(weightage) # write a python program to print if year is a leap year or not year = 2000 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) # write a python program to check and print if a number is prime num = 407 if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number") # write a python program to print all prime numbers in a given interval lower = 900 upper = 1000 for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # write a python function to return words in a sentence in sorted order def get_sorted_words(sentence): words = [word for word in sentence.split()] words.sort() return words # write a python function to remove all punctuation from a string def remove_punctuations(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct = '' for char in sentence: if char not in punctuations: no_punct = no_punct + char return no_punct # write a python function to return the nth fibonacci number def fib(n): if n <= 1: return n else: return (fib(n-1) + fib(n-2)) # write a python function to return the sum of first n numbers def sum_of_nums(n): if n <= 1: return n else: return n + sum_of_nums(n-1) # write a python function to return the factorial of a number def fact(n): if n == 1: return n else: return n * fact(n-1) # write a python program to print the factors of a number num = 320 for i in range(1, num + 1): if num % i == 0: print(i) # write a python function that returns the lcm of two numbers def lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # write a python function that returns the gcd of two numbers def gcd(x, y): if x > y: smaller = y else: smaller = x for i in range(1, smaller + 1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd # write a python program to print the ASCII value of a character character = 'x' print(f'The ASCII value of {character} is {ord(character)}') # write a python program to print the character of an ASCII value value = 65 print(f'The ASCII value {value} is of the character {chr(value)}') # write a python function to print the binary value of a decimal number def print_binary(dec): print(bin(dec)) # write a python function to print the octal value of a decimal number def print_octal(dec): print(oct(dec)) # write a python function to print the hexadecimal value of a decimal number def print_hexadecimal(dec): print(hex(dec)) # write a python program that prints the sum of natural numbers up to a given number num = 16 sum = 0 while (num > 0): sum += num num -= 1 print(f'The sum is {sum}') # write a python function to return the number of lines in a file def count_lines(filename): with open(filename, 'r') as f: contents = f.read().split('\n') return len(contents) # write a program to print the current date and time from datetime import datetime now = datetime.now() print(now) # write a python program to extract the file name and extension of a file import os filename, extension = os.path.splitext('/path/to/some/file.ext') # write a python program to merge two lists odd = [1, 3, 5, 7, 9] even = [2, 4, 6, 8, 10] odd.extend(even) # write a python program to print a random vowel import random vowels = ['a', 'e', 'i', 'o', 'u'] print(random.choice(vowels)) # write a python program to flip a coin 100 times and print number of heads and tails import random heads = 0 tails = 0 for i in range(100): if(random.choice([True, False])): heads += 1 else: tails += 1 print(f'{heads} heads, {tails} tails') # write a python program to print common elements in two lists list_a = [1, 2, 3, 4, 5, 6, 7] list_b = [2, 4, 6, 8, 10] print(f'Common elements: { set(list_a).intersection(set(list_b)) }') # write a python program to print squares of numbers until 20 for i in range(20): print(i*i) # write a python program to print the number of uppercase and lowercase letters in a string sentence = 'The Quick Brown Fox' lowercase = 0 uppercase = 0 for c in sentence: if c.isupper(): uppercase += 1 elif c.islower(): lowercase += 1 else: pass print(f'Lowercase: {lowercase}, Uppercase: {uppercase}') # write a python program to print the number of letters and digits in sentence sentence = 'The Quick 123 Fox' digits = 0 letters = 0 for c in sentence: if c.isdigit(): digits += 1 elif c.isalpha(): letters += 1 else: pass print(f'Digits: {digits}, Letters: {letters}') # write a python function to print a given string n times def printn(string, n): print(string * n) # write a python program that creates a dictionary whose keys are numbers from 1 to 10 and values are squares of the key square_dict = {} for i in range(1, 11): square_dict[i] = i*i # write a python class called Person that has a name property class Person: def __init__(self, name): self.name = name # write a python function that takes two strings as a parameter and prints the shorter one def print_shorter(str1, str2): if (len(str1) > len(str2)): print(str2) else: print(str1) # write a program to compute the count of each word in a sentence and print it word_freq = {} line = 'how many how words does this many have' for word in line.split(): word_freq[word] = word_freq.get(word, 0) + 1 print(word_freq) # write a python function that squares every number in a list using a list comprehension and returns the result def square_numbers(nums): return [i*i for i in nums] # write a python program that converts a binary number to decimal and prints it binary_num = '1010101' decimal_num = int(binary_num, 2) print(decimal_num) # write a python program that converts a octal number to octal and prints it octal_num = '17' decimal_num = int(octal_num, 8) print(decimal_num) # write a python program that converts a hexadecimal number to hexadecimal and prints it hexadecimal_num = 'FF' decimal_num = int(hexadecimal_num, 16) print(decimal_num) # write a python program that alphabetically sorts the words in a sentence and prints it sentence = 'the quick brown fox jumps' sorted_words = sentence.split(' ') sorted_words.sort() print(' '.join(sorted_words)) # write a python program that prints the area of a circle import math radius = 5 print(f'Area: {math.pi * radius * radius}') # write a python function that returns a dictionary with the area and perimeter of a rectangle def calculate_rect_properties(width, height): return { 'perimeter': 2 * (width + height), 'area': width * height } # write a python program that removes all blank spaces in a sentence and prints it sentence = 'the quick brown fox' print(sentence.replace(' ', '')) # write a python program that prints all characters at even indexes in a sentence sentence = 'the quick brown fox' print(sentence[::2]) # write a python program that prints every third character in a sentence sentence = 'the quick brown fox' print(sentence[::3]) # write a program to remove odd numbers from a list using list comprehensions nums = [1, 2, 3, 4, 5, 6, 7, 8] no_odd_nums = [i for i in nums if i % 2 == 0] # write a program to remove even numbers from a list using list comprehensions nums = [1, 2, 3, 4, 5, 6, 7, 8] no_even_nums = [i for i in nums if i % 2 == 1] # write a program to print 5 random numbers between 100 and 200 import random print(random.sample(range(100, 200), 5)) # write a program to print 5 even random numbers between 10 and 100 import random print(random.sample([i for i in range(10, 100) if i%2 == 0], 5)) # write a program to print 5 odd random numbers between 100 and 200 import random print(random.sample([i for i in range(10, 100) if i%2 == 1], 5)) # write a program to print 5 random numbers divisible by 4 between 100 and 200 import random print(random.sample([i for i in range(10, 100) if i%4 == 0], 5)) # write a program that adds corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] sum_list = [a+b for (a,b) in zip(list1, list2)] print(sum_list) # write a program that subtracts corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] diff_list = [a-b for (a,b) in zip(list1, list2)] print(diff_list) # write a program that multiplies corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] prod_list = [a*b for (a,b) in zip(list1, list2)] print(prod_list) # write a program that divides corresponding elements in two lists and prints a new list list1 = [1, 2, 3, 4, 5] list2 = [5, 4, 3, 2, 1] quot_list = [a/b for (a,b) in zip(list1, list2)] print(quot_list) # write a python program to print 5 random vowels import random vowels = ['a', 'e', 'i', 'o', 'u'] print([random.choice(vowels) for _ in range(5)]) # write a python program that creates a dictionary whose keys are numbers from 1 to 10 and values are cubes of the key cube_dict = {} for i in range(1, 11): cube_dict[i] = i ** 3 # write a program to create a string variable and print the amount of memory it consumes import sys string_var = 'string variable' print(sys.getsizeof(string_var)) # write a python function that joins strings in a list and returns the result def join_string_parts(str_list): return " ".join(str_list) # write a python program that reverses an integer and prints it num = 12345 reversed = int(str(num)[::-1]) print(reversed) # write a python program that sorts and prints a comma separated list of values values = 'one,two,three,four,five' items = values.split(',') items.sort() print(','.join(items)) # write a python program to print unique words in a sentence sentence = 'the king is the one' unique = set(sentence.split(' ')) print(unique) # write a python program that multiplies a tuple n times and print the result my_tuple = (1, 2, 3) n = 3 print(my_tuple * 3) # write a python program to multiply three numbers and print the result num1 = 2 num2 = 4 num3 = 6 print(num1 * num2 * num3) # write a python program to print the sum of first n numbers n = 10 sum = 0 while n > 0: sum += n n -= 1 print(sum) # write a python program to print the factorial of a number num = 5 fact = 1 while num > 0: fact *= num num -= 1 print(fact) # write a python function to return the factors of a number def get_factors(num): factors = [] for i in range(1, num + 1): if num % i == 0: factors.append(i) return factors # write a python function that returns True if the product of two provided numbers is even def is_prod_even(num1, num2): prod = num1 * num2 return not prod % 2 # write a python function that returns True if the sum of two provided numbers is even def is_prod_even(num1, num2): sum = num1 + num2 return not sum % 2 # write a python program to print the first 5 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[:5]) # write a python program to print the last 3 items in a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[-3:]) # write a python program to print the items in a list apart from the first 4 my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(my_list[4:]) # write a python function that makes all negative values in a list zero and returns it def make_negative_zero(items): return [0 if item < 0 else item for item in items] # write a python program to shuffle the items in a list and print it from random import shuffle mylist = [1, 2, 3, 4, 5] shuffle(mylist) print(mylist) # write a python program that adds the elements of a list to a set and prints the set my_set = {1, 2, 3} my_list = [4, 5, 6] my_set.update(my_list) print(my_set) # write a python program that prints the circumference of a circle import math radius = 10 print(f'Area: {2 * math.pi * radius}') # write a python program that prints the area of a rectangle length = 10 width = 5 print(f'Area: {length * width}') # write a python program that prints the area of a square side = 5 print(f'Area: {side * side}') # write a python program to create a dictionary with numbers 1 to 5 as keys and the numbers in english as values number_dict = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' } # write a python program to remove words less than a specified length from a sentence sentence = 'this is my sentence and i will write it my way' minlength = 3 result = [word for word in sentence.split(' ') if len(word) >= minlength] # write a python program to keep words less than a specified length in a sentence sentence = 'this is my sentence and i will write it my way' maxlength = 3 result = [word for word in sentence.split(' ') if len(word) <= minlength] #### 93 # write a python function that takes a list as an input and converts all numbers to positive numbers and returns the new list def make_all_positive(nums): return [num if num > 0 else -num for num in nums] # write a python function that takes a list as an input and converts all numbers to negative numbers and returns the new list def make_all_negative(nums): return [num if num < 0 else -num for num in nums] # write a python function to return a set of all punctuation used in a string def get_punctuations(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' used_punctuation = set() for char in sentence: if char in punctuations: used_punctuation.add(char) return used_punctuation # write a python program to print the words in a sentence in reverse order sentence = 'the quick brown fox' words = sentence.split(' ') words.reverse() print(' '.join(words)) # write a python program to replace each word in a sentence with the length of the word and print it sentence = 'the quick brown fox jumps over the lazy dog' words = sentence.split(' ') lengths = [str(len(word)) for word in words] print(' '.join(lengths)) # write a python program to convert a set to a list myset = {1, 2, 4, 7} mylist = list(myset) # write a python program to convert a list to a dictionary where the key is the index and the value is the item in the list my_list = [1, 8, 1, 2, 2, 9] my_dict = {key: value for key, value in enumerate(my_list)} #1 write a program to get numbers = 1,3,11,42,12,4001 from collections import Iterable highestnumber = -999 for i in numbers: if i > highestnumber: highestnumber = i print(numbers.index(highestnumber)) #2 write a program to get numbers = 1,3,11,42,12,4001 highestnumber = -999 for i in numbers: if i > highestnumber: highestnumber = i print(numbers.index(highestnumber)) #3 add 1 to all elements in list python lst = [1,2,3] list(map(lambda x:x+1, lst)) #4 add a string to each element of a list python my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' list2 = list(map(lambda orig_string: orig_string + string, my_list)) #5 add a third dimension matrix dataset python x = [2D_matrix] # To convert from a 2-D to 3-D # or x = [[[value1]]] # To convert from a 1-D to 3-D #6 python add all values of another list a = [1, 2, 3] b = [4, 5, 6] a += b #7 add a value to the start of a list python var=7 array = [1,2,3,4,5,6] array.insert(0,var) #8 print into lowersase an uppercase sentence in python s = "Kilometer" print(s.lower()) #9 sort a dictionary mydictionary : {1: 1, 7: 2, 4: 2, 3: 1, 8: 1} sortedDictionary = sorted(mydictionary.keys()) #10 limit decimals to only two decimals in python answer = str(round(answer, 2)) #11 print how many keys are in a dictionary python a = {'foo':42, 'bar':69} print(len(a)) #11 access index of a character in a string python foo = 'Hello' foo.find('lo') #12 python print last element of list mylist = [0, 1, 2] print(myList[-1]) #13 how to add a blank line in python print("") #14 how to add element at first position in array python x = [1,3,4] a = 2 x.insert(1,a) #15 how to add extra zeros after decimal in python format(2.0, '.6f') '2.000000' #16 how to add list numbers in python numbers = [1,2,3,4,5,1,4,5] Sum = sum(numbers) #17 split list into lists of equal length python [lst[i:i + n] for i in range(0, len(lst), n)] #18 how to break out of nested loops python x_loop_must_break = False for x in [1, 2, 3]: print(f"x is {x}") for y in [1, 2, 3]: print(f"y is {y}") if y == 2: x_loop_must_break = True break if x_loop_must_break: break #19 capitalize first letter in python in list my_list = ['apple pie', 'orange jam'] my_list[0].capitalize() #20 how to check if a list is a subset of another list if(all(x in test_list for x in sub_list)): flag = True #21 write a function to check if string is camelcase pythonpython by Breakable Buffalo on Aug 09 2020 Donate def is_camel_case(s): return s != s.lower() and s != s.upper() and "_" not in s #22 how to check if string is in byte formate pythin isinstance(string, bytes) #23 how to check nth prime in python x=int(input()) n,c=1,0 while(c 1: mid = len(myList) // 2 left = myList[:mid] right = myList[mid:] # Recursive call on each half mergeSort(left) mergeSort(right) # Two iterators for traversing the two halves i = 0 j = 0 # Iterator for the main list k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: # The value from the left half has been used myList[k] = left[i] # Move the iterator forward i += 1 else: myList[k] = right[j] j += 1 # Move to the next slot k += 1 # For all the remaining values while i < len(left): myList[k] = left[i] i += 1 k += 1 while j < len(right): myList[k]=right[j] j += 1 k += 1 myList = [54,26,93,17,77,31,44,55,20] mergeSort(myList) #50 write a python function to find the median on an array of numbers def median(arr): if len(arr) == 1: return arr[0] else: arr = sorted(arr) a = arr[0:round(len(arr)/2)] b = arr[len(a):len(arr)] if len(arr)%2 == 0: return (a[len(a)-1]+b[0])/2 else: return a[len(a)-1] #51 write a python function to find a missing number in a list of consecutive natural numbers def getMissingNo(A): n = len(A) total = (n + 1)*(n + 2)/2 sum_of_A = sum(A) return total - sum_of_A #52 write a python program to normalize a list of numbers and print the result a = [2,4,10,6,8,4] amin, amax = min(a), max(a) for i, val in enumerate(a): a[i] = (val-amin) / (amax-amin) print(a) #53 write a python program to permutations of a given string in python and print the result from itertools import permutations import string s = "GEEK" a = string.ascii_letters p = permutations(s) d = [] for i in list(p): if (i not in d): d.append(i) print(''.join(i)) #54 Write a Python function to check if a number is a perfect square def is_perfect_square(n): x = n // 2 y = set([x]) while x * x != n: x = (x + (n // x)) // 2 if x in y: return False y.add(x) return True #55 Write a Python function to check if a number is a power of a given base. import math def isPower (n, base): if base == 1 and n != 1: return False if base == 1 and n == 1: return True if base == 0 and n != 1: return False power = int (math.log(n, base) + 0.5) return base ** power == n #56 Write a Python function to find three numbers from an array such that the sum of three numbers equal to zero. def three_Sum(num): if len(num)<3: return [] num.sort() result=[] for i in range(len(num)-2): left=i+1 right=len(num)-1 if i!=0 and num[i]==num[i-1]:continue while left 0 else 0 #60 Write a function program to reverse the digits of an integer. def reverse_integer(x): sign = -1 if x < 0 else 1 x *= sign # Remove leading zero in the reversed integer while x: if x % 10 == 0: x /= 10 else: break # string manipulation x = str(x) lst = list(x) # list('234') returns ['2', '3', '4'] lst.reverse() x = "".join(lst) x = int(x) return sign*x #61 Write a Python function to reverse the bits of an integer (32 bits unsigned). def reverse_Bits(n): result = 0 for i in range(32): result <<= 1 result |= n & 1 n >>= 1 return result #62 Write a Python function to check a sequence of numbers is an arithmetic progression or not. def is_arithmetic(l): delta = l[1] - l[0] for index in range(len(l) - 1): if not (l[index + 1] - l[index] == delta): return False return True #63 Python Challenges: Check a sequence of numbers is a geometric progression or not def is_geometric(li): if len(li) <= 1: return True # Calculate ratio ratio = li[1]/float(li[0]) # Check the ratio of the remaining for i in range(1, len(li)): if li[i]/float(li[i-1]) != ratio: return False return True #64 Write a Python function to compute the sum of the two reversed numbers and display the sum in reversed form. def reverse_sum(n1, n2): return int(str(int(str(n1)[::-1]) + int(str(n2)[::-1]))[::-1]) #65 Write a Python function where you take any positive integer n, if n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach 1. def collatz_sequence(x): num_seq = [x] if x < 1: return [] while x > 1: if x % 2 == 0: x = x / 2 else: x = 3 * x + 1 num_seq.append(x) return num_seq #65 Write a Python function to check if a given string is an anagram of another given string. def is_anagram(str1, str2): list_str1 = list(str1) list_str1.sort() list_str2 = list(str2) list_str2.sort() return (list_str1 == list_str2) #66 Write a Python function to push all zeros to the end of a list. def move_zero(num_list): a = [0 for i in range(num_list.count(0))] x = [ i for i in num_list if i != 0] x.extend(a) return(x) #67 Write a Python function to the push the first number to the end of a list. def move_last(num_list): a = [num_list[0] for i in range(num_list.count(num_list[0]))] x = [ i for i in num_list if i != num_list[0]] x.extend(a) return(x) #68 Write a Python function to find the length of the last word. def length_of_last_word(s): words = s.split() if len(words) == 0: return 0 return len(words[-1]) #69 Write a Python function to add two binary numbers. def add_binary_nums(x,y): max_len = max(len(x), len(y)) x = x.zfill(max_len) y = y.zfill(max_len) result = '' carry = 0 for i in range(max_len-1, -1, -1): r = carry r += 1 if x[i] == '1' else 0 r += 1 if y[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 if carry !=0 : result = '1' + result return result.zfill(max_len) #70 Write a Python function to find the single number which occurs odd numbers and other numbers occur even number. def odd_occurrence(arr): # Initialize result result = 0 # Traverse the array for element in arr: # XOR result = result ^ element return result #71 Write a Python function that takes a string and encode it that the amount of symbols would be represented by integer and the symbol. For example, the string "AAAABBBCCDAAA" would be encoded as "4A3B2C1D3A" def encode_string(str1): encoded = "" ctr = 1 last_char = str1[0] for i in range(1, len(str1)): if last_char == str1[i]: ctr += 1 else: encoded += str(ctr) + last_char ctr = 0 last_char = str1[i] ctr += 1 encoded += str(ctr) + last_char return encoded #72 Write a Python function to create a new array such that each element at index i of the new array is the product of all the numbers of a given array of integers except the one at i. def product(nums): new_nums = [] for i in nums: nums_product = 1 for j in nums: if j != i: nums_product = nums_product * j new_nums.append(nums_product) return new_nums #73 Write a python function to find the difference between the sum of the squares of the first two hundred natural numbers and the square of the sum. r = range(1, 201) a = sum(r) print (a * a - sum(i*i for i in r)) #74 Write a Python function to compute s the sum of the digits of the number 2 to the power 20. def digits_sum(): n = 2**20 ans = sum(int(c) for c in str(n)) return str(ans) #75 Write a Python program to compute the sum of all the multiples of 3 or 5 below 500. n = 0 for i in range(1,500): if not i % 5 or not i % 3: n = n + i print(n) #76 Write a Python function to converting an integer to a string in any base. def to_string(n,base): conver_tString = "0123456789ABCDEF" if n < base: return conver_tString[n] else: return to_string(n//base,base) + conver_tString[n % base #77 Write a Python function to calculate the geometric sum of n-1. def geometric_sum(n): if n < 0: return 0 else: return 1 / (pow(2, n)) + geometric_sum(n - 1) #78 Write a Python function 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) #79 Write a program to print which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) #80 write a Python program to print the roots of a quadratic equation import math a = float(input("Enter the first coefficient: ")) b = float(input("Enter the second coefficient: ")) c = float(input("Enter the third coefficient: ")) if (a!=0.0): d = (bb)-(4ac) if (d==0.0): print("The roots are real and equal.") r = -b/(2a) print("The roots are ", r,"and", r) elif(d>0.0): print("The roots are real and distinct.") r1 = (-b+(math.sqrt(d)))/(2a) r2 = (-b-(math.sqrt(d)))/(2a) print("The root1 is: ", r1) print("The root2 is: ", r2) else: print("The roots are imaginary.") rp = -b/(2a) ip = math.sqrt(-d)/(2a) print("The root1 is: ", rp, "+ i",ip) print("The root2 is: ", rp, "- i",ip) else: print("Not a quadratic equation." #81 Write a Python program to convert a given Bytearray to Hexadecimal string. def bytearray_to_hexadecimal(list_val): result = ''.join('{:02x}'.format(x) for x in list_val) return(result) #82 Write a Python program to count number of substrings with same first and last characters of a given string. def no_of_substring_with_equalEnds(str1): result = 0; n = len(str1); for i in range(n): for j in range(i, n): if (str1[i] == str1[j]): result = result + 1 return result #83 Write a Python program to move all spaces to the front of a given string in single traversal. def moveSpaces(str1): no_spaces = [char for char in str1 if char!=' '] space= len(str1) - len(no_spaces) result = ' '*space return result + ''.join(no_spaces) #84 Write a Python program to find maximum length of consecutive 0ā€™s in a given binary string. def max_consecutive_0(input_str): return max(map(len,input_str.split('1'))) str1 = '111000010000110' print("Original string:" + str1) print("Maximum length of consecutive 0ā€™s:") #85 Write a Python program that iterate over elements repeating each as many times as its count. from collections import Counter c = Counter(p=4, q=2, r=0, s=-2) print(list(c.elements())) #86 Write a Python program to find the second smallest number in a list. def second_smallest(numbers): if (len(numbers)<2): return if ((len(numbers)==2) and (numbers[0] == numbers[1]) ): return dup_items = set() uniq_items = [] for x in numbers: if x not in dup_items: uniq_items.append(x) dup_items.add(x) uniq_items.sort() return uniq_items[1] #87 Write a Python function to check whether a list contains a sublist. def is_Sublist(l, s): sub_set = False if s == []: sub_set = True elif s == l: sub_set = True elif len(s) > len(l): sub_set = False else: for i in range(len(l)): if l[i] == s[0]: n = 1 while (n < len(s)) and (l[i+n] == s[n]): n += 1 if n == len(s): sub_set = True return sub_set #86 Write a Python program to generate groups of five consecutive numbers in a list l = [[5*i + j for j in range(1,6)] for i in range(5)] print(l) #87 Write a Python program to print the list in a list of lists whose sum of elements is the highest. print(max(num, key=sum)) #88 Write a Python fuction to print the depth of a dictionary. def dict_depth(d): if isinstance(d, dict): return 1 + (max(map(dict_depth, d.values())) if d else 0) return 0 dic = {'a':1, 'b': {'c': {'d': {}}}} print(dict_depth(dic)) #89 Write a Python function to pack consecutive duplicates of a given list elements into sublists and print the output. from itertools import groupby def pack_consecutive_duplicates(l_nums): return [list(group) for key, group in groupby(l_nums)] n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ] print("Original list:") print(n_list) print("\nAfter packing consecutive duplicates of the said list elements into sublists:") print(pack_consecutive_duplicates(n_list)) #90 Write a Python function to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters and print the output. from itertools import groupby def modified_encode(alist): def ctr_ele(el): if len(el)>1: return [len(el), el[0]] else: return el[0] return [ctr_ele(list(group)) for key, group in groupby(alist)] n_list = [1,1,2,3,4,4,5, 1] print("Original list:") print(n_list) print("\nList reflecting the modified run-length encoding from the said list:") print(modified_encode(n_list)) #91 Write a Python function to create a multidimensional list (lists of lists) with zeros and print the output. nums = [] for i in range(3): nums.append([]) for j in range(2): nums[i].append(0) print("Multidimensional list:") print(nums) #92 Write a Python function to read a square matrix from console and print the sum of matrix primary diagonal.Accept the size of the square matrix and elements for each column separated with a space (for every row) as input from the user and print the output. size = int(input("Input the size of the matrix: ")) matrix = [[0] * size for row in range(0, size)] for x in range(0, size): line = list(map(int, input().split())) for y in range(0, size): matrix[x][y] = line[y] matrix_sum_diagonal = sum(matrix[size - i - 1][size - i - 1] for i in range(size)) #93 Write a Python function to check if a nested list is a subset of another nested list and print the output. def checkSubset(input_list1, input_list2): return all(map(input_list1.__contains__, input_list2)) list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]] list2 = [[1, 3],[13,15,17]] print("Original list:") print(list1) print(list2) print("\nIf the one of the said list is a subset of another.:") print(checkSubset(list1, list2)) #94 Write a Python function to print all permutations with given repetition number of characters of a given string and print the output. from itertools import product def all_repeat(str1, rno): chars = list(str1) results = [] for c in product(chars, repeat = rno): results.append(c) return results print(all_repeat('xyz', 3)) #95 Write a Python function to find the index of a given string at which a given substring starts. If the substring is not found in the given string return 'Not found' and print the output. def find_Index(str1, pos): if len(pos) > len(str1): return 'Not found' for i in range(len(str1)): for j in range(len(pos)): if str1[i + j] == pos[j] and j == len(pos) - 1: return i elif str1[i + j] != pos[j]: break return 'Not found #96 Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors. def smallest_multiple(n): if (n<=2): return n i = n * 2 factors = [number for number in range(n, 1, -1) if number * 2 > n] print(factors) while True: for a in factors: if i % a != 0: i += n break if (a == factors[-1] and i % a == 0): return i #97 Write a Python program to print all permutations of a given string (including duplicates). def permute_string(str): if len(str) == 0: return [''] prev_list = permute_string(str[1:len(str)]) next_list = [] for i in range(0,len(prev_list)): for j in range(0,len(str)): new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1] if new_str not in next_list: next_list.append(new_str) return next_lis #98 Write a Python program to multiply two integers without using the '*' operator in python. def multiply(x, y): if y < 0: return -multiply(x, -y) elif y == 0: return 0 elif y == 1: return x else: return x + multiply(x, y - 1) #99 Write a Python program to calculate distance between two points using latitude and longitude. from math import radians, sin, cos, acos print("Input coordinates of two points:") slat = radians(float(input("Starting latitude: "))) slon = radians(float(input("Ending longitude: "))) elat = radians(float(input("Starting latitude: "))) elon = radians(float(input("Ending longitude: "))) dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon)) print("The distance is %.2fkm." % dist) #99 Write a Python class to convert a roman numeral to an integer. class Solution: def roman_to_int(self, s): rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} int_val = 0 for i in range(len(s)): if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]: int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]] else: int_val += rom_val[s[i]] return int_val #100 Write a Python class to convert an integer to a roman numeral. class Solution: def int_to_Roman(self, num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in range(num // val[i]): roman_num += syb[i] num -= val[i] i += 1 return roman_num # write a function to merge two sorted lists def merge_lists(lst1, lst2): # Write your code here res = [] # handle case where one of the list will be empty if len(lst1) == 0 or len(lst2) == 0: res.extend(lst1 + lst2) return res last_processed_i_idx = 0 last_processed_j_idx = 0 for i_idx, i in enumerate(lst1): for j_idx, j in enumerate(lst2, start=last_processed_j_idx + 1): if i < j: res.append(i) last_processed_i_idx = i_idx break elif i > j: res.append(j) last_processed_j_idx = j_idx continue else: res.append(i) last_processed_i_idx = i_idx res.append(j) last_processed_j_idx = j_idx break if len(lst1) == last_processed_i_idx: res.extend(lst2[last_processed_j_idx + 1:]) if len(lst2) == last_processed_j_idx: res.extend(lst1[last_processed_i_idx+ 1:]) return res # Implement a function which modifies a list so that each index has a product of all the numbers present in the list except the number stored at that index. def find_product(lst): # get product start from left left = 1 product = [] for ele in lst: product.append(left) left = left * ele # get product starting from right right = 1 for i in range(len(lst)-1, -1, -1): product[i] = product[i] * right right = right * lst[i] return product # write a function to find out the second maximum number in the given list def find_second_maximum(lst): max = float('-inf') sec_max = float('-inf') for elem in list: if elem > max: sec_max = max max = elem elif elem > sec_max: sec_max = elem return sec_max # write a function to right rotate a given list by given input def right_rotate(lst, n): n = n % len(lst) return lst[-n:] + lst[:-n] # write a function which rearranges the elements such that all the negative elements appear on the left and positive elements appear at the right of the list. Note that it is not necessary to maintain the sorted order of the input list. def rearrange(lst): leftMostPosEle = 0 # index of left most element # iterate the list for curr in range(len(lst)): # if negative number if (lst[curr] < 0): # if not the last negative number if (curr is not leftMostPosEle): # swap the two lst[curr], lst[leftMostPosEle] = lst[leftMostPosEle], lst[curr] # update the last position leftMostPosEle += 1 return lst # With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. tp=(1,2,3,4,5,6,7,8,9,10) tp1=tp[:5] tp2=tp[5:] print(tp1) print(tp2) # Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". s= input() if s=="yes" or s=="YES" or s=="Yes": print("Yes") else: print("No") # Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print(evenNumbers) # Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. li = [1,2,3,4,5,6,7,8,9,10] squaredNumbers = map(lambda x: x**2, li) print(squaredNumbers) # Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10] and print it li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) print(evenNumbers) # Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). evenNumbers = filter(lambda x: x%2==0, range(1,21)) print(evenNumbers) # Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). squaredNumbers = map(lambda x: x**2, range(1,21)) print(squaredNumbers) # Define a class named American which has a static method called printNationality. class American(object): @staticmethod def printNationality(): print("America") anAmerican = American() anAmerican.printNationality() American.printNationality() # Define a class named American and its subclass NewYorker. class American(object): pass class NewYorker(American): pass # Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class Circle(object): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 # Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width # Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. class Shape(object): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, l): Shape.__init__(self) self.length = l def area(self): return self.length*self.length # Please raise a RuntimeError exception. raise RuntimeError('something wrong') # Write a function to compute 5/0 and use try/except to catch the exceptions. def throws(): return 5/0 try: throws() except ZeroDivisionError: print("division by zero!") except Exception: print('Caught an exception') finally: print('In finally block for cleanup') # Define a custom exception class which takes a string message as attribute. class MyError(Exception): def __init__(self, msg): self.msg = msg # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = 'bing@google.com' pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print(r2.group(1)) # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = 'bing@google.com' pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAddress) print(r2.group(2)) # Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. import re s = input() print(re.findall("\d+",s)) # Print a unicode string "hello world". unicodeString = u"hello world!" print(unicodeString) # Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. s = input() u = unicode( s ,"utf-8") print(u) # Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by input parameters. n=int(input()) sum=0.0 for i in range(1,n+1): sum += float(float(i)/(i+1)) print(sum) # Write a function to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 with a given n input by input parameters. def f(n): if n==0: return 0 else: return f(n-1)+100 # Please write a function to compute the Fibonacci sequence until a given number via input paramters. def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) # Please write a function using generator to print the even numbers between 0 and n in comma separated form while n is input by console. def EvenGenerator(n): i=0 while i<=n: if i%2==0: yield i i+=1 # Please write a function using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i # Please write assert statements to verify that every number in the list [2,4,6,8] is even. li = [2,4,6,8] for i in li: assert i%2==0 # Please write a program which accepts basic mathematic expression from console and print the evaluation result. expression = input() print(eval(expression)) # Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index # Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index # Please generate a random float where the value is between 10 and 100 using Python math module. import random print(random.random()*100) # Please generate a random float where the value is between 5 and 95 using Python math module. import random print(random.random()*100-5) # Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. import random print(random.choice([i for i in range(11) if i%2==0])) # Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension import random print(random.choice([i for i in range(201) if i%5==0 and i%7==0])) # Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. import random print(random.sample(range(100), 5)) # Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. import random print(random.sample([i for i in range(100,201) if i%2==0], 5)) # Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. import random print(random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)) # Please write a program to randomly print a integer number between 7 and 15 inclusive. import random print(random.randrange(7,16)) # Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". import zlib s = b'hello world!hello world!hello world!hello world!' t = zlib.compress(s) print(t) print(zlib.decompress(t)) # Please write a program to print the running time of execution of "1+1" for 100 times. from timeit import Timer t = Timer("for i in range(100):1+1") print(t.timeit()) # Please write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3,6,7,8] shuffle(li) print(li) # Please write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3,6,7,8] shuffle(li) print(li) # Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. subjects=["I", "You"] verbs=["Play", "Love"] objects=["Hockey","Football"] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print(sentence) # Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print(li) # By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print(li) # By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print(li) # By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print(array) # By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] print(li) # By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print(li) # With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print(li) # With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. def removeDuplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli # Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. class Person(object): def getGender( self ): return "Unknown" class Male( Person ): def getGender( self ): return "Male" class Female( Person ): def getGender( self ): return "Female" # Please write a program which count and print the numbers of each character in a string input by console. dic = {} s=input() for s in s: dic[s] = dic.get(s,0)+1 print('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])) # Please write a program which accepts a string from console and print it in reverse order. s=input() s = s[::-1] print(s) # Please write a program which accepts a string from console and print the characters that have even indexes. s=input() s = s[::2] print(s) # Please write a program which prints all permutations of [1,2,3] import itertools print(list(itertools.permutations([1,2,3]))) # Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2*i+4*j==numlegs: return i,j return ns,ns # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence on a single line. l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print(','.join(l)) # Write a function which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(input()) print(fact(x)) # With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. n=int(input()) d=dict() for i in range(1,n+1): d[i]=i*i print(d) # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. values=input() l=values.split(",") t=tuple(l) print(l) print(t) # Define a class which has at least two methods: class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = input() def printString(self): print(self.s.upper()) strObj = InputOutString() strObj.getString() strObj.printString() # Write a program that calculates and prints the value according to the given formula: # Q = Square root of [(2 * C * D)/H] # Following are the fixed values of C and H: # C is 50. H is 30. # D is the variable whose values should be input to your program in a comma-separated sequence. import math c=50 h=30 value = [] items=[x for x in input().split(',')] for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print(','.join(value)) # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. input_str = input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] colNum=dimensions[1] multilist = [[0 for col in range(colNum)] for row in range(rowNum)] for row in range(rowNum): for col in range(colNum): multilist[row][col]= row*col print(multilist) # Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. items=[x for x in input().split(',')] items.sort() print(','.join(items)) # Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. lines = [] while True: s = input() if s: lines.append(s.upper()) else: break; for sentence in lines: print(sentence) # Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. s = input() words = [word for word in s.split(" ")] print(" ".join(sorted(list(set(words))))) # Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. value = [] items=[x for x in input().split(',')] for p in items: intp = int(p, 2) if not intp%5: value.append(p) print(','.join(value)) # Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print(",".join(values)) # Write a program that accepts a sentence and calculate the number of letters and digits. s = input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print("LETTERS", d["LETTERS"]) print("DIGITS", d["DIGITS"]) # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. s = input() 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("UPPER CASE", d["UPPER CASE"]) print("LOWER CASE", d["LOWER CASE"]) # Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. a = input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print(n1+n2+n3+n4) # Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. values = input() numbers = [x for x in values.split(",") if int(x)%2!=0] print(",".join(numbers)) # Write a function with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. def putNumbers(n): i = 0 while ilen2: print(s1) elif len2>len1: print(s2) else: print(s1) print(s2) # Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". def even_or_odd_num(n): if n%2 == 0: print("It is an even number") else: print("It is an odd number") # Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. def print_dict_keys_val_1(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print(d) # Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. def print_dict_keys_val_2(): d=dict() for i in range(1,21): d[i]=i**2 print(d) # Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. def print_dict_keys_val_3(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print(v) # Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. def print_dict_keys_val_4(): d=dict() for i in range(1,21): d[i]=i**2 for k in d.keys(): print(k) # Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). def printList(): li=list() for i in range(1,21): li.append(i**2) print(li) # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print(li[:5]) # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print(li[-5:]) # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print(li[5:]) # Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). def printTuple(): li=list() for i in range(1,21): li.append(i**2) print(tuple(li)) # write a python function to check if the user provided string is palindrome or not a palindrome def ifPalindrome(inVar): revInvar = [] for _ in range((len(inVar)-1), -1, -1): revInvar.append(inVar[_]) if revInvar == inVar: return "Palindrome" else: return "Not a palindrome" # write a python function to Calculate the date of n days from the given date. from datetime import datetime, timedelta def add_days(n, d = datetime.today()): return d + timedelta(n) # write a python function to check if all elements in a list are equal. def all_equal(lst): return len(set(lst)) == 1 # write a python function to check if all elements in a list are unique. def all_unique(lst): return len(lst) == len(set(lst)) # write a python function to find the average of two or more numbers and return the average def average(*args): return sum(args, 0.0) / len(args) # write a python function to convert a user provided string to camelcase from re import sub def camel(s): s = sub(r"(_|-)+", " ", s).title().replace(" ", "") return ''.join([s[0].lower(), s[1:]]) # write a python function to capitalize the first letter of a string def capitalize(s, lower_rest = False): return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])]) # write a python function to convert Celsius to Fahrenheit. def celsius_to_fahrenheit(degrees): return ((degrees * 1.8) + 32) # write a python function to convert a given string into a list of words. import re def words(s, pattern = '[a-zA-Z-]+'): return re.findall(pattern, s) # write a python function thats returns a flat list of all the values in a flat dictionary def values_only(flat_dict): return list(flat_dict.values()) # write a python function thats accepts a list and returns most frequent element that appears in a list def most_frequent(list): return max(set(list), key = list.count) # write a python program to create multiplication table of 5 n=5 for i in range(1,11): print(n,'x',i,'=',n*i) # write a python function to create multiplication table from the user provided number def multiplication_table(n): for i in range(1,11): print(n,'x',i,'=',n*i) # write a python program to print a dictionary where the keys are numbers between 1 and 10 (both included) and the values are square of keys. d=dict() for x in range(1,11): d[x]=x**2 print(d) # write a python program to sort a list of tuples using Lambda. marks = [('Computer Science', 88), ('Physics', 90), ('Maths', 97), ('Chemistry', 82)] print("Original list of tuples:") print(marks) marks.sort(key = lambda x: x[1]) print("\nSorting the List of Tuples:") print(marks) # write a python function to calculate the median of user provided list of numbers def median(list): list.sort() list_length = len(list) if list_length % 2 == 0: return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2 return float(list[int(list_length / 2)]) # write a Python program to calculate simple interest p = 10000 t = 6 r = 8 si = (p * t * r)/100 print(f'Simple interest is {si}') # write a python program to check if year is a leap year or not year = 2004 if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") # Write a python function to check if user provided year is a leap year or not def is_leap(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") # Write a python function to check the strength of user provided password def check_password_strength(password): import re flag = 0 while True: if (len(password)<8): flag = -1 break elif not re.search("[a-z]", password): flag = -1 break elif not re.search("[A-Z]", password): flag = -1 break elif not re.search("[0-9]", password): flag = -1 break elif not re.search("[_@$]", password): flag = -1 break elif re.search("\s", password): flag = -1 break else: flag = 0 print("Strong Password") break if flag ==-1: print("Weak Password") # write a python Program to find area of circle PI = 3.14 radius = float(6) area = PI * radius * radius circumference = 2 * PI * radius print(f'Area Of a Circle {area}') print(f'Circumference Of a Circle {circumference}') # write a python function to find the area of a circle using the user provided radius def area_of_circle(radius): PI = 3.14 radius = float(radius) area = PI * radius * radius circumference = 2 * PI * radius print(f'Area Of a Circle {area}') print(f'Circumference Of a Circle {circumference}') # write a python function to find the area of a circle using the user provided circumference def area_of_circle(circumference): circumference = float(circumference) PI = 3.14 area = (circumference * circumference)/(4 * PI) print(f'Area Of a Circle {area}') # write a python function to find the area of a circle using the user provided diameter def area_of_circle(diameter): PI = 3.14 area = (PI/4) * (diameter * diameter) print(f'Area Of a Circle {area}') # write a python function to generate 4 digit OTP import math, random def generateOTP() : digits = "0123456789" OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] return OTP # write a python function to generate 6 digit OTP import math, random def generateOTP() : digits = "0123456789" OTP = "" for i in range(6) : OTP += digits[math.floor(random.random() * 10)] return OTP # write a python program to calculate distance between tao points import math p1 = [4, 0] p2 = [6, 6] distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) ) print(f"The distance between {p1} and {p2} is {distance}") # write a python function to calculate compound interest def compound_interest(principle, rate, time): Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle print(f"Compound interest is {CI}") # write a python function to convert hours to minutes def convert_to_minutes(num_hours): minutes = num_hours * 60 return minutes # write a python function to convert hours to seconds def convert_to_seconds(num_hours): minutes = num_hours * 60 seconds = minutes * 60 return seconds # write a python function to remove vowels from a string def vowel_remover(text): string = "" for l in text: if l.lower() != "a" and l.lower() != "e" and l.lower() != "i" and l.lower() != "o" and l.lower() != "u": string += l return string # write a python program to print all integers that arenā€™t divisible by either 2 or 3 and lies between 1 and 50. for i in range(0,50): if((i%2!=0) & (i%3!=0)): print(i) # write a python function to print odd numbers between user provided ranges def odd_numbers(lower,upper): for i in range(lower,upper+1): if(i%2!=0): print(i) # write a python program to find sum of natural numbers up to a 16 num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) # write a python program to remove punctuations from a string punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, she said ---and went." no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # write a python function to find the resolution on the user provided image def jpeg_res(filename): with open(filename,'rb') as img_file: img_file.seek(163) a = img_file.read(2) height = (a[0] << 8) + a[1] a = img_file.read(2) width = (a[0] << 8) + a[1] print(f"The resolution of the image is {width}x{height}") # write a python program to count the number of each vowels in a given text vowels = 'aeiou' text = 'Hello, have you tried our tutorial section yet?' text = text.casefold() count = {}.fromkeys(vowels,0) for char in text: if char in count: count[char] += 1 print(count) # write a python function to check if a key exists in a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} 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') # write a python program to check if the list is empty l = [] if not l: print("List is empty") else: print("List is not empty") # write a python program to convert two lists into dictionary column_names = ['id', 'color', 'style'] column_values = [1, 'red', 'bold'] name_to_value_dict = dict(zip(column_names, column_values)) name_to_value_dict = {key:value for key, value in zip(column_names, column_values)} name_value_tuples = zip(column_names, column_values) name_to_value_dict = {} for key, value in name_value_tuples: if key in name_to_value_dict: pass else: name_to_value_dict[key] = value print(name_to_value_dict) # write a python program to get index values for a list in the form of key:value pair using enumerate my_list = ['a', 'b', 'c', 'd', 'e'] for index, value in enumerate(my_list): print('{0}: {1}'.format(index, value)) # write a python program to merge two dictionaries dict_1 = {'apple': 9, 'banana': 6} dict_2 = {'banana': 4, 'orange': 8} combined_dict = {**dict_1, **dict_2} print(combined_dict) # write a python function to check if all elements in a list are unique or not def unique(l): if len(l)==len(set(l)): print("All elements are unique") else: print("List has duplicates") # write a python function to validate the email import re regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' def check(email): if(re.search(regex,email)): print("Valid Email") else: print("Invalid Email") # write a python function to calculate the age with the user provided date of birth from datetime import date def calculate_age(dtob): today = date.today() return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day)) # write a python function to check if a user provided number is a perfect square. def is_perfect_square(n): x = n // 2 y = set([x]) while x * x != n: x = (x + (n // x)) // 2 if x in y: return False y.add(x) return True # write a python function that removes element from a list using a user provided number def drop(a, n = 1): return a[n:] # write a program function to check if given words appear together in a list of sentence def check(sentence, words): res = [all([k in s for k in words]) for s in sentence] return [sentence[i] for i in range(0, len(res)) if res[i]] # write a python program to convert list of tuples into list lt = [('English', 2), ('Maths', 4), ('Science', '6')] out = [item for t in lt for item in t] print(out) # write a python program to count the number of words in a sentence test_string = "This is a good book" res = len(test_string.split()) print (f"The number of words in string are :{str(res)}") # write a python function to count the occurrences of a value in a list. def count_occurrences(lst, val): return lst.count(val) # write a python function to return the length of user provided string in bytes def byte_size(s): return len(s.encode('utf-8')) # write a python function to calculate the greatest common divisor (GCD) of two user provided positive integers. def gcd(num1, num2): gcd = 1 if num1 % num2 == 0: return num2 for k in range(int(num2 / 2), 0, -1): if num1 % k == 0 and num2 % k == 0: gcd = k break return gcd # write a python function to calculate the least common multiple (LCM) of two user provided positive integers. def lcm(num1, num2): if num1 > num2: z = num1 else: z = num2 while(True): if((z % num1 == 0) and (z % num2 == 0)): lcm = z break z += 1 return lcm # write a python program to split the string into chunks of size 3 str = 'CarBadBoxNumKeyValRayCppSan' n = 3 chunks = [str[i:i+n] for i in range(0, len(str), n)] print(chunks) # write a python function to read first n lines from a file def file_read_from_head(fname, nlines): from itertools import islice with open(fname) as f: for line in islice(f, nlines): print(line) # write a python program to check whether a person is eligible to vote or not age=23 if age>=18: status="Eligible" else: status="Not Eligible" print("You are ",status," for Vote.") # write a python program to check if a number is positive, negative or zero. num = 5 if num > 0: print("It is positive number") elif num == 0: print("It is Zero") else: print("It is a negative number") # write a python program to get numbers divisible by fifteen from a list num_list = [45, 55, 60, 37, 100, 105, 220] result = list(filter(lambda x: (x % 15 == 0), num_list)) print(f"Numbers divisible by 15 are {result}") # write a python function to append text to a user provided file def file_read(fname): with open(fname, "w") as myfile: myfile.write("Appending line one\n") myfile.write("Appending line two") txt = open(fname) print(txt.read()) # write a python function to pad a user provided number to specified length def pad_number(n, l): return str(n).zfill(l) # write a python function to convert a user provided list of dictionaries into a list of values corresponding to the user specified key def pluck(lst, key): return [x.get(key) for x in lst] # write a python function to convert the values of RGB components to a hexadecimal color code. def rgb_to_hex(r, g, b): return ('{:02X}' * 3).format(r, g, b) # write a python function to reverse a user provided list or string def reverse(itr): return itr[::-1] # write a python function to convert an angle from radians to degrees. def rads_to_degrees(rad): return (rad * 180.0) / 3.14 # write a python function that returns a list of elements that exist in both user provided lists. def similarity(a, b): return [item for item in a if item in b] # write a python function that converts a user provided string to snake case from re import sub def snake(s): return '_'.join( sub('([A-Z][a-z]+)', r' \1', sub('([A-Z]+)', r' \1', s.replace('-', ' '))).split()).lower() # write a python function that sorts a list based on the user provided list of indexes. def sort_by_indexes(lst, indexes, reverse=False): return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \ x[0], reverse=reverse)] # write a python function to sort the dictionary by key def sort_dict_by_key(d, reverse = False): return dict(sorted(d.items(), reverse = reverse)) # write a python function to sort the dictionary by values def sort_dict_by_value(d, reverse = False): return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse)) # write a python function to capitalize first letter of a string def capitalize(s, lower_rest = False): return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])]) # write a python function that chunks a list into smaller lists of a specified size from math import ceil def chunk(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(ceil(len(lst) / size))))) # write a python function to calculate a sigmoid value for any user provided real numbers def sigmoid(x): return 1 / (1 + math.exp(-x)) # write a python program to count the number of lines in a text file !touch abc.txt file = open("abc.txt","r") Counter = 0 Content = file.read() CoList = Content.split("\n") for i in CoList: if i: Counter += 1 print(f"There are {Counter} number of lines in the file") # write a python program to count the number of lower case in a string string="This is a very good place to Visit" count=0 for i in string: if(i.islower()): count=count+1 print(f"The number of lowercase characters is:{count}") # write a python program to find the sequences of one upper case letter followed by lower case letters. import re text="Albert" patterns = '[A-Z]+[a-z]+$' if re.search(patterns, text): print('Found a match!') else: print('Not matched!') # write a python program to find the number of files in a directory import os dir='.' list = os.listdir(dir) number_files = len(list) print(f'There are {number_files} file in the directory') # write a python function to clamp a number within a user specified range def clamp_number(num, a, b): return max(min(num, max(a, b)), min(a, b)) # write a python function that returns every nth element in a list def every_nth(lst, nth): return lst[nth - 1::nth] # write a python function that returns first element of a list def head(lst): return lst[0] # write a python function to check if two lists contains same elements regardless of order def have_same_contents(a, b): for v in set(a + b): if a.count(v) != b.count(v): return False return True # write a python function to rotate the given list by n times toward left def rotate(lst, offset): return lst[offset:] + lst[:offset] # write a python function to transpose a user provided two dimensional list def transpose(lst): return list(zip(*lst)) # write a python function to convert a user provided date to iso representation from datetime import datetime def to_iso_date(d): return d.isoformat() # write a python function to convert an integer to its roman numeral representation def to_roman_numeral(num): lookup = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] res = '' for (n, roman) in lookup: (d, num) = divmod(num, n) res += roman * d return res # write a python function that returns binary representation of given number def to_binary(n): return bin(n) # write a python function to calculate weighted average of two or more numbers def weighted_average(nums, weights): return sum(x * y for x, y in zip(nums, weights)) / sum(weights) # write a python program to filter out non-empty rows of a matrix test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []] print(f"The original list is :{test_list} ") res = [row for row in test_list if len(row) > 0] print(f"Filtered Matrix {res}") # write a python program to print prime factors of user provided number import math def primeFactors(n): while n % 2 == 0: print(2), n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: print(i), n = n / i if n > 2: print(n) # write a python function to return sum of the powers between two numbers def sum_of_powers(end, power = 2, start = 1): return sum([(i) ** power for i in range(start, end + 1)]) # write a python function to implement odd-even sort def oddEvenSort(arr, n): isSorted = 0 while isSorted == 0: isSorted = 1 temp = 0 for i in range(1, n-1, 2): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] isSorted = 0 for i in range(0, n-1, 2): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] isSorted = 0 return # write a python program to find the smallest multiple of the first n numbers. def smallest_multiple(n): if (n<=2): return n i = n * 2 factors = [number for number in range(n, 1, -1) if number * 2 > n] print(factors) while True: for a in factors: if i % a != 0: i += n break if (a == factors[-1] and i % a == 0): return i # write a python program to generate random float numbers in a specific numerical range. import random for x in range(6): print('{:04.3f}'.format(random.uniform(x, 100)), end=' ') # write a python program to drop microseconds from datetime. import datetime dt = datetime.datetime.today().replace(microsecond=0) dt # write a python program to convert unix timestamp string to readable date. import datetime unix_timestamp="1284105682" print( datetime.datetime.fromtimestamp( int(unix_timestamp) ).strftime('%Y-%m-%d %H:%M:%S') ) # write a python program to add two matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) # write a python program to multiply two matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) # write a python function to calculate the day difference between two user provided dates def days_diff(start, end): return (end - start).days # write a python function to decapitalize the first letter of user provided string. def decapitalize(s, upper_rest = False): return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])]) # write a python program to reverse user provided number n = 4562; rev = 0 while(n > 0): a = n % 10 rev = rev * 10 + a n = n // 10 print(rev) # -*- coding: utf-8 -*- """Python Assignment Codes.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/github/piyushjain220/TSAI/blob/main/NLP/Session8/Python_Assignment_Codes.ipynb """ # Given a string, find the length of the longest substring without repeating characters. str = "akshayjain" def longest_non_repeat(str): i=0 max_length = 1 for i,c in enumerate(str): start_at = i sub_str=[] while (start_at < len(str)) and (str[start_at] not in sub_str): sub_str.append(str[start_at]) start_at = start_at + 1 if len(sub_str) > max_length: max_length = len(sub_str) print(sub_str) return max_length longest_non_repeat(str) # Given an array of integers, return indices of the two numbers such that they add up to a specific target. input_array = [2, 7, 11, 15] target = 26 result = [] for i, num in enumerate(input_array): for j in range(i+1, len(input_array)): print(i,j) # Given a sorted integer array without duplicates, return the summary of its ranges. input_array = [0,1,2,4,5,7] start=0 result = [] while start < len(input_array): end = start while end+1{1}".format(input_array[start], input_array[end])) print(result) else: result.append("{0}".format(input_array[start])) print(result) start = end+1 print(result) # Rotate an array of n elements to the right by k steps. org = [1,2,3,4,5,6,7] result = org[:] steps = 3 for idx,num in enumerate(org): if idx+steps < len(org): result[idx+steps] = org[idx] else: result[idx+steps-len(org)] = org[idx] print(result) # Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. first_array = [1,2,3,4,5,6,7] second_array = [3,7,2,1,4,6] def finder(first_array, second_array): return(sum(first_array) - sum(second_array)) missing_number = finder(first_array, second_array) print(missing_number) # Given a collection of intervals which are already sorted by start number, merge all overlapping intervals. org_intervals = [[1,3],[2,6],[5,10],[11,16],[15,18],[19,22]] i = 0 while i < len(org_intervals)-1: if org_intervals[i+1][0] < org_intervals[i][1]: org_intervals[i][1]=org_intervals[i+1][1] del org_intervals[i+1] i = i - 1 i = i + 1 print(org_intervals) # Given a list slice it into a 3 equal chunks and revert each list sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89] length = len(sampleList) chunkSize = int(length/3) start = 0 end = chunkSize for i in range(1, 4, 1): indexes = slice(start, end, 1) listChunk = sampleList[indexes] mylist = [i for i in listChunk] print("After reversing it ", mylist) start = end if(i != 2): end +=chunkSize else: end += length - chunkSize # write a program to calculate exponents of an input input = 9 exponent = 2 final = pow(input, exponent) print(f'Exponent Value is:{final}') # write a program to multiply two Matrix # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] print(f"Final Result is{result}") # write a program to find and print the remainder of two number num1 = 12 num2 = 10 ratio = num1 % num2 print(f'remainder:{ratio}') # reverse a number in Python number = 1367891 revs_number = 0 while (number > 0): remainder = number % 10 revs_number = (revs_number * 10) + remainder number = number // 10 print("The reverse number is : {}".format(revs_number)) # Python program to compute sum of digits in number def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) n = 1234511 print(sumDigits(n)) # Find the middle element of a random number list my_list = [4,3,2,9,10,44,1] print("mid value is ",my_list[int(len(my_list)/2)]) # Sort the list in ascending order my_list = [4,3,2,9,10,44,1] my_list.sort() print(f"Ascending Order list:,{my_list}") # Sort the list in descending order my_list = [4,3,2,9,10,44,1] my_list.sort(reverse=True) print(f"Descending Order list:,{my_list}") # Concatenation of two List my_list1 = [4,3,2,9,10,44,1] my_list2 = [5,6,2,8,15,14,12] print(f"Sum of two list:,{my_list1+my_list2}") # Removes the item at the given index from the list and returns the removed item my_list1 = [4,3,2,9,10,44,1,9,12] index = 4 print(f"Sum of two list:,{my_list1.pop(index)}") # Adding Element to a List animals = ['cat', 'dog', 'rabbit'] animals.append('guinea pig') print('Updated animals list: ', animals) # Returns the number of times the specified element appears in the list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] count = vowels.count('i') print('The count of i is:', count) # Count Tuple Elements Inside List random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] count = random.count(('a', 'b')) print("The count of ('a', 'b') is:", count) # Removes all items from the list list = [{1, 2}, ('a'), ['1.1', '2.2']] list.clear() print('List:', list) # access first characters in a string word = "Hello World" letter=word[0] print(f"First Charecter in String:{letter}") # access Last characters in a string word = "Hello World" letter=word[-1] print(f"First Charecter in String:{letter}") # Generate a list by list comprehension list = [x for x in range(10)] print(f"List Generated by list comprehension:{list}") # Sort the string list alphabetically thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(f"Sorted List:{thislist}") # Join Two Sets set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set2.union(set1) print(f"Joined Set:{set3}") # keep only the items that are present in both sets x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(f"Duplicate Value in Two set:{x}") # Keep All items from List But NOT the Duplicates x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(f"Duplicate Value in Two set:{x}") # Create and print a dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Sample Dictionary:{thisdict}") # Calculate the length of dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(f"Length of Dictionary:{len(thisdict)}") # Evaluate a string and a number print(bool("Hello")) print(bool(15)) # Calculate length of a string word = "Hello World" print(f"Length of string: {len(word)}") # Count the number of spaces in a sring s = "Count, the number of spaces" lenx = s.count(' ') print(f"number of spaces in sring: {lenx}") # Split Strings word = "Hello World" ksplit = word.split(' ') print(f"Splited Strings: {ksplit}") # Prints ten dots ten = "." * 10 print(f"Ten dots: {ten}") # Replacing a string with another string word = "Hello World" replace = "Bye" input = "Hello" after_replace = word.replace(input, replace) print(f"String ater replacement: {after_replace}") #removes leading characters word = " xyz " lstrip = word.lstrip() print(f"String ater removal of leading characters:{lstrip}") #removes trailing characters word = " xyz " rstrip = word.rstrip() print(f"String ater removal of trailing characters:{rstrip}") # check if all char are alphanumeric word = "Hello World" check = word.isalnum() print(f"All char are alphanumeric?:{check}") # check if all char in the string are alphabetic word = "Hello World" check = word.isalpha() print(f"All char are alphabetic?:{check}") # test if string contains digits word = "Hello World" check = word.isdigit() print(f"String contains digits?:{check}") # Test if string contains upper case word = "Hello World" check = word.isupper() print(f"String contains upper case?:{check}") # Test if string starts with H word = "Hello World" check = word.startswith('H') print(f"String starts with H?:{check}") # Returns an integer value for the given character str = "A" val = ord(str) print(f"Integer value for the given character?:{val}") # Fibonacci series up to 100 n = 100 result = [] a, b = 0 , 1 while b < n: result. append( b) a, b = b, a + b final = result print(f"Fibonacci series up to 100:{final}") # Counting total Digits in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isdigit()): digitCount += 1 print('Number of digits: ',digitCount) # Counting total alphanumeric in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.isalpha()): digitCount += 1 print('Number of alphanumeric: ',digitCount) # Counting total Upper Case in a string str1 = "abc4234AFde" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.upper()): digitCount += 1 print('Number total Upper Case: ',digitCount) # Counting total lower Case in a string str1 = "abc4234AFdeaa" digitCount = 0 for i in range(0,len(str1)): char = str1[i] if(char.lower()): digitCount += 1 print('Number total lower Case: ',digitCount) # Bubble sort in python list1 = [1, 5, 3, 4] for i in range(len(list1)-1): for j in range(i+1,len(list1)): if(list1[i] > list1[j]): temp = list1[i] list1[i] = list1[j] list1[j] = temp print("Bubble Sorted list: ",list1) # Compute the product of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a*b for a in list1 for b in list2] print(f"Product of every pair of numbers from two lists:{final}") # Calculate the sum of every pair of numbers from two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [a+b for a in list1 for b in list2] print(f"sum of every pair of numbers from two lists:{final}") # Calculate the pair-wise product of two lists list1 = [1, 2, 3] list2 = [5, 6, 7] final = [list1[i]*list2[i] for i in range(len(list1))] print(f"pair-wise product of two lists:{final}") # Remove the last element from the stack s = [1,2,3,4] print(f"last element from the stack:{s.pop()}") # Insert a number at the beginning of the queue q = [1,2,3,4] q.insert(0,5) print(f"Revised List:{q}") # Addition of two vector v1 = [1,2,3] v2 = [1,2,3] s1 = [0,0,0] for i in range(len(v1)): s1[i] = v1[i] + v2[i] print(f"New Vector:{s1}") # Replace negative prices with 0 and leave the positive values unchanged in a list original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] print(f"Final List:{prices}") # Convert dictionary to JSON import json person_dict = {'name': 'Bob', 'age': 12, 'children': None } person_json = json.dumps(person_dict) print(person_json) # Writing JSON to a file import json person_dict = {"name": "Bob", "languages": ["English", "Fench"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file) # Pretty print JSON import json person_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}' person_dict = json.loads(person_string) print(json.dumps(person_dict, indent = 4, sort_keys=True)) # Check if the key exists or not in JSON import json studentJson ="""{ "id": 1, "name": "Piyush Jain", "class": null, "percentage": 35, "email": "piyushjain220@gmail.com" }""" print("Checking if percentage key exists in JSON") student = json.loads(studentJson) if "percentage" in student: print("Key exist in JSON data") print(student["name"], "marks is: ", student["percentage"]) else: print("Key doesn't exist in JSON data") # Check if there is a value for a key in JSON import json studentJson ="""{ "id": 1, "name": "Piyush Jain", "class": null, "percentage": 35, "email": "piyushjain220@gmail.com" }""" student = json.loads(studentJson) if not (student.get('email') is None): print("value is present for given JSON key") print(student.get('email')) else: print("value is not present for given JSON key") # Sort JSON keys in Python and write it into a file import json sampleJson = {"id" : 1, "name" : "value2", "age" : 29} with open("sampleJson.json", "w") as write_file: json.dump(sampleJson, write_file, indent=4, sort_keys=True) print("Done writing JSON data into a file") # Given a Python list. Turn every item of a list into its square aList = [1, 2, 3, 4, 5, 6, 7] aList = [x * x for x in aList] print(aList) # Remove empty strings from the list of strings list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"] resList = [i for i in (filter(None, list1))] print(resList) # Write a program which will achieve given a Python list, remove all occurrence of an input from the list list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, 20) print(resList) # Generate 3 random integers between 100 and 999 which is divisible by 5 import random print("Generating 3 random integer number between 100 and 999 divisible by 5") for num in range(3): print(random.randrange(100, 999, 5), end=', ') # Pick a random character from a given String import random name = 'pynative' char = random.choice(name) print("random char is ", char) # Generate random String of length 5 import random import string def randomString(stringLength): """Generate a random string of 5 charcters""" letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) print ("Random String is ", randomString(5) ) # Generate a random date between given start and end dates import random import time def getRandomDate(startDate, endDate ): print("Printing random date between", startDate, " and ", endDate) randomGenerator = random.random() dateFormat = '%m/%d/%Y' startTime = time.mktime(time.strptime(startDate, dateFormat)) endTime = time.mktime(time.strptime(endDate, dateFormat)) randomTime = startTime + randomGenerator * (endTime - startTime) randomDate = time.strftime(dateFormat, time.localtime(randomTime)) return randomDate print ("Random Date = ", getRandomDate("1/1/2016", "12/12/2018")) # Write a program which will create a new string by appending s2 in the middle of s1 given two strings, s1 and s2 def appendMiddle(s1, s2): middleIndex = int(len(s1) /2) middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:] print("After appending new string in middle", middleThree) appendMiddle("Ault", "Kelly") # Arrange string characters such that lowercase letters should come first str1 = "PyNaTive" lower = [] upper = [] for char in str1: if char.islower(): lower.append(char) else: upper.append(char) sorted_string = ''.join(lower + upper) print(sorted_string) # Given a string, return the sum and average of the digits that appear in the string, ignoring all other characters import re inputStr = "English = 78 Science = 83 Math = 68 History = 65" markList = [int(num) for num in re.findall(r'\b\d+\b', inputStr)] totalMarks = 0 for mark in markList: totalMarks+=mark percentage = totalMarks/len(markList) print("Total Marks is:", totalMarks, "Percentage is ", percentage) # Given an input string, count occurrences of all characters within a string str1 = "Apple" countDict = dict() for char in str1: count = str1.count(char) countDict[char]=count print(countDict) # Reverse a given string str1 = "PYnative" print("Original String is:", str1) str1 = str1[::-1] print("Reversed String is:", str1) # Remove special symbols/Punctuation from a given string import string str1 = "/*Jon is @developer & musician" new_str = str1.translate(str.maketrans('', '', string.punctuation)) print("New string is ", new_str) # Removal all the characters other than integers from string str1 = 'I am 25 years and 10 months old' res = "".join([item for item in str1 if item.isdigit()]) print(res) # From given string replace each punctuation with # from string import punctuation str1 = '/*Jon is @developer & musician!!' replace_char = '#' for char in punctuation: str1 = str1.replace(char, replace_char) print("The strings after replacement : ", str1) # Given a list iterate it and count the occurrence of each element and create a dictionary to show the count of each elemen sampleList = [11, 45, 8, 11, 23, 45, 23, 45, 89] countDict = dict() for item in sampleList: if(item in countDict): countDict[item] += 1 else: countDict[item] = 1 print("Printing count of each item ",countDict) # Given a two list of equal size create a set such that it shows the element from both lists in the pair firstList = [2, 3, 4, 5, 6, 7, 8] secondList = [4, 9, 16, 25, 36, 49, 64] result = zip(firstList, secondList) resultSet = set(result) print(resultSet) # Given a two sets find the intersection and remove those elements from the first set firstSet = {23, 42, 65, 57, 78, 83, 29} secondSet = {57, 83, 29, 67, 73, 43, 48} intersection = firstSet.intersection(secondSet) for item in intersection: firstSet.remove(item) print("First Set after removing common element ", firstSet) # Given a dictionary get all values from the dictionary and add it in a list but donā€™t add duplicates speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54} speedList = [] for item in speed.values(): if item not in speedList: speedList.append(item) print("unique list", speedList) # Convert decimal number to octal print('%o,' % (8)) # Convert string into a datetime object from datetime import datetime date_string = "Feb 25 2020 4:20PM" datetime_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p') print(datetime_object) # Subtract a week from a given date from datetime import datetime, timedelta given_date = datetime(2020, 2, 25) days_to_subtract = 7 res_date = given_date - timedelta(days=days_to_subtract) print(res_date) # Find the day of week of a given date? from datetime import datetime given_date = datetime(2020, 7, 26) print(given_date.strftime('%A')) # Add week (7 days) and 12 hours to a given date from datetime import datetime, timedelta given_date = datetime(2020, 3, 22, 10, 00, 00) days_to_add = 7 res_date = given_date + timedelta(days=days_to_add, hours=12) print(res_date) # Calculate number of days between two given dates from datetime import datetime date_1 = datetime(2020, 2, 25).date() date_2 = datetime(2020, 9, 17).date() delta = None if date_1 > date_2: delta = date_1 - date_2 else: delta = date_2 - date_1 print("Difference is", delta.days, "days") # Write a recursive function to calculate the sum of numbers from 0 to 10 def calculateSum(num): if num: return num + calculateSum(num-1) else: return 0 res = calculateSum(10) print(res) # Generate a Python list of all the even numbers between two given numbers num1 = 4 num2 = 30 myval = [i for i in range(num1, num2, 2)] print(myval) # Return the largest item from the given list aList = [4, 6, 8, 24, 12, 2] print(max(aList)) # Write a program to extract each digit from an integer, in the reverse order number = 7536 while (number > 0): digit = number % 10 number = number // 10 print(digit, end=" ") # Given a Python list, remove all occurrence of a given number from the list num1 = 20 list1 = [5, 20, 15, 20, 25, 50, 20] def removeValue(sampleList, val): return [value for value in sampleList if value != val] resList = removeValue(list1, num1) print(resList) # Shuffle a list randomly import random list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list) # Generate a random n-dimensional array of float numbers import numpy random_float_array = numpy.random.rand(2, 2) print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n") # Generate random Universally unique IDs import uuid safeId = uuid.uuid4() print("safe unique id is ", safeId) # Choose given number of elements from the list with different probability import random num1 =5 numberList = [111, 222, 333, 444, 555] print(random.choices(numberList, weights=(10, 20, 30, 40, 50), k=num1)) # Generate weighted random numbers import random randomList = random.choices(range(10, 40, 5), cum_weights=(5, 15, 10, 25, 40, 65), k=6) print(randomList) # generating a reliable secure random number import secrets print("Random integer number generated using secrets module is ") number = secrets.randbelow(30) print(number) # Calculate memory is being used by an list in Python import sys list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith'] print("size of list = ",sys.getsizeof(list1)) # Find if all elements in a list are identical listOne = [20, 20, 20, 20] print("All element are duplicate in listOne:", listOne.count(listOne[0]) == len(listOne)) # Merge two dictionaries in a single expression currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"} formerEmployee = {2: 'Eric', 4: "Emma"} allEmployee = {**currentEmployee, **formerEmployee} print(allEmployee) # Convert two lists into a dictionary ItemId = [54, 65, 76] names = ["Hard Disk", "Laptop", "RAM"] itemDictionary = dict(zip(ItemId, names)) print(itemDictionary) # Alternate cases in String test_str = "geeksforgeeks" res = "" for idx in range(len(test_str)): if not idx % 2 : res = res + test_str[idx].upper() else: res = res + test_str[idx].lower() print(res) # 1 write a python function to add to add two numbers def return_exponential(num1, num2): return num1 ** num2 # 2 write a python function to split a string at space def string_split_at_space(string): return string.split() # 3 write a python program to convert a string to a char array def char_array(string): return list(string) # 4 write a python function to print the factorial of a number def factorial(x): prod = 1 for i in range(1, x + 1): prod *= i return prod # 5 write a python function to accept a number and return all the numbers from 0 to that number def print_numbers(x): for i in range(x): print(i) # 6 write a python function that concatenates two stings def concat(s1, s2): return s1 + s2 # 7 write a python function to return every second number from a list def every_other_number(lst): return lst[::2] # 7 write a python function to return every nth number from a list def every_nth_number(lst, n): return lst[::n] # 8 write a python function to accept a key, value pair and return a dictionary def create_dictionary(key, value): return {str(key): value} # 9 write a python function to update a dictionary with a new key, value pair def update_dictionary(dict, key, value): dict[str(key)] = value return dict # 10 write a python function to return the median of a list def calc_median(arr): arr = sorted(arr) if len(arr) / 2 == 0: return arr[len(arr) / 2] else: return (arr[len(arr) // 2] + arr[(len(arr) - 1) // 2]) / 2 # 11 write a python function to return the length of an array plus 27 def return_length(arr): return len(arr) + 27 # 12 write a python function to return the third last element of an array def return_last(arr): return arr[-3] # 13 write a function to calculate the mean of an array def calc_mean(arr): sum = 0 for i in range(len(arr)): sum += arr[i] return sum / len(arr) # 14 write a function to perform insertion sort on an arary def sort_insertion(arr): for i in range(1, len(arr)): tmp = arr[i] j = i while (j > 0) & (tmp < arr[j - 1]): arr[j] = arr[j - 1] j = j - 1 arr[j] = tmp return arr # 15 write a function to implement a binary tree class BinTree: def __init__(self, key): self.left = None self.right = None self.val = key # 16 write a function to immplement insert in binary search tree class BinaryTreeNode: def __init__(self, key): self.left = None self.right = None self.val = key class Tree: def insert(self, root, key): if root is None: return BinaryTreeNode(key) else: if root.val == key: return root elif root.val < key: root.right = self.insert(root.right, key) else: root.left = self.insert(root.left, key) return root # 17 write a function to initialize a linked list class Cell: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None # 18 write a function to create a linked list with given length and print the list after class Node: def __init__(self, val): self.val = val self.next = None class LList: def __init__(self): self.head = None def create_linked_list(*args): linked_list = LList() linked_list.head = Node(args[0]) prev = linked_list.head for i in range(1, len(args)): entry = Node(args[i]) prev.next = entry prev = entry return # 20 write a function which returns the count of each token in a given sentence as a dictionary from collections import Counter def count_tokens(sent): sent = list(sent) return dict(Counter(sent)) # 21 write a function that removes all the punctuations from a string import string def remove_punct(s): return "".join(ch for ch in s if ch not in set(string.punctuation)) # 22 write a function that counts the sum of every element in the odd place in a list from functools import reduce def count_second(lst): return reduce(lambda x, y: x + y, lst[::2]) # 23 write a function that returns the square root of the third power of every number in a list def comp_power(lst): return list(map(lambda x: x ** 1.5, lst)) # 23 write a function to calculate the residual sum of squares between two lists of the same size def rss(lst1, lst2): diff = [lst1[x] - lst2[x] for x in range(len(lst1))] return sum(list(map(lambda x: x ** 2, diff))) # 24 write a program to caclulate the approximate value of pi using the monte carlo method import random def pi_monte_carlo(n=1000000): count = 0 for _ in range(n): x = random.random() y = random.random() if x ** 2 + y ** 2 <= 1: count += 1 return 4 * count / n print(pi_monte_carlo()) # 25 write a funtion to print all the files in the current directory import os def list_files(): return os.listdir() # 26 write a program to calculate the root of a nonlinear equation using Newton's method class NewtonRaphsonSolver: def __init__(self, f, x, dfdx, min_tol=1e-3): self.func = f self.x = x self.derivative = dfdx self.min_tol = min_tol def calculate(self): func_val = self.func(self.x) iterations = 0 while abs(func_val) > self.min_tol and iterations < 100: self.x = self.x - float(func_val) / self.derivative(self.x) func_val = self.func(self.x) iterations += 1 if iterations <= 100: return self.x else: return None def f(x): return x ** 4 - 16 def dfdx(x): return 4 * x ** 3 nrs = NewtonRaphsonSolver(f, 10, dfdx) print(nrs.calculate()) # 26 write a generator in python which returns a random number between 0 and a million import random def yield_a_number(): yield random.randint(0, 1000000) # 27 write a program that filters a list for even numbers only and returns their sum def map_reduce(lst): return reduce(lambda x, y: x + y, filter(lambda x: x % 2 == 0, lst)) print(map_reduce([1, 2, 3, 4, 5])) # 28 write a program that return the first n numbers from a list def sub_list(lst, ind): return lst[:ind] print(sub_list([1, 2, 3, 4, 5, 56], 3)) # 29 write a program to sort a list using bubblesort def bubblesort(arr): n = len(arr) for i in range(n - 1): for j in range(n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr print(bubblesort([1, 33, 192, 21, 0])) # 30 write a function that accepts two numbers or lists or dictionaries and returns True if the two are equal, and False otherwise def check_assert(item1, item2): try: assert item1 == item2 return True except AssertionError: return False # 31 write a function that checks if a number is an Armstrong number (sum of digits of the number = the number) from itertools import chain def check_armstrong(n): sum_of_digits = sum(map(lambda x: int(x) ** 3, chain(str(n)))) if sum_of_digits == n: return True else: return False # 32 write a program in python to create a directed graph, and add an edge between two vertices from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self, f, t): self.graph[f].append(t) def printEdge(self): for ed in list(self.graph.keys()): print(f"From : {ed}, To : {self.graph[ed]}") g = Graph() g.addEdge("a", "b") g.addEdge("a", "e") g.addEdge("b", "d") g.addEdge("c", "d") g.addEdge("c", "a") g.printEdge() # 33 write a program that shows how child class can access the init method of the parent class using super class A: def __init__(self): print("My name is GYOBU MASATAKA ONIWA!") class B(A): def __init__(self): super(B, self).__init__() print("as I breath, you WILL not pass the castle gates!") tmp = B() ## 34 write a program to generate a random number between two ranges import random def rand_range(low, high): return random.randrange(low, high) # 35 Write a python function that sorts a list of strings by their length in the descending order def sort_by_len(arr): return sorted(arr, reverse=True, key=lambda x: len(x)) # 36 Write a python function that returns the Highest Common Factor of two given numbers def calculate_hcf(x1, x2): if x1 == 0: return x2 else: return hcf(x2 % x1, x1) # 37 Write a python program to calculate the LCM and HCF of two given numbers def hcf(x1, x2): if x1 == 0: return x2 else: return hcf(x2 % x1, x1) def lcm_hcf(x1, x2): h_c_f = hcf(x1, x2) lcm = x1 * x2 / h_c_f return lcm, h_c_f l, h = lcm_hcf(18, 12) print(f"LCM : {l}, HCF: {h}") # 38 write a python program which takes in a dictionary with unique values and converts keys into values and vice versa def flip_dict(d): tmp_dict = {} for pair in d.items(): tmp_dict[pair[1]] = pair[0] return tmp_dict print(flip_dict({"a": 10, "b": 20, "c": 15})) # 39 write a python function to return a list of all punctuations from the string library import string def return_punct(): return string.punctuation # 40 write a python function that takes in a string and returns it in lowercase def to_lower(s): return s.lower() # 41 write a python function that takes in a string and returns it in uppercase def to_upper(s): return s.upper() # 42 write a python program that converts lower case letters to uppercase and vice versa def flip_case(s): s = [int(ord(x)) for x in s] s = [x - 32 if x >= 97 else x + 32 for x in s] s = [chr(x) for x in s] return "".join(s) # 43 Define a function which returns the current working directory import os def get_cwd(): return os.getcwd() # 44 Define a python function that can read text file from a given URL import requests def read_data(url): data = requests.get(url).text return data # 45 Define a python function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. import requests def get_status(url): data = requests.get(url) return data.status_code # 46 Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. import requests def get_encoding(url): data = requests.get(url) return data.encoding # 47 write a python function that accepts a valid path and changes the current working directory import os def change_dir(path): return os.chdir(path) # 48 write a python function that checks if a given key is present in the environment import os def get_env_path(key): return os.getenv(key) # 49 Write a generator that returns True / False randomly import random def generate_tf(): rand = random.random() if rand > 0.5: yield True else: yield False # 50 write a python program to normalize an array such that it sums upto 1 def normalize(arr): return [float(i) / sum(arr) for i in arr] print(normalize([1, 2, 3, 4, 5])) # 51 write a python program to perform Softmax operation on an input array import math def softmax(arr): e_arr = [math.exp(x) for x in arr] e_soft = [i / sum(e_arr) for i in e_arr] return e_soft print(softmax([3.0, 1.0, 0.2])) # 52 Write a python program to calculate the slope of a line given two points def slope_of_a_line(x1, x2, y1, y2): del_x = x2 - x1 del_y = y2 - y1 return float(del_y) / del_x print(slope_of_a_line(0, 10, 0, 10)) # 53 write a python function which checks if a number is a perfect square import math def is_perfect_square(num): sq_root = round(math.sqrt(num)) if num == sq_root ** 2: return True else: return False # 54 Write a python function that implements the ReLU function def relu(arr): return [x if x > 0 else 0 for x in arr] # 55 Write a python program that pads a given python list to a given length at the end and prints the modified list def pad_arr_end(arr, pad_len): pad_arr = [0] * (pad_len - len(arr)) return arr.extend(pad_arr) tmp = [1, 2, 3, 4, 5] pad_arr_end(tmp, 10) print(tmp) # 55 Write a python program that pads a given python list to a given length at the start and prints the modified list def pad_arr_start(arr, pad_len): pad_arr = [0] * (pad_len - len(arr)) pad_arr.extend(arr) return pad_arr tmp = [1, 2, 3, 4, 5] x = pad_arr_start(tmp, 10) print(x) # 56 write a python function to implement the sigmoid activation function import math def sigmoid(x): return 1 / (1 + math.exp(-x)) # 57 write a python function to implement the tanh activation function import math def tanh(x): return (math.exp(2 * x) - 1) / (math.exp(2 * x) + 1) # 58 Write a python program that calculates and prints the area of an ellipse import math class Ellipse: def __init__(self, a, b): self.major_axis = b self.minor_axis = a def area(self): return math.pi * self.major_axis * self.minor_axis ellipse = Ellipse(2, 10) print(ellipse.area()) # 59 Write a python program that adds a time delay between a loop that prints numbers between 0 and 10 import time def print_loop_with_delay(sec): for i in range(0, 10): time.sleep(sec) print(i) # 60 Write a function to return the the unique tokens from a string def unique_tokens(st): return set(st) # 61 write a python function to return the standard deviation of a list of numbers import math def st_dev(arr): avg = sum(arr) / len(arr) ss_dev = sum([(x - avg) ** 2 for x in arr]) return math.sqrt(ss_dev / (len(arr) - 1)) # 62 write a python function to return mode of the data import statistics def mode(arr): return statistics.mode(arr) # 63 Write a python function which returns true if all the numbers in a list negative, else return False def are_all_negative(arr): filt_arr = list(filter(lambda x: x < 0, arr)) if len(filt_arr) == len(arr): return True else: return False # 64 Write a python function that checks if all the numbers in a list sum upto 1. Returns False otherwise def sum_upto_one(arr): arr_sum = sum(arr) try: assert float(arr_sum) == 1.0 return True except AssertionError: return False # 65 write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. import random print(random.choice([i for i in range(11) if i % 2 == 0])) # 66 write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. import random print(random.choice([i for i in range(201) if i % 5 == 0 and i % 7 == 0])) # 67 write a program to generate a list with 5 random numbers between 100 and 200 inclusive. import random print(random.sample(range(100), 5)) # 68 write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. import random print(random.sample([i for i in range(100, 201) if i % 2 == 0], 5)) # 69 write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. import random print(random.sample([i for i in range(1, 1001) if i % 5 == 0 and i % 7 == 0], 5)) # 70 write a program to randomly print a integer number between 7 and 15 inclusive. import random print(random.randrange(7, 16)) # 71 write a python function to count the length of the string def len_str(st): return len(st) # 72 write a program to print the running time of execution of "1+1" for 100 times. from timeit import Timer t = Timer("for i in range(100):1+1") print(t.timeit()) # 73 write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3, 6, 7, 8] shuffle(li) print(li) # 74 write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3, 6, 7, 8] shuffle(li) print(li) # 75 write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. subjects = ["I", "You"] verbs = ["Play", "Love"] objects = ["Hockey", "Football"] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print(sentence) # 76 Write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. li = [5, 6, 77, 45, 22, 12, 24] li = [x for x in li if x % 2 != 0] print(li) # 77 By using list comprehension, write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. li = [12, 24, 35, 70, 88, 120, 155] li = [x for x in li if x % 5 != 0 and x % 7 != 0] print(li) # 78 By using list comprehension, write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. li = [12, 24, 35, 70, 88, 120, 155] li = [x for (i, x) in enumerate(li) if i % 2 != 0] print(li) # 79 By using list comprehension, write a program generate a 3*5*8 3D array whose each element is 0. array = [[[0 for col in range(8)] for col in range(5)] for row in range(3)] print(array) # 80 By using list comprehension, write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. li = [12, 24, 35, 70, 88, 120, 155] li = [x for (i, x) in enumerate(li) if i not in (0, 4, 5)] print(li) # 81 By using list comprehension, write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. li = [12, 24, 35, 24, 88, 120, 155] li = [x for x in li if x != 24] print(li) # 82 With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. set1 = set([1, 3, 6, 78, 35, 55]) set2 = set([12, 24, 35, 24, 88, 120, 155]) set1 &= set2 li = list(set1) print(li) # 83 With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. def removeDuplicate(li): newli = [] seen = set() for item in li: if item not in seen: seen.add(item) newli.append(item) return newli li = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155] print(removeDuplicate(li)) # 84 Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. class Person(object): def getGender(self): return "Unknown" class Male(Person): def getGender(self): return "Male" class Female(Person): def getGender(self): return "Female" aMale = Male() aFemale = Female() print(aMale.getGender()) print(aFemale.getGender()) # 85 write a program which count and print the numbers of each character in a string dic = {} s = "JRR Tolkien" for s in s: dic[s] = dic.get(s, 0) + 1 print("\n".join(["%s,%s" % (k, v) for k, v in dic.items()])) # 86 write a program which accepts a string and counts the number of words in it def num_of_words(st): return len(st.split()) # 87 write a function which accepts a string prints the characters that have even indexes. def every_alternate_char(s): s = s[::2] return s # 88 write a program which prints all permutations of [1,2,3] import itertools print(list(itertools.permutations([1, 2, 3]))) # 89 Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? def solve(numheads, numlegs): ns = "No solutions!" for i in range(numheads + 1): j = numheads - i if 2 * i + 4 * j == numlegs: return i, j return ns, ns # 90 Write a python function to round down a given decimal number import math def apply_ceil(num): return math.ceil(x) # 91 Write a python function to round up a given decimal number import math def apply_floor(num): return math.floor(num) # 92 Write a python function to round off a given decimal number def apply_round(num): return round(num) # 93 write a python function to find One's compliment of a number import math def OnesComplement(num): bits = int(math.floor(math.log(num) / math.log(2)) + 1) return ((1 << bits) - 1) ^ num # 94 write a python function that takes in a decimal number and prints it's binary representation def dec2bin(num): print(format(num, "b")) # 95 write a python function that accepts a binary string and converts it into an equivalent decimal number def bin2dec(num): return int(num, 2) # 96 write a python function that takes a number and returns an array of the number duplicated n times def duplicate_array(num, n): num = [num] * n return num # 97 write a python function that accepts a number, and returns the nearest square number import math def nearest_square(n): upp = math.floor(math.sqrt(n)) low = math.floor(math.sqrt(n)) upp_diff = upp ** 2 - n low_diff = n - low ** 2 if upp_diff > low_diff: return upp else: return low # 98 write a python function that calculates the midpoint between two numbers def midpoint(a, b): lar = b if b > a else a sm = a if b > a else b return float(lar + sm) / 2 # 99 write a python function that accepts a string and reverses it def reverse(st): return st[::-1] # 100 write a python program that checks if a string is a pallindrome def is_palindrome(st): st = st.lower() rev_st = st[::-1] try: assert rev_st == st return True except AssertionError: return False st = "Nitin" print(is_palindrome(st)) # coding: utf-8 # write a python program to add two numbers num1 = 5465461 num2 = 8765468 sum = num1 + num2 print(f'Sum: {sum}') # write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum # write a program to find and print the largest among three numbers num1 = 123 num2 = 125 num3 = 148 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}') # write a program to find length of list l = [1,2,3,4,5] print(len(l)) # write a function to find length of list def get_list_length(l): return len(l) # write a program to convert tuple to list t = (1,2,4,5,6) print(f'list:{list(t)}') # write a function to convert tuple to list def convert_tuple2list(t): return list(t) # write a program to convert list to tuple l = ['a',4,5] print(f'tuple:{tuple(l)}') # write a function to convert list to tuple def list2tuple(l): return tuple(l) # write a function to find length of list def tuple_lenght(t): return len(t) # write a program to find length of list t = 1,2,3,4,5 print(f'tuple length: {len(t)}') # write a program to concat two list l1 = [1,2,3] l2 = [4,5,6] print(f'sum : {l1 + l2}') # write a functiom to concat two list l1 = [1,2,3] l2 = [4,5,6] def list_concat(l1,l2): return l1 + l2 # write Python code to convert Celsius scale to Fahrenheit scale def Cel_To_Fah(n): return (n*1.8)+32 n = 20 print(int(Cel_To_Fah(n))) # write Python program to convert temperature from Fahrenheit to Kelvin def Fahrenheit_to_Kelvin(F): return 273.5 + ((F - 32.0) * (5.0/9.0)) F = 100 print("Temperature in Kelvin ( K ) = {:.3f}" .format(Fahrenheit_to_Kelvin( F ))) # write Function to convert temperature from degree Celsius to Kelvin def Celsius_to_Kelvin(C): return (C + 273.15) C = 100 print("Temperature in Kelvin ( K ) = ", Celsius_to_Kelvin(C)) # write Python code to convert radian to degree def Convert(radian): pi = 3.14159 degree = radian * (180/pi) return degree radian = 5 print("degree =",(Convert(radian))) # write Function to Rotate the matrix by 180 degree def rotateMatrix(mat): N = 3 i = N - 1; while(i >= 0): j = N - 1; while(j >= 0): print(mat[i][j], end = " "); j = j - 1; print(); i = i - 1; # Driven code mat = [[1, 2, 3], [ 4, 5, 6 ], [ 7, 8, 9 ]]; rotateMatrix(mat); # write Function to left rotate n by d bits def leftRotate(n, d): INT_BITS = 32 return (n << d)|(n >> (INT_BITS - d)) n = 16 d = 2 print("Left Rotation of",n,"by",d,"is",end=" ") print(leftRotate(n, d)) # write Function to right rotate n by d bits def rightRotate(n, d): INT_BITS = 32 return (n >> d)|(n << (INT_BITS - d)) & 0xFFFFFFFF n = 16 d = 2 print("Right Rotation of",n,"by",d,"is",end=" ") print(rightRotate(n, d)) # Function to rotate string left and right by d length def rotate(input,d): Lfirst = input[0 : d] Lsecond = input[d :] Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] print ("Left Rotation : ", (Lsecond + Lfirst) ) print ("Right Rotation : ", (Rsecond + Rfirst)) input = 'GeeksforGeeks' d=2 rotate(input,d) # write Python3 code to demonstrate to create a substring from a string ini_string = 'xbzefdgstb' print ("initial_strings : ", ini_string) sstring_strt = ini_string[:2] sstring_end = ini_string[3:] print ("print resultant substring from start", sstring_strt) print ("print resultant substring from end", sstring_end) # write Python3 code to demonstrate to create a substring from string ini_string = 'xbzefdgstb' print ("initial_strings : ", ini_string) sstring_alt = ini_string[::2] sstring_gap2 = ini_string[::3] print ("print resultant substring from start", sstring_alt) print ("print resultant substring from end", sstring_gap2) # write Python3 code to demonstrate to create a substring from string ini_string = 'xbzefdgstb' sstring = ini_string[2:7:2] print ('resultant substring{sstring}') # Program to cyclically rotate an array by one def cyclicRotate(input): print ([input[-1]] + input[0:-1]) # write Python3 code to demonstrate list slicing from K to end using None test_list = [5, 6, 2, 3, 9] K = 2 res = test_list[K : None] print (f"The sliced list is :{str(res)} " ) # write Python code t get difference of two lists Using set() def Diff(li1, li2): return (list(list(set(li1)-set(li2)) + list(set(li2)-set(li1)))) li1 = [10, 15, 20, 25, 30, 35, 40] li2 = [25, 40, 35] print(Diff(li1, li2)) # write a program for round for integers integer = 18 print(f"Round off value : {round(integer , -1)}") # write a program for floating pointwrite a program print(f"Round off value : {round(51.6)}") # write Program to demonstrate conditional operator a, b = 10, 20 min = a if a < b else b print(min) # write Python program to demonstrate ternary operator using tuples, Dictionary and lambda a, b = 10, 20 print( (b, a) [a < b] ) print({True: a, False: b} [a < b]) print((lambda: b, lambda: a)[a < b]()) # write a python program using "any" function print (any([False, True, False, False])) # write a python program using "all" function print (all([False, True, False, False])) #write Python3 code to demonstrate working of Check if tuple has any None value using any() + map() + lambda test_tup = (10, 4, 5, 6, None) res = any(map(lambda ele: ele is None, test_tup)) print("Does tuple contain any None value ? : " + str(res)) # write Python3 code to demonstrate working of Check if tuple has any None value using not + all() test_tup = (10, 4, 5, 6, None) print("The original tuple : " + str(test_tup)) res = not all(test_tup) print("Does tuple contain any None value ? : " + str(res)) # write Python3 code to demonstrate working of Sort tuple list by Nth element of tuple using sort() + lambda test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] print("The original list is : " + str(test_list)) N = 1 test_list.sort(key = lambda x: x[N]) print("List after sorting tuple by Nth index sort : " + str(test_list)) # write Python program to demonstrate printing of complete multidimensional list row by row. a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] for record in a: print(record) # write Python program to demonstrate that we can access multidimensional list using square brackets a = [ [2, 4, 6, 8 ], [ 1, 3, 5, 7 ], [ 8, 6, 4, 2 ], [ 7, 5, 3, 1 ] ] for i in range(len(a)) : for j in range(len(a[i])) : print(a[i][j], end=" ") print() # write a program for Adding a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a.append([5, 10, 15, 20, 25]) print(a) #write a program for Extending a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a[0].extend([12, 14, 16, 18]) print(a) # write a program for Reversing a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a[2].reverse() print(a) # write a Python3 program to demonstrate the use of replace() method string = "geeks for geeks geeks geeks geeks" print(string.replace("geeks", "Geeks")) print(string.replace("geeks", "GeeksforGeeks", 3)) # write Python3 code to demonstrate working of Rear word replace in String using split() + join() test_str = "GFG is good" print("The original string is : " + test_str) rep_str = "best" res = " ".join(test_str.split(' ')[:-1] + [rep_str]) print("The String after performing replace : " + res) # write Python3 code to demonstrate working of Rear word replace in String using rfind() + join() test_str = "GFG is good" print("The original string is : " + test_str) rep_str = "best" res = test_str[: test_str.rfind(' ')] + ' ' + rep_str print("The String after performing replace : " + res) # write Python3 code to demonstrate Shift from Front to Rear in List using list slicing and "+" operator test_list = [1, 4, 5, 6, 7, 8, 9, 12] print ("The original list is : " + str(test_list)) test_list = test_list[1 :] + test_list[: 1] print ("The list after shift is : " + str(test_list)) # Python3 code to demonstrate Shift from Front to Rear in List using insert() + pop() test_list = [1, 4, 5, 6, 7, 8, 9, 12] print ("The original list is : " + str(test_list)) test_list.insert(len(test_list) - 1, test_list.pop(0)) print ("The list after shift is : " + str(test_list)) # write Python3 code to demonstrate working of Sort by Rear Character in Strings List Using sort() def get_rear(sub): return sub[-1] test_list = ['gfg', 'is', 'best', 'for', 'geeks'] print("The original list is : " + str(test_list)) test_list.sort(key = get_rear) print("Sorted List : " + str(test_list)) # write Python3 code to demonstrate working of Sort by Rear Character in Strings List Using sorted() + lambda test_list = ['gfg', 'is', 'best', 'for', 'geeks'] print("The original list is : " + str(test_list)) res = sorted(test_list, key = lambda sub : sub[-1]) print("Sorted List : " + str(res)) # write Python3 code to demonstrate Remove Rear K characters from String List using list comprehension + list slicing test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils'] print("The original list : " + str(test_list)) K = 4 res = [sub[ : len(sub) - K] for sub in test_list] print("The list after removing last characters : " + str(res)) # write Python3 code to demonstrate Remove Rear K characters from String List using map() + lambda test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils'] print("The original list : " + str(test_list)) K = 4 res = list(map(lambda i: i[ : (len(i) - K)], test_list)) print("The list after removing last characters : " + str(res)) # write Python3 code to demonstrate Kth Non-None String from Rear using next() + list comprehension test_list = ["", "", "Akshat", "Nikhil"] print("The original list : " + str(test_list)) K = 2 test_list.reverse() test_list = iter(test_list) for idx in range(0, K): res = next(sub for sub in test_list if sub) print("The Kth non empty string from rear is : " + str(res)) # write Python code to demonstrate Kth Non-None String from Rear using filter() test_list = ["", "", "Akshat", "Nikhil"] print("The original list : " + str(test_list)) K = 2 res = list (filter(None, test_list))[-K] print("The Kth non empty string from rear is : " + str(res)) # write a program Creating a Dictionary with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # program Creating a Dictionary with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) # write a program Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # write a program Creating a Dictionary with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) # write a program Creating a Dictionary with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict) # write a program Creating a Nested Dictionary as shown in the below image Dict = {1: 'Geeks', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}} print(Dict) # write a program Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} print("Accessing a element using get:") print(Dict.get(3)) #write a python Creating a Dictionary and Accessing element using key Dict = {'Dict1': {1: 'Geeks'}, 'Dict2': {'Name': 'For'}} print(Dict['Dict1']) print(Dict['Dict1'][1]) print(Dict['Dict2']['Name']) # write a program that uses delete function on Dictionary Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', 'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, 'B' : {1 : 'Geeks', 2 : 'Life'}} print("Initial Dictionary: ") print(Dict) del Dict[6] print("\nDeleting a specific key: ") print(Dict) del Dict['A'][2] print("\nDeleting a key from Nested Dictionary: ") print(Dict) # write a rpogram Deleting an arbitrary key using popitem() function in dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} pop_ele = Dict.popitem() print("\nDictionary after deletion: " + str(Dict)) print("The arbitrary pair returned is: " + str(pop_ele)) # write a program for Deleting entire Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Dict.clear() print("\nDeleting Entire Dictionary: ") print(Dict) # write a Python3 code to demonstrate set difference in dictionary list using list comprehension test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ] test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}] print ("The original list 1 is : " + str(test_list1)) print ("The original list 2 is : " + str(test_list2)) res = [i for i in test_list1 if i not in test_list2] + [j for j in test_list2 if j not in test_list1] print ("The set difference of list is : " + str(res)) # write Python code to demonstrate sort a list of dictionary where value date is in string ini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] print ("initial list : ", str(ini_list)) ini_list.sort(key = lambda x:x['d.o.b']) print ("result", str(ini_list)) # write a Python3 code to demonstrate working of Convert Dictionaries List to Order Key Nested dictionaries Using loop + enumerate() test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}] print("The original list : " + str(test_list)) res = dict() for idx, val in enumerate(test_list): res[idx] = val print("The constructed dictionary : " + str(res)) # write Python3 code to demonstrate working of Convert Dictionaries List to Order Key Nested dictionaries Using dictionary comprehension + enumerate() test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}] print("The original list : " + str(test_list)) res = {idx : val for idx, val in enumerate(test_list)} print("The constructed dictionary : " + str(res)) # write Python3 code to demonstrate working of Segregating key's value in list of dictionaries Using generator expression test_list = [{'gfg' : 1, 'best' : 2}, {'gfg' : 4, 'best': 5}] print("The original list : " + str(test_list)) res = [tuple(sub["gfg"] for sub in test_list), tuple(sub["best"] for sub in test_list)] print("Segregated values of keys are : " + str(res)) # write Python3 code to demonstrate working of Segregating key's value in list of dictionaries Using zip() + map() + values() test_list = [{'gfg' : 1, 'best' : 2}, {'gfg' : 4, 'best': 5}] print("The original list : " + str(test_list)) res = list(zip(*map(dict.values, test_list))) print("Segregated values of keys are : " + str(res)) # write a Python3 code to demonstrate working of Sort dictionaries list by Key's Value list index Using sorted() + lambda test_list = [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}] print("The original list : " + str(test_list)) K = "Gfg" idx = 2 res = sorted(test_list, key = lambda ele: ele[K][idx]) print("The required sort order : " + str(res)) # write Python3 code to demonstrate working of Sort dictionaries list by Key's Value list index Using sorted() + lambda (Additional parameter in case of tie) test_list = [{"Gfg" : [6, 7, 9], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}] print("The original list : " + str(test_list)) K = "Gfg" idx = 2 K2 = "best" res = sorted(sorted(test_list, key = lambda ele: ele[K2]), key = lambda ele: ele[K][idx]) print("The required sort order : " + str(res)) # write Python3 code to demonstrate working of Convert List of Dictionaries to List of Lists Using loop + enumerate() test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20}, {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10}, {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}] print("The original list is : " + str(test_list)) res = [] for idx, sub in enumerate(test_list, start = 0): if idx == 0: res.append(list(sub.keys())) res.append(list(sub.values())) else: res.append(list(sub.values())) print("The converted list : " + str(res)) # write a Python3 code to demonstrate working of Convert List of Dictionaries to List of Lists Using list comprehension test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20}, {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10}, {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}] print("The original list is : " + str(test_list)) res = [[key for key in test_list[0].keys()], *[list(idx.values()) for idx in test_list ]] print("The converted list : " + str(res)) # write a Python code demonstrate the working of sorted() with lambda lis = [{ "name" : "Nandini", "age" : 20}, { "name" : "Manjeet", "age" : 20 }, { "name" : "Nikhil" , "age" : 19 }] print ("The list printed sorting by age: ") print (sorted(lis, key = lambda i: i['age'])) print ("\r") # write a Python3 code to demonstrate working of Extract dictionaries with values sum greater than K test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 5, "is": 8, "best" : 1}, {"Gfg" : 3, "is": 7, "best" : 6}, {"Gfg" : 3, "is": 7, "best" : 5}] print("The original list : " + str(test_list)) K = 15 res = [] for sub in test_list: sum = 0 for key in sub: sum += sub[key] if sum > K: res.append(sub) print("Dictionaries with summation greater than K : " + str(res)) # write Python3 program for illustration of values() method of dictionary dictionary = {"raj": 2, "striver": 3, "vikram": 4} print(dictionary.values()) # write Python program to illustrate enumerate function l1 = ["eat","sleep","repeat"] s1 = "geek" obj1 = enumerate(l1) obj2 = enumerate(s1) print ("Return type:",type(obj1) ) print( list(enumerate(l1)) ) print( list(enumerate(s1,2)) ) # write Python program to illustrate enumerate function in loops l1 = ["eat","sleep","repeat"] for count,ele in enumerate(l1,100): print (count,ele ) # write Python3 code to demonstrate working of Merge Python key values to list Using setdefault() + loop test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6}, {'it' : 5, 'is' : 7, 'best' : 8}, {'CS' : 10}] print("The original list is : " + str(test_list)) res = {} for sub in test_list: for key, val in sub.items(): res.setdefault(key, []).append(val) print("The merged values encapsulated dictionary is : " + str(res)) # write Python3 code to demonstrate working of Merge Python key values to list Using list comprehension + dictionary comprehension test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6}, {'it' : 5, 'is' : 7, 'best' : 8}, {'CS' : 10}] print("The original list is : " + str(test_list)) res = {key: list({sub[key] for sub in test_list if key in sub}) for key in {key for sub in test_list for key in sub}} print("The merged values encapsulated dictionary is : " + str(res)) # write Python3 code to demonstrate working of Merge List value Keys to Matrix Using loop + pop() test_dict = {'gfg' : [4, 5, 6], 'is' : [8, 8, 9], 'CS' : [1, 3, 8], 'Maths' : [1, 2]} print("The original dictionary : " + str(test_dict)) que_list = ['gfg', 'CS', 'Maths'] new_data = [test_dict.pop(ele) for ele in que_list] test_dict["merge_key"] = new_data print("The dictionary after merging : " + str(test_dict)) # write Python code to convert string to list def Convert_1(string): li = list(string.split(" ")) return li str1 = "Geeks for Geeks" print(Convert(str1)) # Python code to convert string to list def Convert_2(string): li = list(string.split("-")) return li str1 = "Geeks-for-Geeks" print(Convert(str1)) # write Python code to convert string to list character-wise def Convert_3(string): list1=[] list1[:0]=string return list1 str1="ABCD" print(Convert(str1)) # write Python3 code to demonstrate convert list of strings to list of tuples Using map() + split() + tuple() test_list = ['4, 1', '3, 2', '5, 3'] print("The original list : " + str(test_list)) res = [tuple(map(int, sub.split(', '))) for sub in test_list] print("The list after conversion to tuple list : " + str(res)) # write Python3 code to demonstrate convert list of strings to list of tuples Using map() + eval test_list = ['4, 1', '3, 2', '5, 3'] print("The original list : " + str(test_list)) res = list(map(eval, test_list)) print("The list after conversion to tuple list : " + str(res)) # write Python3 code to demonstrate Combining tuples in list of tuples Using list comprehension test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] print("The original list : " + str(test_list)) res = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] print("The list tuple combination : " + str(res)) # write Python3 code to demonstrate working of Add list elements to tuples list Using list comprehension + "+" operator test_list = [(5, 6), (2, 4), (5, 7), (2, 5)] print("The original list is : " + str(test_list)) sub_list = [7, 2, 4, 6] res = [sub + tuple(sub_list) for sub in test_list] print("The modified list : " + str(res)) # write Python3 code to demonstrate working of Add list elements to tuples list Using list comprehension + "*" operator test_list = [(5, 6), (2, 4), (5, 7), (2, 5)] print("The original list is : " + str(test_list)) sub_list = [7, 2, 4, 6] res = [(*sub, *sub_list) for sub in test_list] print("The modified list : " + str(res)) # write Python3 code to demonstrate conversion of list of tuple to list of list using list comprehension + join() test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] print ("The original list is : " + str(test_list)) res = [''.join(i) for i in test_list] print ("The list after conversion to list of string : " + str(res)) # write Python3 code to demonstrate conversion of list of tuple to list of list using map() + join() test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] print ("The original list is : " + str(test_list)) res = list(map(''.join, test_list)) print ("The list after conversion to list of string : " + str(res)) # write Python3 code to demonstrate working of Concatenating tuples to nested tuples using + operator + ", " operator during initialization test_tup1 = (3, 4), test_tup2 = (5, 6), print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) res = test_tup1 + test_tup2 print("Tuples after Concatenating : " + str(res)) # write Python3 code to demonstrate working of Concatenating tuples to nested tuples Using ", " operator during concatenation test_tup1 = (3, 4) test_tup2 = (5, 6) print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) res = ((test_tup1, ) + (test_tup2, )) print("Tuples after Concatenating : " + str(res)) # write Python code to demonstrate to remove the tuples if certain criteria met ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)] print("intial_list", str(ini_tuple)) result = [i for i in ini_tuple if i[1] <= 100] print ("Resultant tuple list: ", str(result)) # write Python code to demonstrate to remove the tuples if certain criteria met ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)] print("intial_list", str(ini_tuple)) result = list(filter(lambda x: x[1] <= 100, ini_tuple)) print ("Resultant tuple list: ", str(result)) # Python code to demonstrate to remove the tuples if certain criteria met ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)] print("intial_list", str(ini_tuple)) result = [] for i in ini_tuple: if i[1] <= 100: result.append(i) print ("Resultant tuple list: ", str(result)) # write Python code to demonstrate to remove the tuples if certain criteria met ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)] print("intial_list", str(ini_tuple)) result = [] for i in ini_tuple: if i[1] <= 100: result.append(i) print ("Resultant tuple list: ", str(result)) # write Python code to remove all strings from a list of tuples listOfTuples = [('string', 'Geeks'), (2, 225), (3, '111'), (4, 'Cyware'), (5, 'Noida')] output = [tuple(j for j in i if not isinstance(j, str)) for i in listOfTuples] print(output) # write Python3 code to demonstrate working of Extract Tuples with all Numeric Strings Using all() + list comprehension + isdigit() test_list = [("45", "86"), ("Gfg", "1"), ("98", "10"), ("Gfg", "Best")] print("The original list is : " + str(test_list)) res = [sub for sub in test_list if all(ele.isdigit() for ele in sub)] print("Filtered Tuples : " + str(res)) # write Python3 code to demonstrate working of Extract Tuples with all Numeric Strings Using lambda + filter() + isdigit() test_list = [("45", "86"), ("Gfg", "1"), ("98", "10"), ("Gfg", "Best")] print("The original list is : " + str(test_list)) res = list(filter(lambda sub : all(ele.isdigit() for ele in sub), test_list)) print("Filtered Tuples : " + str(res)) # Python3 code to demonstrate working of Extract String till Numeric Using isdigit() + index() + loop test_str = "geeks4geeks is best" print("The original string is : " + str(test_str)) temp = 0 for chr in test_str: if chr.isdigit(): temp = test_str.index(chr) print("Extracted String : " + str(test_str[0 : temp])) 1. # write a python function to check user provided number is prime or not and print the result def primeornot(num): if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number") primeornot(7) 2. # write a python program to swap two numbers and print it num1 = 5 num2 = 10 temp = num1 num1 = num2 num2 = temp print("The value of num1 after swapping: {}".format(num1)) print("The value of num2 after swapping: {}".format(num2)) 3. # write a python function to add user provided list and return the result def addlist(list1,list2): result = list1+list2 return result answer = addlist(['cat','dog'],['samsung','oneplus']) 4. # write a python function to reverse user provided list and return the result def reverselist(inlist): inlist = inlist[::-1] return inlist result = reverselist([1,2]) 5. # write a python function to find the factorial of the user provided number and print the result def findfactorial(num): factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num+1): factorial = factorial*i print("The factorial of",num,"is",factorial) findfactorial(3) 6. # write a python function to find the largest element in an array and return the result def largest(arr): max = arr[0] n = len(arr) for i in range(1,n): if arr[i] > max: max = arr[i] return max largest([1,20,3]) 7. # write a python function to check if a string is palindrome or not and print the result def isPalindrome(s): if (s == s[::-1]): print("Given string is palindrome") else: print("Given string is not palindrome") s = "malayalam" isPalindrome(s) 8. #Write a function to convert Kilometers to Miles def Kilometers_to_Miles(km): conv_fac = 0.621371 miles = km * conv_fac return miles 9. #Write a function to convert Miles to Kilometers def Miles_to_Kilometers(m): conv_fac = 0.621371 kilometers = m / conv_fac return kilometers 10. #Write a function to Convert Celsius To Fahrenheit def Celsius_To_Fahrenheit(c): fahrenheit = (c * 1.8) + 32 return fahrenheit 11. #Write a fucntion to convert Fahrenheit to Celsius def Fahrenheit_to_Celsius(f): celsius = (f - 32) / 1.8 return celsius 12. #Convert Decimal to Binary, Octal and Hexadecimal dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.") 13. #Find ASCII Value of Character c = 'p' print("The ASCII value of '" + c + "' is", ord(c)) 14. #Multiply Two Matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) # Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print fact(x) # With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. n=int(raw_input()) d=dict() for i in range(1,n+1): d[i]=i*i print d # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. values=raw_input() l=values.split(",") t=tuple(l) print l print t # Define a class which has at least two methods: getString: to get a string from console input class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = raw_input() strObj = InputOutString() strObj.getString() # Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] import math c=50 h=30 value = [] items=[x for x in raw_input().split(',')] for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print ','.join(value) # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] colNum=dimensions[1] multilist = [[0 for col in range(colNum)] for row in range(rowNum)] for row in range(rowNum): for col in range(colNum): multilist[row][col]= row*col print multilist # Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) # Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence # Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) # Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. value = [] items=[x for x in raw_input().split(',')] for p in items: intp = int(p, 2) if not intp%5: value.append(p) print ','.join(value) # Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values) # Write a program that accepts a sentence and calculate the number of letters and digits. s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. s = raw_input() 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 "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"] # Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print n1+n2+n3+n4 # Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) # Write a program that computes the net amount of a bank account based a transaction log from console input. netAmount = 0 while True: s = raw_input() if not s: break values = s.split(" ") operation = values[0] amount = int(values[1]) if operation=="D": netAmount+=amount elif operation=="W": netAmount-=amount else: pass print netAmount Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. def putNumbers(n): i = 0 while ilen2: print s1 elif len2>len1: print s2 else: print s1 print s2 # Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". def checkValue(n): if n%2 == 0: print "It is an even number" else: print "It is an odd number" # Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. def printDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print d # Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. def printDict(): d=dict() for i in range(1,21): d[i]=i**2 print d # Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print v # Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for k in d.keys(): print k # Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). def printList(): li=list() for i in range(1,21): li.append(i**2) print li # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print li[:5] # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print li[-5:] # Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. def printList(): li=list() for i in range(1,21): li.append(i**2) print li[5:] # Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). def printTuple(): li=list() for i in range(1,21): li.append(i**2) print tuple(li) # With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. tp=(1,2,3,4,5,6,7,8,9,10) tp1=tp[:5] tp2=tp[5:] print tp1 print tp2 # Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). tp=(1,2,3,4,5,6,7,8,9,10) li=list() for i in tp: if tp[i]%2==0: li.append(tp[i]) tp2=tuple(li) print tp2 # Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". s= raw_input() if s=="yes" or s=="YES" or s=="Yes": print "Yes" else: print "No" # Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers # Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. li = [1,2,3,4,5,6,7,8,9,10] squaredNumbers = map(lambda x: x**2, li) print squaredNumbers # Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) print evenNumbers # Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). evenNumbers = filter(lambda x: x%2==0, range(1,21)) print evenNumbers # Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). squaredNumbers = map(lambda x: x**2, range(1,21)) print squaredNumbers # Define a class named American which has a static method called printNationality. class American(object): @staticmethod def printNationality(): print "America" anAmerican = American() anAmerican.printNationality() American.printNationality() # Define a class named American and its subclass NewYorker. class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker() print anAmerican print aNewYorker # Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class Circle(object): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 aCircle = Circle(2) print aCircle.area() # Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width aRectangle = Rectangle(2,10) print aRectangle.area() # Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. class Shape(object): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, l): Shape.__init__(self) self.length = l def area(self): return self.length*self.length aSquare= Square(3) print aSquare.area() # raise a RuntimeError exception. raise RuntimeError('something wrong') # Write a function to compute 5/0 and use try/except to catch the exceptions. def throws(): return 5/0 try: throws() except ZeroDivisionError: print "division by zero!" except Exception, err: print 'Caught an exception' finally: print 'In finally block for cleanup' # Define a custom exception class which takes a string message as attribute. class MyError(Exception): def __init__(self, msg): self.msg = msg error = MyError("something wrong") # Assuming that we have some email addresses in the "username@companyname.com" format, write program to print the user name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) # Assuming that we have some email addresses in the "username@companyname.com" format, write program to print the company name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAddress) print r2.group(2) # Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. import re s = raw_input() print re.findall("\d+",s) # Print a unicode string "hello world". unicodeString = u"hello world!" print unicodeString # Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. s = raw_input() u = unicode( s ,"utf-8") print u # Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). n=int(raw_input()) sum=0.0 for i in range(1,n+1): sum += float(float(i)/(i+1)) print sum # Write a program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 def f(n): if n==0: return 0 else: return f(n-1)+100 n=int(raw_input()) print f(n) # Write a program to add an integer and [revious non negative integer Solution: def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) # Write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) # write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. def EvenGenerator(n): i=0 while i<=n: if i%2==0: yield i i+=1 n=int(raw_input()) values = [] for i in EvenGenerator(n): values.append(str(i)) print ",".join(values) # write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i n=int(raw_input()) values = [] for i in NumGenerator(n): values.append(str(i)) print ",".join(values) # write assert statements to verify that every number in the list [2,4,6,8] is even. li = [2,4,6,8] for i in li: assert i%2==0 # write a program which accepts basic mathematic expression from console and print the evaluation result. expression = raw_input() print eval(expression) # write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) # write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index # generate a random float where the value is between 10 and 100 using Python math module. import random print random.random()*100 # generate a random float where the value is between 5 and 95 using Python math module. import random print random.random()*100-5 # write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. import random print random.choice([i for i in range(11) if i%2==0]) # write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) # write a program to generate a list with 5 random numbers between 100 and 200 inclusive. import random print random.sample(range(100), 5) # write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. import random print random.sample([i for i in range(100,201) if i%2==0], 5) # write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) # write a program to randomly print a integer number between 7 and 15 inclusive. import random print random.randrange(7,16) # write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". import zlib s = 'hello world!hello world!hello world!hello world!' t = zlib.compress(s) print t print zlib.decompress(t) # write a program to print the running time of execution of "1+1" for 100 times. from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() # write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3,6,7,8] shuffle(li) print li # write a program to shuffle and print the list [3,6,7,8]. from random import shuffle li = [3,6,7,8] shuffle(li) print li # write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. subjects=["I", "You"] verbs=["Play", "Love"] objects=["Hockey","Football"] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print sentence # Write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li # By using list comprehension, write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li # By using list comprehension, write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li # By using list comprehension, write a program generate a 3*5*8 3D array whose each element is 0. array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array # By using list comprehension, write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] print li # By using list comprehension, write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li # With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print li # With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. def removeDuplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) # Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. class Person(object): def getGender( self ): return "Unknown" class Male( Person ): def getGender( self ): return "Male" class Female( Person ): def getGender( self ): return "Female" aMale = Male() aFemale= Female() print aMale.getGender() print aFemale.getGender() # write a program which count and print the numbers of each character in a string input by console. dic = {} s=raw_input() for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) # write a program which accepts a string from console and print it in reverse order. s=raw_input() s = s[::-1] print s # write a program which accepts a string from console and print the characters that have even indexes. s=raw_input() s = s[::2] print s # write a program which prints all permutations of [1,2,3] import itertools print list(itertools.permutations([1,2,3])) # Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2*i+4*j==numlegs: return i,j return ns,ns # write a program to count characters in a string st = "AmmarAdil" count = {} for a in st: if a in count: count[a]+=1 else: count[a] = 1 print('Count', count) # write a program to print count of vowels in a string st = "ammaradil" vowle = ['a', 'e', 'i', 'o', 'u'] count = 0 for s in st: if s in vowle: count = count+1 print("Count", count) # write program to convert string to upper case st = "ammar adil" upper_st = st.upper() print("Upper Case", upper_st) # write program to convert string to lower case st = "AMMAR ADIL" lower_st = st.lower() print("Lower Case", lower_st) # write a program to find union of 2 arrays a = {1, 2, 3, 4} b = {3, 4, 5, 6} union_both = a.union(b) print("Union", union_both) # write a program to find intersection a = {1, 2, 3, 4} b = {3, 4, 5, 6} intersection_both = a.intersection(b) print("Intersection", intersection_both) # write a program to create print array in beautiful format a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] for i in a: row = '|' for b in i: row = row + ' ' + str(b) print(row + ' ' + '|') # write a program to create zero matrix rows = 2 cols = 3 M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1].append(0.0) print("Zero Matrix") for i in range(rows): row = '|' for b in range(cols): row = row + ' ' + str(M[i][b]) print(row + ' ' + '|') # write a program to create identity matrix with dimension provided dim = 3 M = [] while len(M) < dim: M.append([]) while len(M[-1]) < dim: M[-1].append(0.0) for i in range(dim): M[i][i] = 1.0 print('Identity Matrix') for i in range(dim): row = '|' for b in range(dim): row = row + ' ' + str(M[i][b]) print(row + ' ' + '|') # Write a program to copy a given array M = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rows = len(M) cols = len(M[0]) MC = [] while len(MC) < rows: MC.append([]) while len(MC[-1]) < cols: MC[-1].append(0.0) for i in range(rows): for j in range(cols): MC[i][j] = M[i][j] print("Copied Array") for i in range(rows): row = '|' for b in range(cols): row = row + ' ' + str(MC[i][b]) print(row + ' ' + '|') # write a program to transpose a matrix M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] if not isinstance(M[0], list): M = [M] rows = len(M) cols = len(M[0]) MT = [] while len(MT) < dim: MT.append([]) while len(MT[-1]) < dim: MT[-1].append(0.0) for i in range(rows): for j in range(cols): MT[j][i] = M[i][j] print("Transpose Array") for i in range(rows): row = '|' for b in range(cols): row = row + ' ' + str(MT[i][b]) print(row + ' ' + '|') # write a program to add two matrix A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] rowsA = len(A) colsA = len(A[0]) rowsB = len(B) colsB = len(B[0]) if rowsA != rowsB or colsA != colsB: raise ArithmeticError('Matrices are NOT the same size.') C = [] while len(C) < rowsA: C.append([]) while len(C[-1]) < colsB: C[-1].append(0.0) for i in range(rowsA): for j in range(colsB): C[i][j] = A[i][j] + B[i][j] print("Added Array") for i in range(rowsA): row = '|' for b in range(colsA): row = row + ' ' + str(C[i][b]) print(row + ' ' + '|') # write a program to subtract two matrix A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] rowsA = len(A) colsA = len(A[0]) rowsB = len(B) colsB = len(B[0]) if rowsA != rowsB or colsA != colsB: raise ArithmeticError('Matrices are NOT the same size.') C = [] while len(C) < rowsA: C.append([]) while len(C[-1]) < colsB: C[-1].append(0.0) for i in range(rowsA): for j in range(colsB): C[i][j] = A[i][j] - B[i][j] print("Subtracted Array") for i in range(rowsA): row = '|' for b in range(colsA): row = row + ' ' + str(C[i][b]) print(row + ' ' + '|') # write a program to multiply two matrix rowsA = len(A) colsA = len(A[0]) rowsB = len(B) colsB = len(B[0]) if colsA != rowsB: raise ArithmeticError('Number of A columns must equal number of B rows.') C = [] while len(C) < rowsA: C.append([]) while len(C[-1]) < colsB: C[-1].append(0.0) for i in range(rowsA): for j in range(colsB): total = 0 for ii in range(colsA): total += A[i][ii] * B[ii][j] C[i][j] = total print("Multiplied Array") for i in range(rowsA): row = '|' for b in range(colsA): row = row + ' ' + str(C[i][b]) print(row + ' ' + '|') # write a program to join all items in a tuple into a string, using a hash character as separator myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) # write a program to remove spaces at the beginning and at the end of the string txt = " banana " x = txt.strip() print("of all fruits", x, "is my favorite") # write a program to remove the leading and trailing characters txt = ",,,,,rrttgg.....banana....rrr" x = txt.strip(",.grt") print(x) # write a program to split a string into a list where each line is a list item txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines() print(x) # write a program to find index of a word in given string txt = "Hello, welcome to my world." x = txt.index("welcome") print(x) # write a program to find ceil of a number import math number = 34.564 ce = math.ceil(number) print('Ceil', ce) # write a program to find absoluute number of a given number import math number = 34.564 fa = math.fabs(number) print('Fabs', fa) # write a program to find factorinal of a number import math number = 8 fa = math.factorial(number) print('Factorial', fa) # write a program to find exponential of a number import math number = 3 print('Exponential', math.exp(number)) # write a program to find log of a number import math num = 5 base = 7 print("Log_x_b", math.log(num, base)) # write a program to find cosine of a number import math num = 45 print("Cosine", math.cos(num)) # write a program to find sin of a number import math num = 45 print("Sin", math.sin(num)) # write a program to find tangent of a number import math num = 45 print("Tangent", math.tan(num)) # Write a program to print bit wise AND of two numbers a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = a & b # 12 = 0000 1100 print("AND", c) # Write a program to print bit wise OR of two numbers a = 60 b = 13 c = a | b print("OR", c) # Write a program to print bit wise XOR of two numbers a = 60 b = 13 c = a ^ b print("XOR", c) # Write a program to calculate Binary Ones Complement of a number a = 60 c = ~a print("Binary Ones Complement", c) # write a program to Binary Left Shift a number c = a << 2 print("Binary Left Shift", c) # write a program to Binary Right Shift a number c = a >> 2 print("Binary Right Shift", c)