code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# How to rename columns in Pandas DataFrame in Python
# Import pandas package
import pandas as pd
# Define a dictionary containing ICC rankings
rankings = {'test': ['India', 'South Africa', 'England',
'New Zealand', 'Australia'],
'odi': ['England', 'India', 'New Zealand',... | 81 |
# Write a Python program to Numpy matrix.tolist()
# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1, 12, 3]')
# applying matrix.tolist() method
geek = gfg.tolist()
print(geek) | 38 |
# Write a Python Lambda with underscore as an argument
remainder = lambda num: num % 2
print(remainder(5)) | 18 |
# Write a NumPy program to generate a random number between 0 and 1.
import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1:")
print(rand_num)
| 28 |
# Write a Python program to sort a given positive number in descending/ascending order.
def test_dsc(n):
return int(''.join(sorted(str(n), reverse = True)))
def test_asc(n):
return int(''.join(sorted(list(str(n))))[::1])
n = 134543
print("Original Number: ",n);
print("Descending order of the said number: "... | 69 |
# How to find the number of arguments in a Python function
def no_of_argu(*args):
# using len() method in args to count
return(len(args))
a = 1
b = 3
# arguments passed
n = no_of_argu(1, 2, 4, a)
# result printed
print(" The number of arguments are: ", n) | 49 |
# Write a Python program to insert tags or strings immediately after 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, after inserting the text:")
so... | 41 |
# Program to print the Half Pyramid Number Pattern
row_size=int(input("Enter the row size:"))
for out in range(1,row_size+1):
for i in range(row_size+1,out,-1):
print(out,end="")
print("\r")
| 23 |
# Write a Python program to Split Strings on Prefix Occurrence
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + startswith()
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original lis... | 98 |
# Write a NumPy program to create an empty and a full array.
import numpy as np
# Create an empty array
x = np.empty((3,4))
print(x)
# Create a full array
y = np.full((3,3),6)
print(y)
| 35 |
# Write a Python program to Insertion at the beginning in OrderedDict
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
# inserting items in starting of ... | 59 |
# Write a NumPy program to calculate cumulative sum of the elements along a given axis, sum over rows for each of the 3 columns and sum over columns for each of the 2 rows of a given 3x3 array.
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
print("Original array: ")
print(x)
print("Cumulative sum of the element... | 91 |
# Print every character of a string twice
str=input("Enter Your String:")for inn in range(0,len(str)): print(str[inn]+str[inn],end="") | 15 |
# Write a NumPy program to get the number of nonzero elements in an array.
import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print("Original array:")
print(x)
print("Number of non zero elements in the above array:")
print(np.count_nonzero(x))
| 40 |
# Write a Python code to send a request to a web page, and print the response text and content. Also get the raw socket response from the server.
import requests
res = requests.get('https://www.google.com/')
print("Response text of https://google.com/:")
print(res.text)
print("\n=====================================... | 61 |
# Write a NumPy program to access last two columns of a multidimensional columns.
import numpy as np
arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arra)
result = arra[:,[1,2]]
print(result)
| 34 |
# Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15.
import numpy as np
x = np.arange(21)
print("Original vector:")
print(x)
print("After changing the sign of the numbers in the range from 9 to 15:")
x[(x >= 9) & (x <= 15)] *= -1
print(x)
| 63 |
# Write a Python program to remove empty lists from a given list of lists.
list1 = [[], [], [], 'Red', 'Green', [1,2], 'Blue', [], []]
print("Original list:")
print(list1)
print("\nAfter deleting the empty lists from the said lists of lists")
list2 = [x for x in list1 if x]
print(list2)
| 50 |
# Write a Python program to find unique triplets whose three elements gives the sum of zero from an array of n integers.
def three_sum(nums):
result = []
nums.sort()
for i in range(len(nums)-2):
if i> 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
s = nums[i] ... | 123 |
# Write a Python program to create a 3-tuple ISO year, ISO week number, ISO weekday and an ISO 8601 formatted representation of the date and time.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\n3-tuple - ISO year, ISO week number, ISO weekday:")
print(arrow.utcnow().isocalendar())
print... | 55 |
# How to create multiple CSV files from existing CSV file using Pandas in Python
import pandas as pd
# initialise data dictionary.
data_dict = {'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Gender': ["Male", "Female", "Female", "Male",
"Male", "Female", "Male",... | 99 |
# Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda.
def sort_matrix(M):
result = sorted(M, key=lambda matrix_row: sum(matrix_row))
return result
matrix1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
matrix2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
print("O... | 90 |
# Write a Python program to Kth Column Product in Tuple List
# Python3 code to demonstrate working of
# Tuple List Kth Column Product
# using list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [(5, 6, 7), ... | 114 |
# Write a Python program to print even numbers in a list
# Python program to print Even Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
print(num, end = " ") | 58 |
# Write a Python program to create a symbolic link and read it to decide the original file pointed by the link.
import os
path = '/tmp/' + os.path.basename(__file__)
print('Creating link {} -> {}'.format(path, __file__))
os.symlink(__file__, path)
stat_info = os.lstat(path)
print('\nFile Permissions:', oct(stat_info... | 51 |
# Write a Python program to convert list to list of dictionaries.
color_name = ["Black", "Red", "Maroon", "Yellow"]
color_code = ["#000000", "#FF0000", "#800000", "#FFFF00"]
print([{'color_name': f, 'color_code': c} for f, c in zip(color_name, color_code)])
| 34 |
# Using Timedelta and Period to create DateTime based indexes in Pandas in Python
# importing pandas as pd
import pandas as pd
# Creating the timestamp
ts = pd.Timestamp('02-06-2018')
# Print the timestamp
print(ts) | 35 |
# Write a Python program to remove all consecutive duplicates of a given string.
from itertools import groupby
def remove_all_consecutive(str1):
result_str = []
for (key,group) in groupby(str1):
result_str.append(key)
return ''.join(result_str)
str1 = 'xxxxxyyyyy'
print("Original string:" + str1)
print(... | 45 |
# Write a Python program to count the values associated with key in a dictionary.
student = [{'id': 1, 'success': True, 'name': 'Lary'},
{'id': 2, 'success': False, 'name': 'Rabi'},
{'id': 3, 'success': True, 'name': 'Alex'}]
print(sum(d['id'] for d in student))
print(sum(d['success'] for d in student))
| 45 |
# Python Program to Implement a Stack using Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
... | 115 |
# Describe a NumPy Array in Python
import numpy as np
# sample array
arr = np.array([4, 5, 8, 5, 6, 4,
9, 2, 4, 3, 6])
print(arr) | 28 |
# Write a Python program to extract year, month and date value from current datetime using arrow module.
import arrow
a = arrow.utcnow()
print("Year:")
print(a.year)
print("\nMonth:")
print(a.month)
print("\nDate:")
print(a.day)
| 29 |
# Write a Pandas program to split a given dataframe into groups and list all the keys from the GroupBy object.
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V',... | 106 |
# Write a NumPy program to add a new row to an empty NumPy array.
import numpy as np
arr = np.empty((0,3), int)
print("Empty array:")
print(arr)
arr = np.append(arr, np.array([[10,20,30]]), axis=0)
arr = np.append(arr, np.array([[40,50,60]]), axis=0)
print("After adding two new arrays:")
print(arr)
| 42 |
# String slicing in Python to check if a string can become empty by recursive deletion
def checkEmpty(input, pattern):
# If both are empty
if len(input)== 0 and len(pattern)== 0:
return 'true'
# If only pattern is empty
if len(pattern)== 0:
return 'true'
... | 100 |
# Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays.
import numpy as np
x = np.array([3, 5])
y = np.array([2, 5])
print("Original numbers:")
print(x)
print(y)
print("Comparison - greater")
print(np.greater(x, y))
print("Comparison - greater_e... | 55 |
# Write a program to print the pattern
print("Enter the row and column size:");
row_size=int(input())
for out in range(1,row_size+1):
for i in range(0,row_size):
print(out,end="")
print("\r") | 25 |
# Write a NumPy program to create 24 python datetime.datetime objects (single object for every hour), and then put it in a numpy array.
import numpy as np
import datetime
start = datetime.datetime(2000, 1, 1)
dt_array = np.array([start + datetime.timedelta(hours=i) for i in range(24)])
print(dt_array)
| 45 |
# Write a Pandas program to get all the sighting days of the unidentified flying object (ufo) which are less than or equal to 40 years (365*40 days).
import pandas as pd
import datetime
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
now = pd.to_datetime('today')
duration = da... | 79 |
# Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.
def average_tuple(nums):
result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
return result
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print ("Original Tuple: ")
pri... | 93 |
# Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Add the fare as a dimension of columns and partition fare column into 2 categories based on the values present in fare columns.
import pandas as pd
import numpy as np
df = pd.read_cs... | 78 |
# Write a NumPy program to calculate the arithmetic means of corresponding elements of two given arrays of same size.
import numpy as np
nums1 = np.array([[2, 5, 2],
[1, 5, 5]])
nums2 = np.array([[5, 3, 4],
[3, 2, 5]])
print("Array1:")
print(nums1)
print("Array2:")
print(nums2)
print("... | 56 |
# Write a Python program to strip a set of characters from a string.
def strip_chars(str, chars):
return "".join(c for c in str if c not in chars)
print("\nOriginal String: ")
print("The quick brown fox jumps over the lazy dog.")
print("After stripping a,e,i,o,u")
print(strip_chars("The quick brown fox ju... | 54 |
# Program to check whether a matrix is diagonal or not
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the 1st matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([... | 96 |
# Write a NumPy program to test whether any of the elements of a given array is non-zero.
import numpy as np
x = np.array([1, 0, 0, 0])
print("Original array:")
print(x)
print("Test whether any of the elements of a given array is non-zero:")
print(np.any(x))
x = np.array([0, 0, 0, 0])
print("Original array:")
print(... | 66 |
# Write a Python program to find common elements in three lists using sets
# Python3 program to find common elements
# in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
# Converting the arrays into sets
s1 = set(arr1)
s2 = set(arr2)
s3 = set(arr3)
# Calculates intersection... | 137 |
# Write a Python program to check a list is empty or not.
l = []
if not l:
print("List is empty")
| 22 |
# Write a Python program to convert more than one list to nested dictionary.
def nested_dictionary(l1, l2, l3):
result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)]
return result
student_id = ["S001", "S002", "S003", "S004"]
student_name = ["Adina Park", "Leyton Marsh", "Duncan Boyle", "Saim Richards"... | 66 |
# Write a Pandas program to create a comparison of the top 10 years in which the UFO was sighted vs each Month.
import pandas as pd
#Source: https://bit.ly/1l9yjm9
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
most_sightings_years = df['Date_time'].dt.year.value_counts().hea... | 71 |
# numpy string operations | swapcase() function in Python
# Python Program explaining
# numpy.char.swapcase() function
import numpy as geek
in_arr = geek.array(['P4Q R', '4q Rp', 'Q Rp4', 'rp4q'])
print ("input array : ", in_arr)
out_arr = geek.char.swapcase(in_arr)
print ("output swapcasecased array :"... | 44 |
# Write a Python program to Unique Tuple Frequency (Order Irrespective)
# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using tuple() + list comprehension + sorted() + len()
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
# printing original list
pri... | 95 |
# Create a Numpy array filled with all ones in Python
# Python Program to create array with all ones
import numpy as geek
a = geek.ones(3, dtype = int)
print("Matrix a : \n", a)
b = geek.ones([3, 3], dtype = int)
print("\nMatrix b : \n", b) | 47 |
# Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.
import numpy as np
x = [1., 2., 3., 4.]
print("Original array:")
print(x)
print("Largest integer smaller or equal to the division of the inputs:")
print(np.floor_divide(x, 1.5))
| 45 |
# Write a Python program to convert a given list of strings and characters to a single list of characters.
def l_strs_to_l_chars(lst):
result = [i for element in lst for i in element]
return result
colors = ["red", "white", "a", "b", "black", "f"]
print("Original list:")
print(colors)
print("\nConvert the s... | 61 |
# Print the Inverted Full Pyramid Star Pattern
row_size=int(input("Enter the row size:"))
star_print=row_size*2-1
for out in range(row_size,0,-1):
for inn in range(row_size,out,-1):
print(" ",end="")
for p in range(0,star_print):
print("*",end="")
star_print-=2
print("\r") | 30 |
# Write a Python program to Remove keys with substring values
# Python3 code to demonstrate working of
# Remove keys with substring values
# Using any() + generator expression
# initializing dictionary
test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}
# printing original dictionary... | 111 |
# Write a Python program to Extract Symmetric Tuples
# Python3 code to demonstrate working of
# Extract Symmetric Tuples
# Using dictionary comprehension + set()
# initializing list
test_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
# printing original list
print("The original list is : " + str(test... | 99 |
# String slicing in Python to rotate a string
# Function to rotate string left and right by d length
def rotate(input,d):
# slice string in two parts for left and right
Lfirst = input[0 : d]
Lsecond = input[d :]
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
... | 86 |
# Generate Random Numbers From The Uniform Distribution using NumPy in Python
# importing module
import numpy as np
# numpy.random.uniform() method
r = np.random.uniform(size=4)
# printing numbers
print(r) | 29 |
# Write a Python program to reverse each list in a given list of lists.
def reverse_list_lists(nums):
for l in nums:
l.sort(reverse = True)
return nums
nums = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
print("Original list of lists:")
print(nums)
print("\nReverse each list in... | 59 |
# Write a Python program to extract a specified column from a given nested list.
def remove_column(nums, n):
result = [i.pop(n) for i in nums]
return result
list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
n = 0
print("Original Nested list:")
print(list1)
print("Extract 1st column:")
print(remove_column(list1, n))
... | 73 |
# K’th Non-repeating Character in Python using List Comprehension and OrderedDict
# Function to find k'th non repeating character
# in string
from collections import OrderedDict
def kthRepeating(input,k):
# OrderedDict returns a dictionary data
# structure having characters of input
# stri... | 140 |
# Write a Python program to generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
from operator import itemgetter
DEBUG = False # like the built-in __debug__
def spermutations(n):
"""permutations by swapping. Yields: perm, sign"""
sign ... | 350 |
# Write a Python Code for time Complexity plot of Heap Sort
# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important ... | 332 |
# Binary Search (bisect) in Python
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
a = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch... | 72 |
# How to change border color in Tkinter widget in Python
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# Create a Frame for border
border_color = Frame(window, background="red")
# Label Widget inside the Frame
label = Label(border_c... | 68 |
# 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).
:
Solution
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
| 34 |
# Find the number of rows and columns of a given matrix using NumPy in Python
import numpy as np
matrix= np.arange(1,9).reshape((3, 3))
# Original matrix
print(matrix)
# Number of rows and columns of the said matrix
print(matrix.shape) | 38 |
# Write a Python program to print content of elements that contain a specified string of a given web page.
import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print("\nContent of elements that contain 'Python' string... | 54 |
# How to extract youtube data in Python
from youtube_statistics import YTstats
# paste the API key generated by you here
API_KEY = "AIzaSyA-0KfpLK04NpQN1XghxhSlzG-WkC3DHLs"
# paste the channel id here
channel_id = "UC0RhatS1pyxInC00YKjjBqQ"
yt = YTstats(API_KEY, channel_id)
yt.get_channel_statistics()
yt.d... | 39 |
# Write a NumPy program to convert a NumPy array into Python list structure.
import numpy as np
x= np.arange(6).reshape(3, 2)
print("Original array elements:")
print(x)
print("Array to list:")
print(x.tolist())
| 29 |
# 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
string=raw_input("Enter string:")
print("Modified string is:")
print(modify(string)) | 42 |
# 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... | 73 |
# Write a Pandas program to calculate the total number of missing values in a DataFrame.
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[np.nan,np.nan,70002,np.nan,np.nan,70005,np.nan,70010,70003,70012,np.nan,np.... | 54 |
# Write a Python program to count the occurrences of the items in a given list using lambda.
def count_occurrences(nums):
result = dict(map(lambda el : (el, list(nums).count(el)), nums))
return result
nums = [3,4,5,8,0,3,8,5,0,3,1,5,2,3,4,2]
print("Original list:")
print(nums)
print("\nCount the occurrences... | 47 |
# Write a NumPy program to compute the condition number of a given matrix.
import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
print("Original matrix:")
print(a)
print("The condition number of the said matrix:")
print(LA.cond(a))
| 46 |
# Compute the condition number of a given matrix using NumPy in Python
# Importing library
import numpy as np
# Creating a 2X2 matrix
matrix = np.array([[4, 2], [3, 1]])
print("Original matrix:")
print(matrix)
# Output
result = np.linalg.cond(matrix)
print("Condition number of the matrix:")
print(result) | 45 |
# Write a Python program to find the indices of elements of a given list, greater than a specified value.
def test(lst, value):
result = [i for i,val in enumerate(lst) if val > value]
return result
nums = [1234, 1522, 1984, 19372, 1000, 2342, 7626]
print("\nOriginal list:")
print(nums)
val = 3000
print("Indi... | 86 |
# Write a Python program to split a given list into specified sized chunks using itertools module.
from itertools import islice
def split_list(lst, n):
lst = iter(lst)
result = iter(lambda: tuple(islice(lst, n)), ())
return list(result)
nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83]
print("Origi... | 74 |
# Write a NumPy program to save a NumPy array to a text file.
import numpy as np
a = np.arange(1.0, 2.0, 36.2)
np.savetxt('file.out', a, delimiter=',')
| 26 |
# Write a NumPy program to stack arrays in sequence horizontally (column wise).
import numpy as np
print("\nOriginal arrays:")
x = np.arange(9).reshape(3,3)
y = x*3
print("Array-1")
print(x)
print("Array-2")
print(y)
new_array = np.hstack((x,y))
print("\nStack arrays in sequence horizontally:")
print(new_array)... | 38 |
# Write a NumPy program to merge three given NumPy arrays of same shape.
import numpy as np
arr1 = np.random.random(size=(25, 25, 1))
arr2 = np.random.random(size=(25, 25, 1))
arr3 = np.random.random(size=(25, 25, 1))
print("Original arrays:")
print(arr1)
print(arr2)
print(arr3)
result = np.concatenate((arr1, arr2, ... | 47 |
# Write a Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
import re
string = "ThisIsGeeksforGeeks !, 123"
# Creating separate lists using
# the re.findall() method.
uppercase_characters = re.findall(r"[A-Z]", string)
lowercase_characters = re.findall(r"[a-z]", ... | 77 |
# Write a Python program to Extract Unique values dictionary values
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best... | 109 |
# Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print("Original set elements:")
print(color_list_1)
print(color_list_2)
print("\nDifferenct of color_list_1... | 48 |
# Write a NumPy program to test whether all elements in an array evaluate to True.
import numpy as np
print(np.all([[True,False],[True,True]]))
print(np.all([[True,True],[True,True]]))
print(np.all([10, 20, 0, -50]))
print(np.all([10, 20, -50]))
| 29 |
# Count the number of white spaces in a Sentence
str=input("Enter the String:")
count = 0
for i in range(len(str)):
if str[i] == ' ':
count+=1
print("Number of white space in a string are ",count) | 35 |
# Python Program to Read a Number n And Print the Series "1+2+…..+n= "
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print() | 33 |
# 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 (i... | 64 |
# Write a NumPy program to divide each row by a vector element.
import numpy as np
x = np.array([[20,20,20],[30,30,30],[40,40,40]])
print("Original array:")
print(x)
v = np.array([20,30,40])
print("Vector:")
print(v)
print(x / v[:,None])
| 31 |
# Write a Python program to find the indexes of all None items in a given list.
def relative_order(lst):
result = [i for i in range(len(lst)) if lst[i] == None]
return result
nums = [1, None, 5, 4,None, 0, None, None]
print("Original list:")
print(nums)
print("\nIndexes of all None items of the list:")
prin... | 53 |
# Scrape LinkedIn Using Selenium And Beautiful Soup in Python
from selenium import webdriver
from bs4 import BeautifulSoup
import time
# Creating a webdriver instance
driver = webdriver.Chrome("Enter-Location-Of-Your-Web-Driver")
# This instance will be used to log into LinkedIn
# Opening linkedIn's login page
... | 133 |
# Write a Python program to find all index positions of the maximum and minimum values in a given list of numbers.
def position_max_min(nums):
max_val = max(nums)
min_val = min(nums)
max_result = [i for i, j in enumerate(nums) if j == max_val]
min_result = [i for i, j in enumerate(nums) if j == min_v... | 87 |
#
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
| 37 |
# Write a Python program to print a nested lists (each list on a new line) using the print() function.
colors = [['Red'], ['Green'], ['Black']]
print('\n'.join([str(lst) for lst in colors]))
| 30 |
# Write a Python program to convert a given list of lists to a dictionary.
def test(lst):
result = {item[0]: item[1:] for item in lst}
return result
students = [[1, 'Jean Castro', 'V'], [2, 'Lula Powell', 'V'], [3, 'Brian Howell', 'VI'], [4, 'Lynne Foster', 'VI'], [5, 'Zachary Simon', 'VII']]
print("\nOrig... | 64 |
# Program to Find nth Pronic Number
import math
rangenumber=int(input("Enter a Nth Number:"))
c = 0
letest = 0
num = 1
while c != rangenumber:
flag = 0
for j in range(0, num + 1):
if j * (j + 1) == num:
flag = 1
break
if flag == 1:
c+=1
letest = num... | 66 |
# Write a Pandas program to split a dataset, group by one column and get mean, min, and max values by group. Using the following dataset find the mean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id).
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('di... | 86 |
# Write a Python program to count repeated characters in a string.
import collections
str1 = 'thequickbrownfoxjumpsoverthelazydog'
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s %d' % (c, d[c]))
| 42 |
# Write a NumPy program to count the number of dimensions, number of elements and number of bytes for each element in a given array.
import numpy as np
print("\nOriginal arrays:")
x = np.array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
print(x)
pr... | 78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.