code
stringlengths
63
8.54k
code_length
int64
11
747
# Python Program to Implement Depth-First Search on a Graph using Recursion class Graph: def __init__(self): # dictionary containing keys that map to the corresponding vertex object self.vertices = {}   def add_vertex(self, key): """Add a vertex with the given key to the graph.""" vertex = Vertex(key) self.vertices[key] = vertex   def get_vertex(self, key): """Return vertex object with the corresponding key.""" return self.vertices[key]   def __contains__(self, key): return key in self.vertices   def add_edge(self, src_key, dest_key, weight=1): """Add edge from src_key to dest_key with given weight.""" self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)   def does_edge_exist(self, src_key, dest_key): """Return True if there is an edge from src_key to dest_key.""" return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])   def __iter__(self): return iter(self.vertices.values())     class Vertex: def __init__(self, key): self.key = key self.points_to = {}   def get_key(self): """Return key corresponding to this vertex object.""" return self.key   def add_neighbour(self, dest, weight): """Make this vertex point to dest with given edge weight.""" self.points_to[dest] = weight   def get_neighbours(self): """Return all vertices pointed to by this vertex.""" return self.points_to.keys()   def get_weight(self, dest): """Get weight of edge from this vertex to dest.""" return self.points_to[dest]   def does_it_point_to(self, dest): """Return True if this vertex points to dest.""" return dest in self.points_to     def display_dfs(v): """Display DFS traversal starting at vertex v.""" display_dfs_helper(v, set())     def display_dfs_helper(v, visited): """Display DFS traversal starting at vertex v. Uses set visited to keep track of already visited nodes.""" visited.add(v) print(v.get_key(), end=' ') for dest in v.get_neighbours(): if dest not in visited: display_dfs_helper(dest, visited)     g = Graph() print('Menu') print('add vertex <key>') print('add edge <src> <dest>') print('dfs <vertex key>') print('display') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0] if operation == 'add': suboperation = do[1] if suboperation == 'vertex': key = int(do[2]) if key not in g: g.add_vertex(key) else: print('Vertex already exists.') elif suboperation == 'edge': src = int(do[2]) dest = int(do[3]) if src not in g: print('Vertex {} does not exist.'.format(src)) elif dest not in g: print('Vertex {} does not exist.'.format(dest)) else: if not g.does_edge_exist(src, dest): g.add_edge(src, dest) else: print('Edge already exists.')   elif operation == 'dfs': key = int(do[1]) print('Depth-first Traversal: ', end='') vertex = g.get_vertex(key) display_dfs(vertex) print()   elif operation == 'display': print('Vertices: ', end='') for v in g: print(v.get_key(), end=' ') print()   print('Edges: ') for v in g: for dest in v.get_neighbours(): w = v.get_weight(dest) print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w)) print()   elif operation == 'quit': break
382
# Write a Python program to reverse strings in a given list of string values using lambda. def reverse_strings_list(string_list): result = list(map(lambda x: "".join(reversed(x)), string_list)) return result colors_list = ["Red", "Green", "Blue", "White", "Black"] print("\nOriginal lists:") print(colors_list) print("\nReverse strings of the said given list:") print(reverse_strings_list(colors_list))
45
# Write a Python program to interleave multiple lists of the same length. Use itertools module. import itertools def interleave_multiple_lists(list1,list2,list3): result = list(itertools.chain(*zip(list1, list2, list3))) return result list1 = [100,200,300,400,500,600,700] list2 = [10,20,30,40,50,60,70] list3 = [1,2,3,4,5,6,7] print("Original list:") print("list1:",list1) print("list2:",list2) print("list3:",list3) print("\nInterleave multiple lists:") print(interleave_multiple_lists(list1,list2,list3))
45
# Write a Python program to filter the height and width of students, which are stored in a dictionary. def filter_data(students): result = {k: s for k, s in students.items() if s[0] >=6.0 and s[1] >=70} return result students = {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), 'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)} print("Original Dictionary:") print(students) print("\nHeight > 6ft and Weight> 70kg:") print(filter_data(students))
66
# rite a Python program to get the unique enumeration values. import enum class Countries(enum.Enum): Afghanistan = 93 Albania = 355 Algeria = 213 Andorra = 376 Angola = 244 India = 355 USA = 213 for result in Countries: print('{:15} = {}'.format(result.name, result.value))
44
# Write a NumPy program to generate a generic 2D Gaussian-like array. import numpy as np x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) d = np.sqrt(x*x+y*y) sigma, mu = 1.0, 0.0 g = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) print("2D Gaussian-like array:") print(g)
45
# Write a Python program to get hourly datetime between two hours. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nString representing the date, controlled by an explicit format string:") print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
36
# Python Program to Find Longest Common Substring using Dynamic Programming with Bottom-Up Approach def lcw(u, v): """Return length of an LCW of strings u and v and its starting indexes.   (l, i, j) is returned where l is the length of an LCW of the strings u, v where the LCW starts at index i in u and index j in v. """ # c[i][j] will contain the length of the LCW at the start of u[i:] and # v[j:]. c = [[-1]*(len(v) + 1) for _ in range(len(u) + 1)]   for i in range(len(u) + 1): c[i][len(v)] = 0 for j in range(len(v)): c[len(u)][j] = 0   lcw_i = lcw_j = -1 length_lcw = 0 for i in range(len(u) - 1, -1, -1): for j in range(len(v)): if u[i] != v[j]: c[i][j] = 0 else: c[i][j] = 1 + c[i + 1][j + 1] if length_lcw < c[i][j]: length_lcw = c[i][j] lcw_i = i lcw_j = j   return length_lcw, lcw_i, lcw_j     u = input('Enter first string: ') v = input('Enter second string: ') length_lcw, lcw_i, lcw_j = lcw(u, v) print('Longest Common Subword: ', end='') if length_lcw > 0: print(u[lcw_i:lcw_i + length_lcw])
192
# Write a Python program to copy of a deque object and verify the shallow copying process. import collections tup1 = (1,3,5,7,9) dq1 = collections.deque(tup1) dq2 = dq1.copy() print("Content of dq1:") print(dq1) print("dq2 id:") print(id(dq1)) print("\nContent of dq2:") print(dq2) print("dq2 id:") print(id(dq2)) print("\nChecking the first element of dq1 and dq2 are shallow copies:") print(id(dq1[0])) print(id(dq2[0]))
55
# Write a Python program to check whether 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))
35
# Print prime numbers from 1 to n using recursion def CheckPrime(i,num):    if num==i:        return 0    else:        if(num%i==0):            return 1        else:            return CheckPrime(i+1,num)n=int(input("Enter your Number:"))print("Prime Number Between 1 to n are: ")for i in range(2,n+1):    if(CheckPrime(2,i)==0):        print(i,end=" ")
38
# numpy.negative() in Python # Python program explaining # numpy.negative() function    import numpy as geek in_num = 10    print ("Input  number : ", in_num)      out_num = geek.negative(in_num)  print ("negative of input number : ", out_num) 
35
# Write a Python program to sort a list of elements using Cocktail shaker sort. def cocktail_shaker_sort(nums): for i in range(len(nums)-1, 0, -1): is_swapped = False for j in range(i, 0, -1): if nums[j] < nums[j-1]: nums[j], nums[j-1] = nums[j-1], nums[j] is_swapped = True for j in range(i): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] is_swapped = True if not is_swapped: return nums num1 = input('Input comma separated numbers:\n').strip() nums = [int(item) for item in num1.split(',')] print(cocktail_shaker_sort(nums))
79
# Write a Python program to Print Heart Pattern # define size n = even only n = 8    # so this heart can be made n//2 part left, # n//2 part right, and one middle line # i.e; columns m = n + 1 m = n+1    # loops for upper part for i in range(n//2-1):     for j in range(m):                    # condition for printing stars to GFG upper line         if i == n//2-2 and (j == 0 or j == m-1):             print("*", end=" ")                        # condition for printing stars to left upper         elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \                             or (j-i == m//2-n//2+3 and j > m//4)):             print("*", end=" ")                        # condition for printing stars to right upper         elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \                            or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)):             print("*", end=" ")                        # condition for printing spaces         else:             print(" ", end=" ")     print()    # loops for lower part for i in range(n//2-1, n):     for j in range(m):                    # condition for printing stars         if (i-j == n//2-1) or (i+j == n-1+m//2):             print('*', end=" ")                        # condition for printing GFG         elif i == n//2-1:                            if j == m//2-1 or j == m//2+1:                 print('G', end=" ")             elif j == m//2:                 print('F', end=" ")             else:                 print(' ', end=" ")                            # condition for printing spaces         else:             print(' ', end=" ")                    print()
233
# Write a Python program to compute the square of first N Fibonacci numbers, using map function and generate a list of the numbers. import itertools n = 10 def fibonacci_nums(x=0, y=1): yield x while True: yield y x, y = y, x + y print("First 10 Fibonacci numbers:") result = list(itertools.islice(fibonacci_nums(), n)) print(result) square = lambda x: x * x print("\nAfter squaring said numbers of the list:") print(list(map(square, result)))
70
# Write a Python program to access multiple elements of specified index from a given list. def access_elements(nums, list_index): result = [nums[i] for i in list_index] return result nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2] print ("Original list:") print(nums) list_index = [0,3,5,7,10] print("Index list:") print(list_index) print("\nItems with specified index of the said list:") print(access_elements(nums, list_index))
51
# Write a Python program to decode a run-length encoded given list. def decode(alist): def aux(g): if isinstance(g, list): return [(g[1], range(g[0]))] else: return [(g, [0])] return [x for g in alist for x, R in aux(g) for i in R] n_list = [[2, 1], 2, 3, [2, 4], 5, 1] print("Original encoded list:") print(n_list) print("\nDecode a run-length encoded said list:") print(decode(n_list))
62
# Python Program to Sort the List According to the Second Element in Sublist a=[['A',34],['B',21],['C',26]] for i in range(0,len(a)): for j in range(0,len(a)-i-1): if(a[j][1]>a[j+1][1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp   print(a)
28
# Write a Pandas program to check whether only numeric values present in a given column of a DataFrame. import pandas as pd df = pd.DataFrame({ 'company_code': ['Company','Company a001', '2055', 'abcd', '123345'], 'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'], 'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]}) print("Original DataFrame:") print(df) print("\nNumeric values present in company_code column:") df['company_code_is_digit'] = list(map(lambda x: x.isdigit(), df['company_code'])) print(df)
57
# Write a Python Set | Pairs of complete strings in two sets # Function to find pairs of complete strings # in two sets of strings    def completePair(set1,set2):            # consider all pairs of string from     # set1 and set2     count = 0     for str1 in set1:         for str2 in set2:             result = str1 + str2                # push all alphabets of concatenated              # string into temporary set             tmpSet = set([ch for ch in result if (ord(ch)>=ord('a') and ord(ch)<=ord('z'))])             if len(tmpSet)==26:                 count = count + 1     print (count)    # Driver program if __name__ == "__main__":     set1 = ['abcdefgh', 'geeksforgeeks','lmnopqrst', 'abc']     set2 = ['ijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyz']     completePair(set1,set2)
104
# Write a NumPy program to concatenate two 2-dimensional arrays. import numpy as np a = np.array([[0, 1, 3], [5, 7, 9]]) b = np.array([[0, 2, 4], [6, 8, 10]]) c = np.concatenate((a, b), 1) print(c)
36
# Write a Python program to count number of vowels using sets in given string # Python3 code to count vowel in  # a string using set    # Function to count vowel def vowel_count(str):            # Initializing count variable to 0     count = 0            # Creating a set of vowels     vowel = set("aeiouAEIOU")            # Loop to traverse the alphabet     # in the given string     for alphabet in str:                # If alphabet is present         # in set vowel         if alphabet in vowel:             count = count + 1            print("No. of vowels :", count)        # Driver code  str = "GeeksforGeeks"    # Function Call vowel_count(str)
100
# Write a Python program to create a 24-hour time format (HH:MM ) using 4 given digits. Display the latest time and do not use any digit more than once. import itertools def max_time(nums): for i in range(len(nums)): nums[i] *= -1 nums.sort() for hr1, hr2, m1, m2 in itertools.permutations(nums): hrs = -(10*hr1 + hr2) mins = -(10*m1 + m2) if 60> mins >=0 and 24 > hrs >=0: result = "{:02}:{:02}".format(hrs, mins) break return result nums = [1,2,3,4] print("Original array:",nums) print("Latest time: ",max_time(nums)) nums = [1,2,4,5] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [2,2,4,5] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [2,2,4,3] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [0,2,4,3] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums))
115
# Write a Python Library for Linked List # importing module import collections # initialising a deque() of arbitary length linked_lst = collections.deque() # filling deque() with elements linked_lst.append('first') linked_lst.append('second') linked_lst.append('third') print("elements in the linked_list:") print(linked_lst) # adding element at an arbitary position linked_lst.insert(1, 'fourth') print("elements in the linked_list:") print(linked_lst) # deleting the last element linked_lst.pop() print("elements in the linked_list:") print(linked_lst) # removing a specific element linked_lst.remove('fourth') print("elements in the linked_list:") print(linked_lst)
72
# Write a Python program to find a pair with highest product from a given array of integers. def max_Product(arr): arr_len = len(arr) if (arr_len < 2): print("No pairs exists") return # Initialize max product pair x = arr[0]; y = arr[1] # Traverse through every possible pair for i in range(0, arr_len): for j in range(i + 1, arr_len): if (arr[i] * arr[j] > x * y): x = arr[i]; y = arr[j] return x,y nums = [1, 2, 3, 4, 7, 0, 8, 4] print("Original array:", nums) print("Maximum product pair is:", max_Product(nums)) nums = [0, -1, -2, -4, 5, 0, -6] print("\nOriginal array:", nums) print("Maximum product pair is:", max_Product(nums))
111
# Write a NumPy program to convert a NumPy array of float values to a NumPy array of integer values. import numpy as np x= np.array([[12.0, 12.51], [2.34, 7.98], [25.23, 36.50]]) print("Original array elements:") print(x) print("Convert float values to integer values:") print(x.astype(int))
42
# Write a Python program to Numpy np.char.endswith() method # import numpy import numpy as np    # using np.char.endswith() method a = np.array(['geeks', 'for', 'geeks']) gfg = np.char.endswith(a, 'ks')    print(gfg)
30
# Write a Python Program to Replace Specific Line in File with open('example.txt', 'r', encoding='utf-8') as file:     data = file.readlines()    print(data) data[1] = "Here is my modified Line 2\n"    with open('example.txt', 'w', encoding='utf-8') as file:     file.writelines(data)
36
# Write a Python program to group the elements of a list based on the given function and returns the count of elements in each group. from collections import defaultdict def count_by(lst, fn = lambda x: x): count = defaultdict(int) for val in map(fn, lst): count[val] += 1 return dict(count) from math import floor print(count_by([6.1, 4.2, 6.3], floor)) print(count_by(['one', 'two', 'three'], len))
62
# numpy string operations | join() function in Python # Python program explaining # numpy.core.defchararray.join() method     # importing numpy  import numpy as geek    # input array  in_arr = geek.array(['Python', 'Numpy', 'Pandas']) print ("Input original array : ", in_arr)     # creating the separator sep = geek.array(['-', '+', '*'])       out_arr = geek.core.defchararray.join(sep, in_arr) print ("Output joined array: ", out_arr) 
57
# Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise, sales man wise where Manager = "Douglas". import pandas as pd df = pd.read_excel('E:\SaleData.xlsx') table = pd.pivot_table(df,index=["Region","Manager","SalesMan"], values="Sale_amt") print(table.query('Manager == ["Douglas"]'))
41
# Write a Python program to calculate number of days between two dates. from datetime import date f_date = date(2014, 7, 2) l_date = date(2014, 7, 11) delta = l_date - f_date print(delta.days)
33
# Write a Pandas program to create a sequence of durations increasing by an hour. import pandas as pd date_range = pd.timedelta_range(0, periods=49, freq='H') print("Hourly range of perods 49:") print(date_range)
30
# Write a Pandas program to create a Pivot table with multiple indexes from the data set of titanic.csv. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = pd.pivot_table(df, index = ["sex","age"], aggfunc=np.sum) print(result)
38
# Write a Python program to count the number of elements in a list within a specified range. def count_range_in_list(li, min, max): ctr = 0 for x in li: if min <= x <= max: ctr += 1 return ctr list1 = [10,20,30,40,40,40,70,80,99] print(count_range_in_list(list1, 40, 100)) list2 = ['a','b','c','d','e','f'] print(count_range_in_list(list2, 'a', 'e'))
52
# Find the Generic root of a number '''Write a Python program to Find the Generic root of a number.'' print("Enter a number:") num = int(input()) while num > 10:     sum = 0     while num:         r=num % 10         num= num / 10         sum+= r     if sum > 10:         num = sum     else:         break print("Generic root of the number is ", int(sum)) 
61
# Write a Pandas program to start index with different value rather than 0 in a given DataFrame. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 37, 33, 30, 31, 32]}) print("Original DataFrame:") print(df) print("\nDefault Index Range:") print(df.index) df.index += 10 print("\nNew Index Range:") print(df.index) print("\nDataFrame with new index:") print(df)
73
# Write a Python program to update all the values of a specific column of a given SQLite table. import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) def sql_table(conn): cursorObj = conn.cursor() # Create the table cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));") # Insert records cursorObj.executescript(""" INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15); INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25); INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15); INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35); INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45); """) cursorObj.execute("SELECT * FROM salesman") rows = cursorObj.fetchall() print("Agent details:") for row in rows: print(row) print("\nUpdate all commision to .55:") sql_update_query = """Update salesman set commission = .55""" cursorObj.execute(sql_update_query) conn.commit() print("Record Updated successfully ") cursorObj.execute("SELECT * FROM salesman") rows = cursorObj.fetchall() print("\nAfter updating Agent details:") for row in rows: print(row) sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
157
# Write a Python program to create a dictionary with the unique values of a given list as keys and their frequencies as the values. from collections import defaultdict def frequencies(lst): freq = defaultdict(int) for val in lst: freq[val] += 1 return dict(freq) print(frequencies(['a', 'b', 'f', 'a', 'c', 'e', 'a', 'a', 'b', 'e', 'f'])) print(frequencies([3,4,7,5,9,3,4,5,0,3,2,3]))
55
# Write a Python program to Extract digits from Tuple list # Python3 code to demonstrate working of # Extract digits from Tuple list # Using map() + chain.from_iterable() + set() + loop from itertools import chain # initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)] # printing original list print("The original list is : " + str(test_list)) # Extract digits from Tuple list # Using map() + chain.from_iterable() + set() + loop temp = map(lambda ele: str(ele), chain.from_iterable(test_list)) res = set() for sub in temp:     for ele in sub:         res.add(ele) # printing result print("The extracted digits : " + str(res))
105
# Write a Python Program to print all Possible Combinations from the three Digits # Python program to print all # the possible combinations    def comb(L):            for i in range(3):         for j in range(3):             for k in range(3):                                    # check if the indexes are not                 # same                 if (i!=j and j!=k and i!=k):                     print(L[i], L[j], L[k])                        # Driver Code comb([1, 2, 3])
62
# Write a Python program to find common elements in a given list of lists. def common_list_of_lists(lst): temp = set(lst[0]).intersection(*lst) return list(temp) nums = [[7,2,3,4,7],[9,2,3,2,5],[8,2,3,4,4]] print("Original list:") print(nums) print("\nCommon elements of the said list of lists:") print(common_list_of_lists(nums)) chars = [['a','b','c'],['b','c','d'],['c','d','e']] print("\nOriginal list:") print(chars) print("\nCommon elements of the said list of lists:") print(common_list_of_lists(chars))
52
# Write a Python program to copy the contents of a file to another file . from shutil import copyfile copyfile('test.py', 'abc.py')
22
# Write a Pandas program to calculate one, two, three business day(s) from a specified date. Also find the next business month end from a specific date. import pandas as pd from pandas.tseries.offsets import * import datetime from datetime import datetime, date dt = datetime(2020, 1, 4) print("Specified date:") print(dt) print("\nOne business day from the said date:") obday = dt + BusinessDay() print(obday) print("\nTwo business days from the said date:") tbday = dt + 2 * BusinessDay() print(tbday) print("\nThree business days from the said date:") thbday = dt + 3 * BusinessDay() print(thbday) print("\nNext business month end from the said date:") nbday = dt + BMonthEnd() print(nbday)
107
# Write a Pandas program to create a date range using a startpoint date and a number of periods. import pandas as pd date_range = pd.date_range('2020-01-01', periods=45) print("Date range of perods 45:") print(date_range)
33
# Write a Python program to Last business day of every month in year # Python3 code to demonstrate working of # Last weekday of every month in year # Using loop + max() + calendar.monthcalendar import calendar    # initializing year year = 1997    # printing Year print("The original year : " + str(year))    # initializing weekday  weekdy = 5    # iterating for all months res = [] for month in range(1, 13):            # max gets last friday of each month of 1997     res.append(str(max(week[weekdy]                         for week in calendar.monthcalendar(year, month))) +                "/" + str(month)+ "/" + str(year))    # printing  print("Last weekdays of year : " + str(res))
106
# Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + q(3). import numpy as np p = np.array([[0, 0, 0], [1, 2, 3], [4, 5, 6]]) q= np.array([10, 11, 12]) print("Original arrays:") print("Array-1") print(p) print("Array-2") print(q) print("\nNew Array:") new_array1 = p + q print(new_array1)
49
# Write a Python program to check whether a page contains a title or not. from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://www.wikipedia.org/') bs = BeautifulSoup(html, "html.parser") nameList = bs.findAll('a', {'class' : 'link-box'}) for name in nameList: print(name.get_text())
41
# Write a Python program to create a dictionary with the same keys as the given dictionary and values generated by running the given function for each value. def test(obj, fn): return dict((k, fn(v)) for k, v in obj.items()) users = { 'Theodore': { 'user': 'Theodore', 'age': 45 }, 'Roxanne': { 'user': 'Roxanne', 'age': 15 }, 'Mathew': { 'user': 'Mathew', 'age': 21 }, } print("\nOriginal dictionary elements:") print(users) print("\nDictionary with the same keys:") print(test(users, lambda u : u['age']))
78
# Write a NumPy program to extract second and third elements of the second and third rows from a given (4x4) array. import numpy as np arra_data = np.arange(0,16).reshape((4, 4)) print("Original array:") print(arra_data) print("\nExtracted data: Second and third elements of the second and third rows") print(arra_data[1:3, 1:3])
47
# Write a Python program to create a deque and append few elements to the left and right, then remove some elements from the left, right sides and reverse the deque. import collections # Create a deque deque_colors = collections.deque(["Red","Green","White"]) print(deque_colors) # Append to the left print("\nAdding to the left: ") deque_colors.appendleft("Pink") print(deque_colors) # Append to the right print("\nAdding to the right: ") deque_colors.append("Orange") print(deque_colors) # Remove from the right print("\nRemoving from the right: ") deque_colors.pop() print(deque_colors) # Remove from the left print("\nRemoving from the left: ") deque_colors.popleft() print(deque_colors) # Reverse the dequeue print("\nReversing the deque: ") deque_colors.reverse() print(deque_colors)
99
# Python Program to Solve n-Queen Problem without Recursion class QueenChessBoard: def __init__(self, size): # board has dimensions size x size self.size = size # columns[r] is a number c if a queen is placed at row r and column c. # columns[r] is out of range if no queen is place in row r. # Thus after all queens are placed, they will be at positions # (columns[0], 0), (columns[1], 1), ... (columns[size - 1], size - 1) self.columns = []   def place_in_next_row(self, column): self.columns.append(column)   def remove_in_current_row(self): return self.columns.pop()   def is_this_column_safe_in_next_row(self, column): # index of next row row = len(self.columns)   # check column for queen_column in self.columns: if column == queen_column: return False   # check diagonal for queen_row, queen_column in enumerate(self.columns): if queen_column - queen_row == column - row: return False   # check other diagonal for queen_row, queen_column in enumerate(self.columns): if ((self.size - queen_column) - queen_row == (self.size - column) - row): return False   return True   def display(self): for row in range(self.size): for column in range(self.size): if column == self.columns[row]: print('Q', end=' ') else: print('.', end=' ') print()     def solve_queen(size): """Display a chessboard for each possible configuration of placing n queens on an n x n chessboard and print the number of such configurations.""" board = QueenChessBoard(size) number_of_solutions = 0   row = 0 column = 0 # iterate over rows of board while True: # place queen in next row while column < size: if board.is_this_column_safe_in_next_row(column): board.place_in_next_row(column) row += 1 column = 0 break else: column += 1   # if could not find column to place in or if board is full if (column == size or row == size): # if board is full, we have a solution if row == size: board.display() print() number_of_solutions += 1   # small optimization: # In a board that already has queens placed in all rows except # the last, we know there can only be at most one position in # the last row where a queen can be placed. In this case, there # is a valid position in the last row. Thus we can backtrack two # times to reach the second last row. board.remove_in_current_row() row -= 1   # now backtrack try: prev_column = board.remove_in_current_row() except IndexError: # all queens removed # thus no more possible configurations break # try previous row again row -= 1 # start checking at column = (1 + value of column in previous row) column = 1 + prev_column   print('Number of solutions:', number_of_solutions)     n = int(input('Enter n: ')) solve_queen(n)
416
# Program to Find sum of series 1+(1+3)+(1+3+5)+....+N print("Enter the range of number(Limit):") n = int(input()) i = 1 sum = 0 while (i <= n):     for j in range(1, i + 1,2):         sum+=j     i += 2 print("The sum of the series = ", sum)
45
# Write a Python program to create a time object with the same hour, minute, second, microsecond and a timestamp representation of the Arrow object, in UTC time. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nTime object with the same hour, minute, second, microsecond:") print(arrow.utcnow().time()) print("\nTimestamp representation of the Arrow object, in UTC time:") print(arrow.utcnow().timestamp)
56
# Write a Pandas program to create a Pivot table and check missing values of children. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.loc[df['who']=='child'].isnull().sum() print(result)
31
# Write a Pandas program to create a Pivot table and find the item wise unit sold. import pandas as pd import numpy as np df = pd.read_excel('E:\SaleData.xlsx') print(pd.pivot_table(df,index=["Item"], values="Units", aggfunc=np.sum))
31
# Getting frequency counts of a columns in Pandas DataFrame in Python # importing pandas as pd import pandas as pd    # sample dataframe df = pd.DataFrame({'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g',                          'bar', 'bar', 'foo', 'bar'],                   'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] })    # frequency count of column A count = df['A'].value_counts() print(count)
57
# Python Program to Find Longest Common Substring using Dynamic Programming with Memoization def lcw(u, v): """Return length of an LCW of strings u and v and its starting indexes.   (l, i, j) is returned where l is the length of an LCW of the strings u, v where the LCW starts at index i in u and index j in v. """ c = [[-1]*(len(v) + 1) for _ in range(len(u) + 1)]   lcw_i = lcw_j = -1 length_lcw = 0 for i in range(len(u)): for j in range(len(v)): temp = lcw_starting_at(u, v, c, i, j) if length_lcw < temp: length_lcw = temp lcw_i = i lcw_j = j   return length_lcw, lcw_i, lcw_j     def lcw_starting_at(u, v, c, i, j): """Return length of the LCW starting at u[i:] and v[j:] and fill table c.   c[i][j] contains the length of the LCW at the start of u[i:] and v[j:]. This function fills in c as smaller subproblems for solving c[i][j] are solved.""" if c[i][j] >= 0: return c[i][j]   if i == len(u) or j == len(v): q = 0 elif u[i] != v[j]: q = 0 else: q = 1 + lcw_starting_at(u, v, c, i + 1, j + 1)   c[i][j] = q return q     u = input('Enter first string: ') v = input('Enter second string: ') length_lcw, lcw_i, lcw_j = lcw(u, v) print('Longest Common Subword: ', end='') if length_lcw > 0: print(u[lcw_i:lcw_i + length_lcw])
234
# Write a Python program to count float number in a given mixed list using lambda. def count_integer(list1): ert = list(map(lambda i: isinstance(i, float), list1)) result = len([e for e in ert if e]) return result list1 = [1, 'abcd', 3.12, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22] print("Original list:") print(list1) print("\nNumber of floats in the said mixed list:") print(count_integer(list1))
61
# Write a Python program to sort unsorted numbers using Odd Even Transposition Parallel sort. #Ref.https://bit.ly/3cce7iB from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time processLock = Lock() def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe): global processLock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0, 10): if (i + position) % 2 == 0 and RSend is not None: # send your value to your right neighbor processLock.acquire() RSend[1].send(value) processLock.release() # receive your right neighbor's value processLock.acquire() temp = RRcv[0].recv() processLock.release() # take the lower value since you are on the left value = min(value, temp) elif (i + position) % 2 != 0 and LSend is not None: # send your value to your left neighbor processLock.acquire() LSend[1].send(value) processLock.release() # receive your left neighbor's value processLock.acquire() temp = LRcv[0].recv() processLock.release() # take the higher value since you are on the right value = max(value, temp) # after all swaps are performed, send the values back to main resultPipe[1].send(value) """ the function which creates the processes that perform the parallel swaps arr = the list to be sorted """ def OddEvenTransposition(arr): processArray = [] resultPipe = [] # initialize the list of pipes where the values will be retrieved for _ in arr: resultPipe.append(Pipe()) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop tempRs = Pipe() tempRr = Pipe() processArray.append( Process( target=oeProcess, args=(0, arr[0], None, tempRs, None, tempRr, resultPipe[0]), ) ) tempLr = tempRs tempLs = tempRr for i in range(1, len(arr) - 1): tempRs = Pipe() tempRr = Pipe() processArray.append( Process( target=oeProcess, args=(i, arr[i], tempLs, tempRs, tempLr, tempRr, resultPipe[i]), ) ) tempLr = tempRs tempLs = tempRr processArray.append( Process( target=oeProcess, args=( len(arr) - 1, arr[len(arr) - 1], tempLs, None, tempLr, None, resultPipe[len(arr) - 1], ), ) ) # start the processes for p in processArray: p.start() # wait for the processes to end and write their values to the list for p in range(0, len(resultPipe)): arr[p] = resultPipe[p][0].recv() processArray[p].join() return arr # creates a reverse sorted list and sorts it def main(): arr = list(range(10, 0, -1)) print("Initial List") print(*arr) arr = OddEvenTransposition(arr) print("\nSorted List:") print(*arr) if __name__ == "__main__": main()
423
# Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable. import numpy as np x = np.random.rand(10, 4) print("Original array: ") print(x) y= x[:5, :] print("First 5 rows of the above array:") print(y)
49
# Multiply two numbers without using multiplication(*) operator num1=int(input("Enter the First numbers :")) num2=int(input("Enter the Second number:")) sum=0 for i in range(1,num1+1):     sum=sum+num2 print("The multiplication of ",num1," and ",num2," is ",sum)
31
# Write a Python program to sort a given dictionary by key. color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print("%s: %s" % (key, color_dict[key]))
27
# Write a Python program to How to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization    # initialize tuples test_tup1 = (3, 4), test_tup2 = (5, 6),    # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))    # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization res = test_tup1 + test_tup2    # printing result print("Tuples after Concatenating : " + str(res))
98
# Write a Python program to find the maximum occurring character in a given string. def get_max_occuring_char(str1): ASCII_SIZE = 256 ctr = [0] * ASCII_SIZE max = -1 ch = '' for i in str1: ctr[ord(i)]+=1; for i in str1: if max < ctr[ord(i)]: max = ctr[ord(i)] ch = i return ch print(get_max_occuring_char("Python: Get file creation and modification date/times")) print(get_max_occuring_char("abcdefghijkb"))
60
# Write a Python program to create a datetime from a given timezone-aware datetime using arrow module. import arrow from datetime import datetime from dateutil import tz print("\nCreate a date from a given date and a given time zone:") d1 = arrow.get(datetime(2018, 7, 5), 'US/Pacific') print(d1) print("\nCreate a date from a given date and a time zone object from a string representation:") d2 = arrow.get(datetime(2017, 7, 5), tz.gettz('America/Chicago')) print(d2) d3 = arrow.get(datetime.now(tz.gettz('US/Pacific'))) print("\nCreate a date using current datetime and a specified time zone:") print(d3)
84
# Write a NumPy program to compute the following polynomial values. import numpy as np print("Polynomial value when x = 2:") print(np.polyval([1, -2, 1], 2)) print("Polynomial value when x = 3:") print(np.polyval([1, -12, 10, 7, -10], 3))
37
# Write a Python program to Numpy np.polygrid2d() method # Python program explaining # numpy.polygrid2d() method     # importing numpy as np    import numpy as np  from numpy.polynomial.polynomial import polygrid2d    # Input polynomial series coefficients c = np.array([[1, 3, 5], [2, 4, 6]])     # using np.polygrid2d() method  ans = polygrid2d([7, 9], [8, 10], c) print(ans)
54
# Write a NumPy program to calculate percentiles for a sequence or single-dimensional NumPy array. import numpy as np nums = np.array([1,2,3,4,5]) print("50th percentile (median):") p = np.percentile(nums, 50) print(p) print("40th percentile:") p = np.percentile(nums, 40) print(p) print("90th percentile:") p = np.percentile(nums, 90) print(p)
44
# Program to print a butterfly shape star pattern row_size=int(input("Enter the row size:"))print_control_x=1for out in range(1,row_size+1):    for inn in range(1,row_size+1):        if inn<=print_control_x or inn>=row_size-print_control_x+1:            print("*",end="")        else:            print(" ", end="")    if out <= row_size // 2:        print_control_x+=1    else:        print_control_x-=1    print("\r")
39
# Write a Python program to add two given lists using map and lambda. nums1 = [1, 2, 3] nums2 = [4, 5, 6] print("Original list:") print(nums1) print(nums2) result = map(lambda x, y: x + y, nums1, nums2) print("\nResult: after adding two list") print(list(result))
44
# Write a Python program to sort unsorted numbers using Recursive Bubble Sort. #Ref.https://bit.ly/3oneU2l def bubble_sort(list_data: list, length: int = 0) -> list: length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) print("After applying Recursive Insertion Sort the said list becomes:") bubble_sort(nums, len(nums)) print(nums) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) print("After applying Recursive Bubble Sort the said list becomes:") bubble_sort(nums, len(nums)) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Recursive Bubble Sort the said list becomes:") bubble_sort(nums, len(nums)) print(nums) nums = ['z','a','y','b','x','c'] print("\nOriginal list:") print(nums) print("After applying Recursive Bubble Sort the said list becomes:") bubble_sort(nums, len(nums)) print(nums)
157
# How to add timestamp to excel file in Python # Import the required modules import datetime from openpyxl import Workbook import time       # Main Function if __name__ == '__main__':          # Create a worbook object     wb = Workbook()        # Select the active sheet     ws = wb.active        # Heading of Cell A1     ws.cell(row=1, column=1).value = "Current Date and Time"        # Cell A2 containing the Current Date and Time     ws.cell(row=2, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')        # Sleep of 2 seconds     time.sleep(2)        # Cell A3 containing the Current Date and Time     ws.cell(row=3, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')     time.sleep(2)        # Cell A4 containing the Current Date and Time     ws.cell(row=4, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')        # Save the workbook with a     # filename and close the object     wb.save('gfg.xlsx')     wb.close()
121
# Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and to sort the records by the hire_date column. import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') result = df.sort_values('hire_date') result
39
# Write a Python program to iterate over a root level path and print all its sub-directories and files, also loop over specified dirs and files. import os print('Iterate over a root level path:') path = '/tmp/' for root, dirs, files in os.walk(path): print(root)
44
# Write a Python program to compute the sum of elements of a given array of integers, use map() function. from array import array def array_sum(nums_arr): sum_n = 0 for n in nums_arr: sum_n += n return sum_n nums = array('i', [1, 2, 3, 4, 5, -15]) print("Original array:",nums) nums_arr = list(map(int, nums)) result = array_sum(nums_arr) print("Sum of all elements of the said array:") print(result)
65
# Write a Python program to display a given decimal value in scientific notation. Use decimal.Decimal import decimal #Source: https://bit.ly/2SfZEtL def format_e(n): a = '%E' % n return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1] print("Original decimal value: "+ "40800000000.00000000000000") print("Scientific notation of the said decimal value:") print(format_e(decimal.Decimal('40800000000.00000000000000'))) print("\nOriginal decimal value: "+ "40000000000.00000000000000") print("Scientific notation of the said decimal value:") print(format_e(decimal.Decimal('40000000000.00000000000000'))) print("\nOriginal decimal value: "+ "40812300000.00000000000000") print("Scientific notation of the said decimal value:") print(format_e(decimal.Decimal('40812300000.00000000000000')))
72
# Write a Python program to insert tags or strings immediately before specified tags or strings. from bs4 import BeautifulSoup soup = BeautifulSoup("<b>w3resource.com</b>", "lxml") print("Original Markup:") print(soup.b) tag = soup.new_tag("i") tag.string = "Python" print("\nNew Markup, before inserting the text:") soup.b.string.insert_before(tag) print(soup.b)
41
# Create a Numpy array with random values | Python # Python Program to create numpy array  # filled with random values import numpy as geek       b = geek.empty(2, dtype = int)  print("Matrix b : \n", b)       a = geek.empty([2, 2], dtype = int)  print("\nMatrix a : \n", a) 
49
# Write a Pandas program to create a stacked histograms plot of opening, closing, high, low stock prices of Alphabet Inc. between two specific dates with more bins. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-9-30') df['Date'] = pd.to_datetime(df['Date']) new_df = (df['Date']>= start_date) & (df['Date']<= end_date) df1 = df.loc[new_df] df2 = df1[['Open','Close','High','Low']] plt.figure(figsize=(25,25)) df2.plot.hist(stacked=True, bins=200) plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='black') plt.show()
77
# Categorize Password as Strong or Weak using Regex in Python # Categorizing password as Strong or  # Weak in Python using Regex        import re       # Function to categorize password def password(v):         # the password should not be a     # newline or space     if v == "\n" or v == " ":         return "Password cannot be a newline or space!"         # the password length should be in     # between 9 and 20     if 9 <= len(v) <= 20:             # checks for occurrence of a character          # three or more times in a row         if re.search(r'(.)\1\1', v):             return "Weak Password: Same character repeats three or more times in a row"             # checks for occurrence of same string          # pattern( minimum of two character length)         # repeating         if re.search(r'(..)(.*?)\1', v):             return "Weak password: Same string pattern repetition"             else:             return "Strong Password!"         else:         return "Password length must be 9-20 characters!"    # Main method def main():         # Driver code     print(password("Qggf!@ghf3"))     print(password("Gggksforgeeks"))     print(password("aaabnil1gu"))     print(password("Aasd!feasn"))     print(password("772*hd897"))     print(password(" "))         # Driver Code if __name__ == '__main__':     main()
170
# Multiply matrices of complex numbers using NumPy in Python # importing numpy as library import numpy as np       # creating matrix of complex number x = np.array([2+3j, 4+5j]) print("Printing First matrix:") print(x)    y = np.array([8+7j, 5+6j]) print("Printing Second matrix:") print(y)    # vector dot product of two matrices z = np.vdot(x, y) print("Product of first and second matrices are:") print(z)
60
# Write a NumPy program to create a 3X4 array using and iterate over it. import numpy as np a = np.arange(10,22).reshape((3, 4)) print("Original array:") print(a) print("Each element of the array is:") for x in np.nditer(a): print(x,end=" ")
38
# Write a Python program to Sort String by Custom Integer Substrings # Python3 code to demonstrate working of # Sort String by Custom Substrings # Using sorted() + zip() + lambda + regex() import re # initializing list test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"] # printing original list print("The original list : " + str(test_list)) # initializing substring list subord_list = ["6", "7", "4", "11"] # creating inverse mapping with index temp_dict = {val: key for key, val in enumerate(subord_list)} # custom sorting temp_list = sorted([[ele, temp_dict[re.search("(\d+)$", ele).group()]] \                 for ele in test_list], key = lambda x: x[1]) # compiling result res = [ele for ele in list(zip(*temp_list))[0]]           # printing result print("The sorted list : " + str(res))
127
# numpy string operations | find() function in Python # Python program explaining # numpy.char.find() method     # importing numpy as geek import numpy as geek    # input arrays   in_arr = geek.array(['aAaAaA', 'baA', 'abBABba']) print ("Input array : ", in_arr)     # output arrays  out_arr = geek.char.find(in_arr, sub ='A') print ("Output array: ", out_arr) 
52
# Write a NumPy program to find a matrix or vector norm. import numpy as np v = np.arange(7) result = np.linalg.norm(v) print("Vector norm:") print(result) m = np.matrix('1, 2; 3, 4') result1 = np.linalg.norm(m) print("Matrix norm:") print(result1)
37
# Write a Python program to Test if string is subset of another # Python3 code to demonstrate working of  # Test if string is subset of another # Using all()    # initializing strings test_str1 = "geeksforgeeks" test_str2 = "gfks"    # printing original string print("The original string is : " + test_str1)    # Test if string is subset of another # Using all() res = all(ele in test_str1 for ele in test_str2)    # printing result  print("Does string contains all the characters of other list? : " + str(res)) 
88
# Write a NumPy program to convert angles from degrees to radians for all elements in a given array. import numpy as np x = np.array([-180., -90., 90., 180.]) r1 = np.radians(x) r2 = np.deg2rad(x) assert np.array_equiv(r1, r2) print(r1)
39
# Python Program to Find if Directed Graph contains Cycle using DFS class Graph: def __init__(self): # dictionary containing keys that map to the corresponding vertex object self.vertices = {}   def add_vertex(self, key): """Add a vertex with the given key to the graph.""" vertex = Vertex(key) self.vertices[key] = vertex   def get_vertex(self, key): """Return vertex object with the corresponding key.""" return self.vertices[key]   def __contains__(self, key): return key in self.vertices   def add_edge(self, src_key, dest_key, weight=1): """Add edge from src_key to dest_key with given weight.""" self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)   def does_edge_exist(self, src_key, dest_key): """Return True if there is an edge from src_key to dest_key.""" return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])   def __iter__(self): return iter(self.vertices.values())     class Vertex: def __init__(self, key): self.key = key self.points_to = {}   def get_key(self): """Return key corresponding to this vertex object.""" return self.key   def add_neighbour(self, dest, weight): """Make this vertex point to dest with given edge weight.""" self.points_to[dest] = weight   def get_neighbours(self): """Return all vertices pointed to by this vertex.""" return self.points_to.keys()   def get_weight(self, dest): """Get weight of edge from this vertex to dest.""" return self.points_to[dest]   def does_it_point_to(self, dest): """Return True if this vertex points to dest.""" return dest in self.points_to     def is_cycle_present(graph): """Return True if cycle is present in the graph.""" on_stack = set() visited = set() for v in graph: if v not in visited: if is_cycle_present_helper(v, visited, on_stack): return True return False     def is_cycle_present_helper(v, visited, on_stack): """Return True if the DFS traversal starting at vertex v detects a cycle. Uses set visited to keep track of nodes that have been visited. Uses set on_stack to keep track of nodes that are 'on the stack' of the recursive calls.""" if v in on_stack: return True on_stack.add(v) for dest in v.get_neighbours(): if dest not in visited: if is_cycle_present_helper(dest, visited, on_stack): return True on_stack.remove(v) visited.add(v) return False     g = Graph() print('Menu') print('add vertex <key>') print('add edge <vertex1> <vertex2>') print('cycle') print('display') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0] if operation == 'add': suboperation = do[1] if suboperation == 'vertex': key = int(do[2]) if key not in g: g.add_vertex(key) else: print('Vertex already exists.') elif suboperation == 'edge': v1 = int(do[2]) v2 = int(do[3]) if v1 not in g: print('Vertex {} does not exist.'.format(v1)) elif v2 not in g: print('Vertex {} does not exist.'.format(v2)) else: if not g.does_edge_exist(v1, v2): g.add_edge(v1, v2) else: print('Edge already exists.')   elif operation == 'cycle': if is_cycle_present(g): print('Cycle present.') else: print('Cycle not present.')   elif operation == 'display': print('Vertices: ', end='') for v in g: print(v.get_key(), end=' ') print()   print('Edges: ') for v in g: for dest in v.get_neighbours(): w = v.get_weight(dest) print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w)) print()   elif operation == 'quit': break
436
# Write a Pandas program to remove repetitive characters from the specified column of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'text_code': ['t0001.','t0002','t0003', 't0004'], 'text_lang': ['She livedd a long life.', 'How oold is your father?', 'What is tthe problem?','TThhis desk is used by Tom.'] }) print("Original DataFrame:") print(df) def rep_char(str1): tchr = str1.group(0) if len(tchr) > 1: return tchr[0:1] # can change the value here on repetition def unique_char(rep, sent_text): convert = re.sub(r'(\w)\1+', rep, sent_text) return convert df['normal_text']=df['text_lang'].apply(lambda x : unique_char(rep_char,x)) print("\nRemove repetitive characters:") print(df)
94
# Write a NumPy program to remove the leading whitespaces of all the elements of a given array. import numpy as np x = np.array([' python exercises ', ' PHP ', ' java ', ' C++'], dtype=np.str) print("Original Array:") print(x) lstripped_char = np.char.lstrip(x) print("\nRemove the leading whitespaces : ", lstripped_char)
50
# Write a NumPy program to remove single-dimensional entries from a specified shape. import numpy as np x = np.zeros((3, 1, 4)) print(np.squeeze(x).shape)
23
# Write a NumPy program to create an array with 10^3 elements. import numpy as np x = np.arange(1e3) print(x)
20
# Write a Python program to Remove Reduntant Substrings from Strings List # Python3 code to demonstrate working of # Remove Reduntant Substrings from Strings List # Using enumerate() + join() + sort() # initializing list test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] # printing original list print("The original list : " + str(test_list)) # using loop to iterate for each string test_list.sort(key = len) res = [] for idx, val in enumerate(test_list):           # concatenating all next values and checking for existence     if val not in ', '.join(test_list[idx + 1:]):         res.append(val) # printing result print("The filtered list : " + str(res))
105
# Write a Python program to create an object for writing and iterate over the rows to print the values. import csv import sys with open('temp.csv', 'wt') as f: writer = csv.writer(f) writer.writerow(('id1', 'id2', 'date')) for i in range(3): row = ( i + 1, chr(ord('a') + i), '01/{:02d}/2019'.format(i + 1),) writer.writerow(row) print(open('temp.csv', 'rt').read())
54
# Write a Python program to swap cases of a given string. def swap_case_string(str1): result_str = "" for item in str1: if item.isupper(): result_str += item.lower() else: result_str += item.upper() return result_str print(swap_case_string("Python Exercises")) print(swap_case_string("Java")) print(swap_case_string("NumPy"))
36
# Write a Python program to Replace Different characters in String at Once # Python3 code to demonstrate working of # Replace Different characters in String at Once # using join() + generator expression # initializing string test_str = 'geeksforgeeks is best' # printing original String print("The original string is : " + str(test_str)) # initializing mapping dictionary map_dict = {'e':'1', 'b':'6', 'i':'4'} # generator expression to construct vals # join to get string res = ''.join(idx if idx not in map_dict else map_dict[idx] for idx in test_str) # printing result print("The converted string : " + str(res))
98
# Write a Python program to Replace multiple words with K # Python3 code to demonstrate working of  # Replace multiple words with K # Using join() + split() + list comprehension    # initializing string test_str = 'Geeksforgeeks is best for geeks and CS'    # printing original string print("The original string is : " + str(test_str))    # initializing word list  word_list = ["best", 'CS', 'for']    # initializing replace word  repl_wrd = 'gfg'    # Replace multiple words with K # Using join() + split() + list comprehension res = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])    # printing result  print("String after multiple replace : " + str(res)) 
111
# Write a NumPy program to create an array of (3, 4) shape, multiply every element value by 3 and display the new array. import numpy as np x= np.arange(12).reshape(3, 4) print("Original array elements:") print(x) for a in np.nditer(x, op_flags=['readwrite']): a[...] = 3 * a print("New array elements:") print(x)
49
# Write a NumPy program to calculate 2p for all elements in a given array. import numpy as np x = np.array([1., 2., 3., 4.], np.float32) print("Original array: ") print(x) print("\n2^p for all the elements of the said array:") r1 = np.exp2(x) r2 = 2 ** x assert np.allclose(r1, r2) print(r1)
51