code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python function to get the city, state and country name of a specified latitude and longitude using Nominatim API and Geopy package. from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") def city_state_country(coord): location = geolocator.reverse(coord, exactly_one...
59
# Print the Hollow Half Pyramid Number Pattern row_size=int(input("Enter the row size:"))print_control_x=row_size//2+1for out in range(1,row_size+1):    for inn in range(1,row_size+1):        if inn==1 or out==inn or out==row_size:            print(out,end="")        else:            print(" ", end="")    print("\r")
31
# Write a Python program to remove key values pairs from a list of dictionaries. original_list = [{'key1':'value1', 'key2':'value2'}, {'key1':'value3', 'key2':'value4'}] print("Original List: ") print(original_list) new_list = [{k: v for k, v in d.items() if k != 'key1'} for d in original_list] print("New List: ") p...
46
# Write a Pandas program to find the index of a given substring of a DataFrame column. import pandas as pd df = pd.DataFrame({ 'name_code': ['c001','c002','c022', 'c2002', 'c2222'], 'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'], 'age': [18.5, 21.2, 22.5, 22, 23] }) ...
55
# Write a Python program to get the actual module object for a given object. from inspect import getmodule from math import sqrt print(getmodule(sqrt))
24
# Write a Python program to sort a list of elements using Heap sort. def heap_data(nums, index, heap_size): largest_num = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and nums[left_index] > nums[largest_num]: largest_num = left_index if right_ind...
122
# Write a Python program to Successive Characters Frequency # Python3 code to demonstrate working of  # Successive Characters Frequency # Using count() + loop + re.findall() import re        # initializing string test_str = 'geeksforgeeks is best for geeks. A geek should take interest.'    # printing original string ...
104
# Write a Python program to extract specified size of strings from a give list of string values using lambda. def extract_string(str_list1, l): result = list(filter(lambda e: len(e) == l, str_list1)) return result str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution'] print("Original list:") p...
66
# Write a Python program to remove sublists from a given list of lists, which contains an element outside a given range. #Source bit.ly/33MAeHe def remove_list_range(input_list, left_range, rigth_range): result = [i for i in input_list if (min(i)>=left_range and max(i)<=rigth_range)] return result list1 = [[2]...
89
# Write a Python program to convert JSON encoded data into Python objects. import json jobj_dict = '{"name": "David", "age": 6, "class": "I"}' jobj_list = '["Red", "Green", "Black"]' jobj_string = '"Python Json"' jobj_int = '1234' jobj_float = '21.34' python_dict = json.loads(jobj_dict) python_list = json.load...
73
# Write a Python program to Sort by Frequency of second element in Tuple List # Python3 code to demonstrate working of  # Sort by Frequency of second element in Tuple List # Using sorted() + loop + defaultdict() + lambda from collections import defaultdict    # initializing list test_list = [(6, 5), (2, 7), (2, 5), (...
115
# Write a Python program to get the smallest number from a list. def smallest_num_in_list( list ): min = list[ 0 ] for a in list: if a < min: min = a return min print(smallest_num_in_list([1, 2, -8, 0]))
39
# Write a Pandas program to filter all records where the average consumption of beverages per person from .5 to 2.50 in world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head...
66
# Write a Python program to Test if List contains elements in Range # Python3 code to demonstrate  # Test if List contains elements in Range # using loop    # Initializing loop  test_list = [4, 5, 6, 7, 3, 9]    # printing original list  print("The original list is : " + str(test_list))    # Initialization of range  ...
107
# Python Program to Find the Area of a Triangle Given All Three Sides import math a=int(input("Enter first side: ")) b=int(input("Enter second side: ")) c=int(input("Enter third side: ")) s=(a+b+c)/2 area=math.sqrt(s*(s-a)*(s-b)*(s-c)) print("Area of the triangle is: ",round(area,2))
36
# Write a Python program to extract specified size of strings from a give list of string values. def extract_string(str_list1, l): result = [e for e in str_list1 if len(e) == l] return result str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution'] print("Original list:") print(str_list1) l = 8...
67
# Write a Pandas program to get the difference (in days) between documented date and reporting date of unidentified flying object (UFO). import pandas as pd df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') df['date_documented'] = df['date_documented'].astype('datetime64[ns]') p...
55
# rite 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): ...
54
# Write a Python program to find  the greatest common divisor (gcd) of two integers. def Recurgcd(a, b): low = min(a, b) high = max(a, b) if low == 0: return high elif low == 1: return 1 else: return Recurgcd(low, high%low) print(Recurgcd(12,14))
43
# Write a Python program to find a tuple, the smallest second index value from a list of tuples. x = [(4, 1), (1, 2), (6, 0)] print(min(x, key=lambda n: (n[1], -n[0])))
32
# Write a Pandas program to convert a specified character column in upper/lower cases in a given DataFrame. import pandas as pd df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'], 'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'], 'sale_a...
81
# Write a NumPy program to create an array of 10 zeros,10 ones, 10 fives. import numpy as np array=np.zeros(10) print("An array of 10 zeros:") print(array) array=np.ones(10) print("An array of 10 ones:") print(array) array=np.ones(10)*5 print("An array of 10 fives:") print(array)
40
# Program to Find the area and perimeter of a circle radius=int(input("Enter the radius of a circle :")) area=3.14*radius*radius perimeter=2*3.14*radius print("Area =",area) print("Perimeter =",perimeter)
24
# How to Remove columns in Numpy array that contains non-numeric values in Python # Importing Numpy module import numpy as np    # Creating 2X3 2-D Numpy array n_arr = np.array([[10.5, 22.5, np.nan],                   [41, 52.5, np.nan]])    print("Given array:") print(n_arr)    print("\nRemove all columns containing...
48
# Flatten a Matrix in Python using NumPy # importing numpy as np import numpy as np    # declare matrix with np gfg = np.array([[2, 3], [4, 5]])    # using array.flatten() method flat_gfg = gfg.flatten() print(flat_gfg)
36
# Sorting a CSV object by dates in Python import pandas as pd
13
# Write a Pandas program to compute the minimum, 25th percentile, median, 75th, and maximum of a given series. import pandas as pd import numpy as np num_state = np.random.RandomState(100) num_series = pd.Series(num_state.normal(10, 4, 20)) print("Original Series:") print(num_series) result = np.percentile(num_serie...
58
# Write a Python program to display the first and last colors from the following list. color_list = ["Red","Green","White" ,"Black"] print( "%s %s"%(color_list[0],color_list[-1]))
23
# Write a Python program to create a deep copy of a given list. Use copy.copy import copy nums_x = [1, [2, 3, 4]] print("Original list: ", nums_x) nums_y = copy.deepcopy(nums_x) print("\nDeep copy of the said list:") print(nums_y) print("\nChange the value of an element of the original list:") nums_x[1][1] = 10 print...
105
# Combining a one and a two-dimensional NumPy Array in Python # importing Numpy package  import numpy as np    num_1d = np.arange(5) print("One dimensional array:") print(num_1d)    num_2d = np.arange(10).reshape(2,5) print("\nTwo dimensional array:") print(num_2d)    # Combine 1-D and 2-D arrays and display  # their...
56
# 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))
42
# Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically. items=[n for n in input().split('-')] items.sort() print('-'.join(items))
33
# Write a NumPy program to rearrange columns of a given NumPy 2D array using given index positions. import numpy as np array1 = np.array([[11, 22, 33, 44, 55], [66, 77, 88, 99, 100]]) print("Original arrays:") print(array1) i = [1,3,0,4,2] result = array1[:,i] print("New array:") print(result)
46
# Write a Pandas program to create a plot of Open, High, Low, Close, Adjusted Closing prices and Volume of Alphabet Inc. between two specific dates. 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-...
84
# Write a Python program to Remove duplicate lists in tuples (Preserving Order) # Python3 code to demonstrate working of # Remove duplicate lists in tuples(Preserving Order) # Using list comprehension + set() # Initializing tuple test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3]) # printing orig...
106
# Write a Python program to Exceptional Split in String # Python3 code to demonstrate working of  # Exceptional Split in String # Using loop + split()    # initializing string test_str = "gfg, is, (best, for), geeks"    # printing original string print("The original string is : " + test_str)    # Exceptional Split in...
120
# Write a Python program to sort a given list of lists by length and value using lambda. def sort_sublists(input_list): result = sorted(input_list, key=lambda l: (len(l), l)) return result list1 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]] print("Original list:") print(list1) print("\nSort the list of...
55
# Program to Print K using Alphabets in Python // C++ Program to design the // above pattern of K using alphabets #include<bits/stdc++.h> using namespace std; // Function to print // the above Pattern void display(int n) {   int v = n;   // This loop is used   // for rows and prints   // the alphabets in   // dec...
191
# Write a Python program to get a string which is n (non-negative integer) copies of a given string. def larger_string(str, n): result = "" for i in range(n): result = result + str return result print(larger_string('abc', 2)) print(larger_string('.py', 3))
40
# Flattening JSON objects in Python # for a array value of a key unflat_json = {'user' :                {'Rachel':                 {'UserID':1717171717,                 'Email': 'rachel1999@gmail.com',                  'friends': ['John', 'Jeremy', 'Emily']                 }                }               }    # Func...
111
# Write a Python program to compute the sum of digits of each number of a given list of positive integers. from itertools import chain def sum_of_digits(nums): return sum(int(y) for y in (chain(*[str(x) for x in nums]))) nums = [10,2,56] print("Original tuple: ") print(nums) print("Sum of digits of each number...
77
# Write a Python program to Remove nested records from tuple # Python3 code to demonstrate working of # Remove nested records # using isinstance() + enumerate() + loop    # initialize tuple test_tup = (1, 5, 7, (4, 6), 10)    # printing original tuple print("The original tuple : " + str(test_tup))    # Remove nested ...
93
# Write a Python program to convert a given list of strings into list of lists using map function. def strings_to_listOflists(str): result = map(list, str) return list(result) colors = ["Red", "Green", "Black", "Orange"] print('Original list of strings:') print(colors) print("\nConvert the said list of stri...
49
# 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
26
# Write a Python program to retrieve children of the html tag from a given web page. import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("\nChildren of the html tag (https://www.python.org):\n") root = soup.html root...
55
# Write a Pandas program to filter words from a given series that contain atleast two vowels. import pandas as pd from collections import Counter color_series = pd.Series(['Red', 'Green', 'Orange', 'Pink', 'Yellow', 'White']) print("Original Series:") print(color_series) print("\nFiltered words:") result = mask = co...
53
# Write a Python program to Replace index elements with elements in Other List # Python3 code to demonstrate  # Replace index elements with elements in Other List # using list comprehension    # Initializing lists test_list1 = ['Gfg', 'is', 'best'] test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]    # printing origi...
111
# Write a NumPy program to test whether two arrays are element-wise equal within a tolerance. import numpy as np print("Test if two arrays are element-wise equal within a tolerance:") print(np.allclose([1e10,1e-7], [1.00001e10,1e-8])) print(np.allclose([1e10,1e-8], [1.00001e10,1e-9])) print(np.allclose([1e10,1e-8], ...
45
# Python Program to Implement Bucket Sort 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]) el...
122
# Write a Python program to generate combinations of a given length of given iterable. import itertools as it def combinations_data(iter, length): return it.combinations(iter, length) #List result = combinations_data(['A','B','C','D'], 1) print("\nCombinations of an given iterable of length 1:") for i in result:...
97
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and display the last ten rows. import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df.tail(n=10)
33
# Write a Pandas program to display most frequent value in a given series and replace everything else as 'Other' in the series. import pandas as pd import numpy as np np.random.RandomState(100) num_series = pd.Series(np.random.randint(1, 5, [15])) print("Original Series:") print(num_series) print("Top 2 Freq:", num_...
50
# Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged. def new_string(str): if len(str) >= 2 and str[:2] == "Is": return str return "Is" + str print(new_string("Array")) print(new...
53
# Calculate the Euclidean distance using NumPy in Python # Python code to find Euclidean distance # using linalg.norm() import numpy as np # initializing points in # numpy arrays point1 = np.array((1, 2, 3)) point2 = np.array((1, 1, 1)) # calculating Euclidean distance # using linalg.norm() dist = np.linalg.nor...
57
# Write a Pandas program to convert unix/epoch time to a regular time stamp in UTC. Also convert the said timestamp in to a given time zone. import pandas as pd epoch_t = 1621132355 time_stamp = pd.to_datetime(epoch_t, unit='s') # UTC (Coordinated Universal Time) is one of the well-known names of UTC+0 time zone whi...
93
# Write a Python program to check whether it follows the sequence given in the patterns array. def is_samePatterns(colors, patterns): if len(colors) != len(patterns): return False sdict = {} pset = set() sset = set() for i in range(len(patterns)): pset.add(patterns[i])...
92
# Write a Python program to parse a string representing a time according to a format. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\ntime.struct_time, in the current timezone:") print(arrow.utcnow().timetuple())
30
# Scrape and Save Table Data in CSV file using Selenium in Python from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait  import time import pandas as pd from selenium.webdriver.support.ui import Select from selenium.common.exceptions im...
45
# Write a NumPy program to create a 10x4 array filled with random floating point number values with and set the array values with specified precision. import numpy as np nums = np.random.randn(10, 4) print("Original arrays:") print(nums) print("Set the array values with specified precision:") np.set_printoptions(pr...
46
# Write a program to calculate simple Interest principle=float(input("Enter a principle:")) rate=float(input("Enter a rate:")) time=float(input("Enter a time(year):")) simple_interest=(principle*rate*time)/100; print("Simple Interest:",simple_interest)
20
# Menu driven Python program to execute Linux commands # importing the module import os    # sets the text colour to green  os.system("tput setaf 2")    print("Launching Terminal User Interface")    # sets the text color to red os.system("tput setaf 1")    print("\t\tWELCOME TO Terminal User Interface\t\t\t")    # se...
210
# Write a Python program to read a file line by line and store it into a list. def file_read(fname): with open(fname) as f: #Content_list is the list that contains the read lines. content_list = f.readlines() print(content_list) file_read(\'test.txt\')
38
# Write a Pandas program to split the following dataframe into groups based on first column and set other column values into a list of values. import pandas as pd df = pd.DataFrame( {'X' : [10, 10, 10, 20, 30, 30, 10], 'Y' : [10, 15, 11, 20, 21, 12, 14], 'Z' : [22, 20, 18, 2...
68
# Write a Python program to invert a dictionary with unique hashable values. def test(students): return { value: key for key, value in students.items() } students = { 'Theodore': 10, 'Mathew': 11, 'Roxanne': 9, } print(test(students))
36
# Write a Pandas program to compute difference of differences between consecutive numbers of a given series. import pandas as pd series1 = pd.Series([1, 3, 5, 8, 10, 11, 15]) print("Original Series:") print(series1) print("\nDifference of differences between consecutive numbers of the said series:") print(series1.di...
45
# Program to print series 1,22,333,4444...n n=int(input("Enter the range of number(Limit):"))for out in range(n+1):    for i in range(out):        print(out,end="")    print(end=" ")
21
# Get row numbers of NumPy array having element larger than X in Python # importing library import numpy    # create numpy array arr = numpy.array([[1, 2, 3, 4, 5],                   [10, -3, 30, 4, 5],                   [3, 2, 5, -4, 5],                   [9, 7, 3, 6, 5]                   ])    # declare specified v...
78
# Write a Python program to sort a list of elements using the selection sort algorithm. def selectionSort(nlist): for fillslot in range(len(nlist)-1,0,-1): maxpos=0 for location in range(1,fillslot+1): if nlist[location]>nlist[maxpos]: maxpos = location temp = nlist...
46
# 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))
28
# Write a Python program to remove the contents of a tag in a given html document. from bs4 import BeautifulSoup html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>' soup = BeautifulSoup(html_content, "lxml") print("Original Markup:") print(soup.a) tag = soup.a tag = tag.clear() p...
47
# Program to Find the nth Automorphic number rangenumber=int(input("Enter an Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     num1 = num     sqr = num1 * num1     flag = 0     while num1>0:         if num1%10 != sqr%10:             flag = -1             break         num1 = num1 // 10         sqr ...
72
# Write a Python program to How to search for a string in text files string1 = 'coding'    # opening a text file file1 = open("geeks.txt", "r")    # setting flag and index to 0 flag = 0 index = 0    # Loop through the file line by line for line in file1:       index + = 1             # checking string is present in l...
102
# Write a Python program to print the Inverted heart pattern # determining the size of the heart size = 15 # printing the inverted triangle for a in range(0, size):     for b in range(a, size):         print(" ", end = "")     for b in range(1, (a * 2)):         print("*", end = "")     print("") # printing rest ...
143
# Write a Python program to Sort Dictionary key and values List # Python3 code to demonstrate working of  # Sort Dictionary key and values List # Using loop + dictionary comprehension    # initializing dictionary test_dict = {'gfg': [7, 6, 3],               'is': [2, 10, 3],               'best': [19, 4]}    # printi...
93
# Write a Python program to Group similar elements into Matrix # Python3 code to demonstrate working of  # Group similar elements into Matrix # Using list comprehension + groupby() from itertools import groupby    # initializing list test_list = [1, 3, 5, 1, 3, 2, 5, 4, 2]    # printing original list  print("The orig...
89
# Scientific GUI Calculator using Tkinter in Python from tkinter import * import math import tkinter.messagebox
16
# Program to print series 1 9 17 33 49 73 97 ...N n=int(input("Enter the range of number(Limit):"))i=1pr=0while i<=n:    if(i%2==0):        pr=2*pow(i, 2) +1        print(pr,end=" ")    else:        pr = 2*pow(i, 2) - 1        print(pr, end=" ")    i+=1
36
# Print anagrams together in Python using List and Dictionary # Function to return all anagrams together  def allAnagram(input):             # empty dictionary which holds subsets      # of all anagrams together      dict = {}         # traverse list of strings      for strVal in input:                     # sorted(i...
154
# rite a Python program to display the current date and time. import datetime now = datetime.datetime.now() print ("Current date and time : ") print (now.strftime("%Y-%m-%d %H:%M:%S"))
27
# Write a Pandas program to construct a DataFrame using the MultiIndex levels as the column and index. import pandas as pd import numpy as np sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'], ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']] ...
71
# Write a Python program to set the indentation of the first line. 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 o...
70
# Write a Python program to print the following integers with zeros on the left of specified width. x = 3 y = 123 print("\nOriginal Number: ", x) print("Formatted Number(left padding, width 2): "+"{:0>2d}".format(x)); print("Original Number: ", y) print("Formatted Number(left padding, width 6): "+"{:0>6d}".format(y)...
45
# Write a Pandas program to create a plot of stock price and trading volume of Alphabet Inc. between two specific dates. 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') ...
87
# Write a Python program to Create Nested Dictionary using given List # Python3 code to demonstrate working of  # Nested Dictionary with List # Using loop + zip()    # initializing dictionary and list test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}  test_list = [8, 3, 2]    # printing original dictionary and list print...
106
# Write a Python program to Uncommon elements in Lists of List # Python 3 code to demonstrate # Uncommon elements in List # using naive method # initializing lists test_list1 = [ [1, 2], [3, 4], [5, 6] ] test_list2 = [ [3, 4], [5, 7], [1, 2] ] # printing both lists print ("The original list 1 : " + str(test_list1...
119
# Write a Python program to update a specific column value of a given table and select all rows before and after updating the said table. import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) def...
172
# Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) Sightings year. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') df["ufo_yr"] = df.Date_time.dt.year years_data ...
68
# Write a Python Program to Reverse Every Kth row in a Matrix # Python3 code to demonstrate working of # Reverse Kth rows in Matrix # Using reversed() + loop    # initializing list test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],               [3, 6], [3, 7, 4], [2, 9]]    # printing original list print("The original li...
109
# Insertion sort using recursion def InsertionSort(arr,n):    if(n<=1):        return    InsertionSort(arr, n-1)    temp = arr[n - 1]    i = n - 2    while (i >= 0 and arr[i] > temp):        arr[ i +1] = arr[ i]        i=i-1    arr[i+1] = temparr=[]n = int(input("Enter the size of the array: "))print("Enter the Eleme...
69
# Program to print the Full Pyramid Number Pattern row_size=int(input("Enter the row size:")) np=1 for out in range(0,row_size):     for in1 in range(row_size-1,out,-1):         print(" ",end="")     for in2 in range(0, np):         print(np,end="")     np+=2     print("\r")
32
# Write a Python program to drop empty Items from a given Dictionary. dict1 = {'c1': 'Red', 'c2': 'Green', 'c3':None} print("Original Dictionary:") print(dict1) print("New Dictionary after dropping empty items:") dict1 = {key:value for (key, value) in dict1.items() if value is not None} print(dict1)
43
# Write a Python program to calculate the sum of a list, after mapping each element to a value using the provided function. def sum_by(lst, fn): return sum(map(fn, lst)) print(sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
49
# Write a Python program to compute average of two given lists. def average_two_lists(nums1, nums2): result = sum(nums1 + nums2) / len(nums1 + nums2) return result nums1 = [1, 1, 3, 4, 4, 5, 6, 7] nums2 = [0, 1, 2, 3, 4, 4, 5, 7, 8] print("Original list:") print(nums1) print(nums2) print("\nAverage of two...
57
# Python Program to Append, Delete and Display Elements of a List Using Classes class check(): def __init__(self): self.n=[] def add(self,a): return self.n.append(a) def remove(self,b): self.n.remove(b) def dis(self): return (self.n)   obj=check()   choice=1 while choic...
76
# 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] string=raw_input("Enter string:") print("Modified string:") print(change(string))
32
# Write a Python program to sort a list of elements using Comb sort. def comb_sort(nums): shrink_fact = 1.3 gaps = len(nums) swapped = True i = 0 while gaps > 1 or swapped: gaps = int(float(gaps) / shrink_fact) swapped = False i = 0 while gaps + i < len(nums): ...
82
# Write a Python program to find shortest list of values with the keys in a given dictionary. def test(dictt): min_value=1 result = [k for k, v in dictt.items() if len(v) == (min_value)] return result dictt = { 'V': [10, 12], 'VI': [10], 'VII': [10, 20, 30, 40], 'VIII': [20], 'IX': [10,30,50,7...
70
# Write a Python program to extract a given number of randomly selected elements from a given list. import random def random_select_nums(n_list, n): return random.sample(n_list, n) n_list = [1,1,2,3,4,4,5,1] print("Original list:") print(n_list) selec_nums = 3 result = random_select_nums(n_list, selec_nums)...
48
# Write a Python function to check whether a number is divisible by another number. Accept two integers values form the user. def multiple(m, n): return True if m % n == 0 else False print(multiple(20, 5)) print(multiple(7, 2))
39
# rogram to display the name of the most recently added dataset on data.gov. from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('http://www.example.com/') bsh = BeautifulSoup(html.read(), 'html.parser') print(bsh.h1)
30