code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python program to create a doubly linked list and print nodes from current position to first node.
class Node(object):
# Doubly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def print_foward(self):
for node in self.iter():
print(node)
def print_backward(self):
current = self.tail
while current:
print(current.data)
current = current.prev
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print("Print Items in the Doubly linked backwards:")
items.print_backward()
| 141 |
# Write a Pandas program to split a given dataframe into groups and display target column as a list of unique values.
import pandas as pd
df = pd.DataFrame( {'id' : ['A','A','A','A','A','A','B','B','B','B','B'],
'type' : [1,1,1,1,2,2,1,1,1,2,2],
'book' : ['Math','Math','English','Physics','Math','English','Physics','English','Physics','English','English']})
print("Original DataFrame:")
print(df)
new_df = df[['id', 'type', 'book']].drop_duplicates()\
.groupby(['id','type'])['book']\
.apply(list)\
.reset_index()
new_df['book'] = new_df.apply(lambda x: (','.join([str(s) for s in x['book']])), axis = 1)
print("\nList all unique values in a group:")
print(new_df)
| 69 |
# Write a Python program to Stack using Doubly Linked List
# A complete working Python program to demonstrate all
# stack operations using a doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.prev = None # Initialize prev as null
# Stack class contains a Node object
class Stack:
# Function to initialize head
def __init__(self):
self.head = None
# Function to add an element data in the stack
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
self.head.prev = new_node
new_node.next = self.head
new_node.prev = None
self.head = new_node
# Function to pop top element and return the element from the stack
def pop(self):
if self.head is None:
return None
elif self.head.next is None:
temp = self.head.data
self.head = None
return temp
else:
temp = self.head.data
self.head = self.head.next
self.head.prev = None
return temp
# Function to return top element in the stack
def top(self):
return self.head.data
# Function to return the size of the stack
def size(self):
temp = self.head
count = 0
while temp is not None:
count = count + 1
temp = temp.next
return count
# Function to check if the stack is empty or not
def isEmpty(self):
if self.head is None:
return True
else:
return False
# Function to print the stack
def printstack(self):
print("stack elements are:")
temp = self.head
while temp is not None:
print(temp.data, end ="->")
temp = temp.next
# Code execution starts here
if __name__=='__main__':
# Start with the empty stack
stack = Stack()
# Insert 4 at the beginning. So stack becomes 4->None
print("Stack operations using Doubly LinkedList")
stack.push(4)
# Insert 5 at the beginning. So stack becomes 4->5->None
stack.push(5)
# Insert 6 at the beginning. So stack becomes 4->5->6->None
stack.push(6)
# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
stack.push(7)
# Print the stack
stack.printstack()
# Print the top element
print("\nTop element is ", stack.top())
# Print the stack size
print("Size of the stack is ", stack.size())
# pop the top element
stack.pop()
# pop the top element
stack.pop()
# two elements are popped
# Print the stack
stack.printstack()
# Print True if the stack is empty else False
print("\nstack is empty:", stack.isEmpty())
#This code is added by Suparna Raut | 392 |
# Write a Pandas program to split a given dataset, group by one column and apply an aggregate function to few columns and another aggregate function to the rest of the columns of the dataframe.
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001],
'sale_jan':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 1760, 2983.43, 480.4, 1250.45, 75.29,1045.6],
'sale_feb':[250.5, 170.65, 15.26, 110.5, 598.5, 1400.6, 2760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_mar':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_apr':[150.5, 270.65, 95.26, 210.5, 948.5, 2400.6, 760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_may':[130.5, 270.65, 65.26, 310.5, 948.5, 2400.6, 760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_jun':[150.5, 270.65, 45.26, 110.5, 948.5, 3400.6, 5760, 983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_jul':[950.5, 270.65, 65.26, 210.5, 948.5, 2400.6, 5760, 983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_aug':[150.5, 70.65, 65.26, 110.5, 948.5, 400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_sep':[150.5, 270.65, 65.26, 110.5, 948.5, 200.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_oct':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_nov':[150.5, 270.65, 95.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'sale_dec':[150.5, 70.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6]
})
print("Original Orders DataFrame:")
print(df)
print("\Result after group on salesman_id and apply different aggregate functions:")
df = df.groupby('salesman_id').agg(lambda x : x.sum() if x.name in ['sale_jan','sale_feb','sale_mar'] else x.mean())
print(df)
| 219 |
# Write a Python program to assess if a file is closed or not.
f = open('abc.txt','r')
print(f.closed)
f.close()
print(f.closed)
| 20 |
# Write a Python program to get the proleptic Gregorian ordinal of a given date.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nProleptic Gregorian ordinal of the date:")
print(arrow.utcnow().toordinal())
| 30 |
# Write a NumPy program to extract first element of the second row and fourth element of fourth row 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: First element of the second row and fourth element of fourth row ")
print(arra_data[[1,3], [0,3]])
| 52 |
# Write a Python program to sort a list of elements using Pancake sort.
def pancake_sort(nums):
arr_len = len(nums)
while arr_len > 1:
mi = nums.index(max(nums[0:arr_len]))
nums = nums[mi::-1] + nums[mi+1:len(nums)]
nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]
arr_len -= 1
return nums
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(pancake_sort(nums))
| 57 |
# Write a NumPy program to Create a 1-D array of 30 evenly spaced elements between 2.5. and 6.5, inclusive.
import numpy as np
x = np.linspace(2.5, 6.5, 30)
print(x)
| 30 |
# Write a Python program to print a dictionary in table format.
my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}
for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
print(*row)
| 27 |
# Write a Python program to get every element that exists in any of the two given lists once, after applying the provided function to each element of both.
def union_by_el(x, y, fn):
_x = set(map(fn, x))
return list(set(x + [item for item in y if fn(item) not in _x]))
from math import floor
print(union_by_el([4.1], [2.2, 4.3], floor))
| 58 |
# Write a Python program to generate a 3*4*6 3D array whose each element is *.
array = [[ ['*' for col in range(6)] for col in range(4)] for row in range(3)]
print(array)
| 33 |
# Write a Pandas program to find the all the business quarterly begin and end dates of a specified year.
import pandas as pd
q_start_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQS-JUN')
q_end_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQ-JUN')
print("All the business quarterly begin dates of 2020:")
print(q_start_dates.values)
print("\nAll the business quarterly end dates of 2020:")
print(q_end_dates.values)
| 52 |
# Lambda with if but without else in Python
# Lambda function with if but without else.
square = lambda x : x*x if(x > 0)
print(square(6)) | 27 |
# Write a Python program to create a list of random integers and randomly select multiple items from the said list. Use random.sample()
import random
print("Create a list of random integers:")
population = range(0, 100)
nums_list = random.sample(population, 10)
print(nums_list)
no_elements = 4
print("\nRandomly select",no_elements,"multiple items from the said list:")
result_elements = random.sample(nums_list, no_elements)
print(result_elements)
no_elements = 8
print("\nRandomly select",no_elements,"multiple items from the said list:")
result_elements = random.sample(nums_list, no_elements)
print(result_elements)
| 70 |
# a href="#EDITOR">Go to the editor</a>
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
| 28 |
# Write a Python program to find the last occurrence of a specified item in a given list.
def last_occurrence(l1, ch):
return ''.join(l1).rindex(ch)
chars = ['s','d','f','s','d','f','s','f','k','o','p','i','w','e','k','c']
print("Original list:")
print(chars)
ch = 'f'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'c'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'k'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'w'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
| 73 |
# Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number.
def sieve_of_Eratosthenes(num):
limitn = num+1
not_prime_num = set()
prime_nums = []
for i in range(2, limitn):
if i in not_prime_num:
continue
for f in range(i*2, limitn, i):
not_prime_num.add(f)
prime_nums.append(i)
return prime_nums
print(sieve_of_Eratosthenes(100));
| 50 |
# Write a Python program to create a deque from an existing iterable object.
import collections
even_nums = (2, 4, 6)
print("Original tuple:")
print(even_nums)
print(type(even_nums))
even_nums_deque = collections.deque(even_nums)
print("\nOriginal deque:")
print(even_nums_deque)
even_nums_deque.append(8)
even_nums_deque.append(10)
even_nums_deque.append(12)
even_nums_deque.appendleft(2)
print("New deque from an existing iterable object:")
print(even_nums_deque)
print(type(even_nums_deque))
| 44 |
# Write a Python program to display half diamond pattern of numbers with star border
# function to display the pattern up to n
def display(n):
print("*")
for i in range(1, n+1):
print("*", end="")
# for loop to display number up to i
for j in range(1, i+1):
print(j, end="")
# for loop to display number in reverse direction
for j in range(i-1, 0, -1):
print(j, end="")
print("*", end="")
print()
# for loop to display i in reverse direction
for i in range(n-1, 0, -1):
print("*", end="")
for j in range(1, i+1):
print(j, end="")
for j in range(i-1, 0, -1):
print(j, end="")
print("*", end="")
print()
print("*")
# driver code
n = 5
print('\nFor n =', n)
display(n)
n = 3
print('\nFor n =', n)
display(n) | 125 |
# Ways to remove i’th character from string in Python
# Python code to demonstrate
# method to remove i'th character
# Naive Method
# Initializing String
test_str = "GeeksForGeeks"
# Printing original string
print ("The original string is : " + test_str)
# Removing char at pos 3
# using loop
new_str = ""
for i in range(len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
# Printing string after removal
print ("The string after removal of i'th character : " + new_str) | 85 |
# Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
:
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
| 38 |
# Write a Python program to Remove Tuples of Length K
# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using list comprehension
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 1
# 1 liner to perform task
# filter just lengths other than K
# len() used to compute length
res = [ele for ele in test_list if len(ele) != K]
# printing result
print("Filtered list : " + str(res)) | 102 |
# How to switch to new window in Selenium for Python
# import modules
from selenium import webdriver
import time
# provide the path for chromedriver
PATH = "C:/chromedriver.exe"
# pass on the path to driver for working
driver = webdriver.Chrome(PATH) | 41 |
# Write a Python program to round every number of a given list of numbers and print the total sum multiplied by the length of the list.
nums = [22.4, 4.0, -16.22, -9.10, 11.00, -12.22, 14.20, -5.20, 17.50]
print("Original list: ", nums)
print("Result:")
lenght=len(nums)
print(sum(list(map(round,nums))* lenght))
| 46 |
# Write a Python program to Replace all occurrences of a substring in a string
# Python3 code to demonstrate working of
# Swap Binary substring
# Using translate()
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Swap Binary substring
# Using translate()
temp = str.maketrans("geek", "abcd")
test_str = test_str.translate(temp)
# printing result
print("The string after swap : " + str(test_str)) | 72 |
# How to compute numerical negative value for all elements in a given NumPy array in Python
# importing library
import numpy as np
# creating a array
x = np.array([-1, -2, -3,
1, 2, 3, 0])
print("Printing the Original array:",
x)
# converting array elements to
# its corresponding negative value
r1 = np.negative(x)
print("Printing the negative value of the given array:",
r1) | 64 |
# Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length using lambda.
def check_string(str1):
messg = [
lambda str1: any(x.isupper() for x in str1) or 'String must have 1 upper case character.',
lambda str1: any(x.islower() for x in str1) or 'String must have 1 lower case character.',
lambda str1: any(x.isdigit() for x in str1) or 'String must have 1 number.',
lambda str1: len(str1) >= 7 or 'String length should be atleast 8.',]
result = [x for x in [i(str1) for i in messg] if x != True]
if not result:
result.append('Valid string.')
return result
s = input("Input the string: ")
print(check_string(s))
| 116 |
# Write a Python program to Flatten Tuples List to String
# Python3 code to demonstrate working of
# Flatten Tuples List to String
# using join() + list comprehension
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
# printing original tuples list
print("The original list : " + str(test_list))
# Flatten Tuples List to String
# using join() + list comprehension
res = ' '.join([idx for tup in test_list for idx in tup])
# printing result
print("Tuple list converted to String is : " + res) | 95 |
# Write a NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays.
import numpy as np
x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100])
y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001])
print("Original numbers:")
print(x)
print(y)
print("Comparison - equal:")
print(np.equal(x, y))
print("Comparison - equal within a tolerance:")
print(np.allclose(x, y))
| 64 |
# Python Program To Find the Smallest and Largest Elements in the Binary Search Tree
class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)
def search(self, key):
if self.key > key:
if self.left is not None:
return self.left.search(key)
else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key)
else:
return None
return self
class BSTree:
def __init__(self):
self.root = None
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
def search(self, key):
if self.root is not None:
return self.root.search(key)
def get_smallest(self):
if self.root is not None:
current = self.root
while current.left is not None:
current = current.left
return current.key
def get_largest(self):
if self.root is not None:
current = self.root
while current.right is not None:
current = current.right
return current.key
bstree = BSTree()
print('Menu (this assumes no duplicate keys)')
print('add <key>')
print('smallest')
print('largest')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
if operation == 'smallest':
smallest = bstree.get_smallest()
print('Smallest element: {}'.format(smallest))
if operation == 'largest':
largest = bstree.get_largest()
print('Largest element: {}'.format(largest))
elif operation == 'quit':
break | 233 |
# Write a NumPy program to convert 1-D arrays as columns into a 2-D array.
import numpy as np
a = np.array((10,20,30))
b = np.array((40,50,60))
c = np.column_stack((a, b))
print(c)
| 30 |
# How to get the floor, ceiling and truncated values of the elements of a numpy array in Python
# Import the numpy library
import numpy as np
# Initialize numpy array
a = np.array([1.2])
# Get floor value
a = np.floor(a)
print(a) | 43 |
# Write a Python program to get all values from an enum class.
from enum import IntEnum
class Country(IntEnum):
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
country_code_list = list(map(int, Country))
print(country_code_list)
| 42 |
# Simple Diamond Pattern in Python
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size//2+2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print *
if j < i-1:
print(' ', end=" ")
elif j > spaces:
print(' ', end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size-1):
print(' ', end=" ")
else:
print('*', end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print() | 121 |
# Write a Python program to find the second smallest number in a list.
def second_smallest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] == numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[1]
print(second_smallest([1, 2, -8, -2, 0, -2]))
print(second_smallest([1, 1, 0, 0, 2, -2, -2]))
print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_smallest([2,2]))
print(second_smallest([2]))
| 71 |
# Write a Pandas program to create a line plot of the opening, closing stock prices 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-09-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df2 = df.loc[new_df]
plt.figure(figsize=(10,10))
df2.plot(x='Date', y=['Open', 'Close']);
plt.suptitle('Opening/Closing stock prices of Alphabet Inc.,\n 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.xlabel("Date",fontsize=12, color='black')
plt.ylabel("$ price", fontsize=12, color='black')
plt.show()
| 75 |
# Write a Python program to convert timezone from local to utc, utc to local or specified zones.
import arrow
utc = arrow.utcnow()
print("utc:")
print(utc)
print("\nutc to local:")
print(utc.to('local'))
print("\nlocal to utc:")
print(utc.to('local').to('utc'))
print("\nutc to specific location:")
print(utc.to('US/Pacific'))
| 38 |
# Write a NumPy program to extract all the elements of the first and fourth columns 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: All the elements of the first and fourth columns ")
print(arra_data[:, [0,3]])
| 46 |
# Write a Pandas program to extract only number 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({
'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
'address': ['7277 Surrey Ave.','920 N. Bishop Ave.','9910 Golden Star St.', '25 Dunbar St.', '17 West Livingston Court']
})
print("Original DataFrame:")
print(df)
def find_number(text):
num = re.findall(r'[0-9]+',text)
return " ".join(num)
df['number']=df['address'].apply(lambda x: find_number(x))
print("\Extracting numbers from dataframe columns:")
print(df)
| 72 |
# Program to Find gcd or hcf of two numbers
print("Enter two number to find G.C.D")
num1=int(input())
num2=int(input())
while(num1!=num2):
if (num1 > num2):
num1 = num1 - num2
else:
num2= num2 - num1
print("G.C.D is",num1)
| 35 |
# Write a Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list.
from functools import reduce
from operator import getitem
def test(d, selectors):
return reduce(getitem, selectors, d)
users = {
'Carla ': {
'name': {
'first': 'Carla ',
'last': 'Russell'
},
'postIds': [1, 2, 3, 4, 5]
}
}
print(test(users, ['Carla ', 'name', 'last']))
print(test(users, ['Carla ', 'postIds', 1]))
| 71 |
# Write a Python Dictionary to find mirror characters in a string
# function to mirror characters of a string
def mirrorChars(input,k):
# create dictionary
original = 'abcdefghijklmnopqrstuvwxyz'
reverse = 'zyxwvutsrqponmlkjihgfedcba'
dictChars = dict(zip(original,reverse))
# separate out string after length k to change
# characters in mirror
prefix = input[0:k-1]
suffix = input[k-1:]
mirror = ''
# change into mirror
for i in range(0,len(suffix)):
mirror = mirror + dictChars[suffix[i]]
# concat prefix and mirrored part
print (prefix+mirror)
# Driver program
if __name__ == "__main__":
input = 'paradox'
k = 3
mirrorChars(input,k) | 91 |
# Write a Pandas program to swap the cases of a specified character column 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_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print("Original DataFrame:")
print(df)
print("\nSwapp cases in comapny_code:")
df['swapped_company_code'] = list(map(lambda x: x.swapcase(), df['company_code']))
print(df)
| 53 |
# Write a Python program to find the difference between two list including duplicate elements.
def list_difference(l1,l2):
result = list(l1)
for el in l2:
result.remove(el)
return result
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print("Original lists:")
print(l1)
print(l2)
print("\nDifference between two said list including duplicate elements):")
print(list_difference(l1,l2))
| 46 |
# Write a Python program to Filter Range Length Tuples
# Python3 code to demonstrate working of
# Filter Range Length Tuples
# Using list comprehension + len()
# Initializing list
test_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing desired lengths
i, j = 2, 3
# Filter Range Length Tuples
# Using list comprehension + len()
res = [sub for sub in test_list if len(sub) >= i and len(sub) <= j]
# printing result
print("The tuple list after filtering range records : " + str(res)) | 107 |
# Compute the Kronecker product of two multidimension NumPy arrays in Python
# Importing required modules
import numpy
# Creating arrays
array1 = numpy.array([[1, 2], [3, 4]])
print('Array1:\n', array1)
array2 = numpy.array([[5, 6], [7, 8]])
print('\nArray2:\n', array2)
# Computing the Kronecker Product
kroneckerProduct = numpy.kron(array1, array2)
print('\nArray1 ⊗ Array2:')
print(kroneckerProduct) | 50 |
# Write a Python program to Minimum number of subsets with distinct elements using Counter
# Python program to find Minimum number of
# subsets with distinct elements using Counter
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
def minSubsets(input):
# calculate frequency of each element
freqDict = Counter(input)
# get list of all frequency values
# print maximum from it
print (max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = [1, 2, 3, 3]
minSubsets(input) | 85 |
# Write a Python program to construct an infinite iterator that returns evenly spaced values starting with a specified number and step.
import itertools as it
start = 10
step = 1
print("The starting number is ", start, "and step is ",step)
my_counter = it.count(start, step)
# Following loop will run for ever
print("The said function print never-ending items:")
for i in my_counter:
print(i)
| 64 |
# Conditional operation on Pandas DataFrame columns in Python
# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'],
'Last Price':[1200, 1500, 1600, 352],
'Updated Price':[1250, 1450, 1550, 400],
'Discount':[10, 10, 10, 10]})
# Print the dataframe
print(df) | 51 |
# Write a Python program to generate a random integer between 0 and 6 - excluding 6, random integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and random date between two dates. Use random.randrange()
import random
import datetime
print("Generate a random integer between 0 and 6:")
print(random.randrange(5))
print("Generate random integer between 5 and 10, excluding 10:")
print(random.randrange(start=5, stop=10))
print("Generate random integer between 0 and 10, with a step of 3:")
print(random.randrange(start=0, stop=10, step=3))
print("\nRandom date between two dates:")
start_dt = datetime.date(2019, 2, 1)
end_dt = datetime.date(2019, 3, 1)
time_between_dates = end_dt - start_dt
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_dt + datetime.timedelta(days=random_number_of_days)
print(random_date)
| 116 |
# Write a NumPy program to add two arrays A and B of sizes (3,3) and (,3).
import numpy as np
A = np.ones((3,3))
B = np.arange(3)
print("Original array:")
print("Array-1")
print(A)
print("Array-2")
print(B)
print("A + B:")
new_array = A + B
print(new_array)
| 42 |
# Write a Python program to remove the characters which have odd index values of a given string.
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))
| 42 |
# Write a Python program to Swap elements in String list
# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in test_list]
# printing result
print ("List after performing character swaps : " + str(res)) | 85 |
# Write a Pandas program to calculate all the sighting days of the unidentified flying object (ufo) from current date.
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
now = pd.to_datetime('today')
print("Original Dataframe:")
print(df.head())
print("\nCurrent date:")
print(now)
| 39 |
# Write a Pandas program to split the following dataframe into groups based on all columns and calculate Groupby value counts on the dataframe.
import pandas as pd
df = pd.DataFrame( {'id' : [1, 2, 1, 1, 2, 1, 2],
'type' : [10, 15, 11, 20, 21, 12, 14],
'book' : ['Math','English','Physics','Math','English','Physics','English']})
print("Original DataFrame:")
print(df)
result = df.groupby(['id', 'type', 'book']).size().unstack(fill_value=0)
print("\nResult:")
print(result)
| 62 |
# numpy.var() in Python
# Python Program illustrating
# numpy.var() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print("arr : ", arr)
print("var of arr : ", np.var(arr))
print("\nvar of arr : ", np.var(arr, dtype = np.float32))
print("\nvar of arr : ", np.var(arr, dtype = np.float64)) | 53 |
# Write a Python program to detect the number of local variables declared in a function.
def abc():
x = 1
y = 2
str1= "w3resource"
print("Python Exercises")
print(abc.__code__.co_nlocals)
| 29 |
# How to check if a Python variable exists
def func():
# defining local variable
a_variable = 0
# using locals() function
# for checking existence in symbol table
is_local_var = "a_variable" in locals()
# printing result
print(is_local_var)
# driver code
func() | 42 |
# Write a Pandas program to add summation to a row of the given excel file.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
sum_row=df[["Production", "Labor_Hours"]].sum()
df_sum=pd.DataFrame(data=sum_row).T
df_sum=df_sum.reindex(columns=df.columns)
df_sum
| 32 |
# Write a NumPy program to generate a uniform, non-uniform random sample from a given 1-D array with and without replacement.
import numpy as np
print("Generate a uniform random sample with replacement:")
print(np.random.choice(7, 5))
print("\nGenerate a uniform random sample without replacement:")
print(np.random.choice(7, 5, replace=False))
print("\nGenerate a non-uniform random sample with replacement:")
print(np.random.choice(7, 5, p=[0.1, 0.2, 0, 0.2, 0.4, 0, 0.1]))
print("\nGenerate a uniform random sample without replacement:")
print(np.random.choice(7, 5, replace=False, p=[0.1, 0.2, 0, 0.2, 0.4, 0, 0.1]))
| 77 |
# Write a Python program to Get Function Signature
from inspect import signature
# declare a function gfg with some
# parameter
def gfg(x:str, y:int):
pass
# with the help of signature function
# store signature of the function in
# variable t
t = signature(gfg)
# print the signature of the function
print(t)
# print the annonation of the parameter
# of the function
print(t.parameters['x'])
# print the annonation of the parameter
# of the function
print(t.parameters['y'].annotation) | 78 |
# Program to check if a string contains any special character in Python
// C++ program to check if a string
// contains any special character
// import required packages
#include <iostream>
#include <regex>
using namespace std;
// Function checks if the string
// contains any special character
void run(string str)
{
// Make own character set
regex regx("[@_!#$%^&*()<>?/|}{~:]");
// Pass the string in regex_search
// method
if(regex_search(str, regx) == 0)
cout << "String is accepted";
else
cout << "String is not accepted.";
}
// Driver Code
int main()
{
// Enter the string
string str = "Geeks$For$Geeks";
// Calling run function
run(str);
return 0;
}
// This code is contributed by Yash_R | 113 |
# Write a Pandas program to create a heatmap (rectangular data as a color-encoded matrix) for comparison of the top 10 years in which the UFO was sighted vs each Month.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#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().head(10)
def is_top_years(year):
if year in most_sightings_years.index:
return year
month_vs_year = df.pivot_table(columns=df['Date_time'].dt.month,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city')
month_vs_year.columns = month_vs_year.columns.astype(int)
print("\nHeatmap for comparison of the top 10 years in which the UFO was sighted vs each month:")
plt.figure(figsize=(10,8))
ax = sns.heatmap(month_vs_year, vmin=0, vmax=4)
ax.set_xlabel('Month').set_size(20)
ax.set_ylabel('Year').set_size(20)
| 93 |
# Write a Python program to Get list of running processes
import wmi
# Initializing the wmi constructor
f = wmi.WMI()
# Printing the header for the later columns
print("pid Process name")
# Iterating through all the running processes
for process in f.Win32_Process():
# Displaying the P_ID and P_Name of the process
print(f"{process.ProcessId:<10} {process.Name}") | 54 |
# Write a Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
# Python code to find if we can make first string
# from second by deleting some characters from
# second and rearranging remaining characters.
from collections import Counter
def makeString(str1,str2):
# convert both strings into dictionaries
# output will be like str1="aabbcc",
# dict1={'a':2,'b':2,'c':2}
# str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}
dict1 = Counter(str1)
dict2 = Counter(str2)
# take intersection of two dictionries
# output will be result = {'a':1,'b':2,'c':2}
result = dict1 & dict2
# compare resultant dictionary with first
# dictionary comparison first compares keys
# and then compares their corresponding values
return result == dict1
# Driver program
if __name__ == "__main__":
str1 = 'ABHISHEKsinGH'
str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
if (makeString(str1,str2)==True):
print("Possible")
else:
print("Not Possible") | 132 |
# Write a Python program to delete the first item from a singly linked list.
class Node:
# Singly linked node
def __init__(self, data=None):
self.data = data
self.next = None
class singly_linked_list:
def __init__(self):
# Createe an empty list
self.tail = None
self.head = None
self.count = 0
def append_item(self, data):
#Append items on the list
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.count += 1
def delete_item(self, data):
# Delete an item from the list
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def iterate_item(self):
# Iterate the list.
current_item = self.tail
while current_item:
val = current_item.data
current_item = current_item.next
yield val
items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print("Original list:")
for val in items.iterate_item():
print(val)
print("\nAfter removing the first item from the list:")
items.delete_item('PHP')
for val in items.iterate_item():
print(val)
| 168 |
# Write a Python program to calculate the sum of the numbers in a list between the indices of a specified range.
def sum_Range_list(nums, m, n):
sum_range = 0
for i in range(m, n+1, 1):
sum_range += nums[i]
return sum_range
nums = [2,1,5,6,8,3,4,9,10,11,8,12]
print("Original list:")
print(nums)
m = 8
n = 10
print("Range:",m,",",n)
print("\nSum of the specified range:")
print(sum_Range_list(nums, m, n))
| 61 |
# Lambda expression in Python to rearrange positive and negative numbers
# Function to rearrange positive and negative elements
def Rearrange(arr):
# First lambda expression returns list of negative numbers
# in arr.
# Second lambda expression returns list of positive numbers
# in arr.
return [x for x in arr if x < 0] + [x for x in arr if x >= 0]
# Driver function
if __name__ == "__main__":
arr = [12, 11, -13, -5, 6, -7, 5, -3, -6]
print (Rearrange(arr)) | 85 |
# Write a python program to check whether two lists are circularly identical.
list1 = [10, 10, 0, 0, 10]
list2 = [10, 10, 10, 0, 0]
list3 = [1, 10, 10, 0, 0]
print('Compare list1 and list2')
print(' '.join(map(str, list2)) in ' '.join(map(str, list1 * 2)))
print('Compare list1 and list3')
print(' '.join(map(str, list3)) in ' '.join(map(str, list1 * 2)))
| 60 |
# Write a Python program to Filter Strings combination of K substrings
# Python3 code to demonstrate working of
# Filter Strings combination of K substrings
# Using permutations() + map() + join() + set() + loop
from itertools import permutations
# initializing list
test_list = ["geeks4u", "allbest", "abcdef"]
# printing string
print("The original list : " + str(test_list))
# initializing substring list
substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"]
# initializing K
K = 3
# getting all permutations
perms = list(set(map(''.join, permutations(substr_list, r = K))))
# using loop to check permutations with list
res = []
for ele in perms:
if ele in test_list:
res.append(ele)
# printing results
print("Strings after joins : " + str(res)) | 119 |
# Write a Python program to get all possible two digit letter combinations from a digit (1 to 9) string.
def letter_combinations(digits):
if digits == "":
return []
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
}
result = [""]
for num in digits:
temp = []
for an in result:
for char in string_maps[num]:
temp.append(an + char)
result = temp
return result
digit_string = "47"
print(letter_combinations(digit_string))
digit_string = "29"
print(letter_combinations(digit_string))
| 84 |
# Write a Python program to insert an element at the beginning of a given OrderedDictionary.
from collections import OrderedDict
color_orderdict = OrderedDict([('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')])
print("Original OrderedDict:")
print(color_orderdict)
print("Insert an element at the beginning of the said OrderedDict:")
color_orderdict.update({'color4':'Orange'})
color_orderdict.move_to_end('color4', last = False)
print("\nUpdated OrderedDict:")
print(color_orderdict)
| 49 |
# Difference of two columns in Pandas dataframe in Python
import pandas as pd
# Create a DataFrame
df1 = { 'Name':['George','Andrea','micheal',
'maggie','Ravi','Xien','Jalpa'],
'score1':[62,47,55,74,32,77,86],
'score2':[45,78,44,89,66,49,72]}
df1 = pd.DataFrame(df1,columns= ['Name','score1','score2'])
print("Given Dataframe :\n", df1)
# getting Difference
df1['Score_diff'] = df1['score1'] - df1['score2']
print("\nDifference of score1 and score2 :\n", df1) | 48 |
# Write a Python program to create non-repeated combinations of Cartesian product of four given list of numbers.
import itertools as it
mums1 = [1, 2, 3, 4]
mums2 = [5, 6, 7, 8]
mums3 = [9, 10, 11, 12]
mums4 = [13, 14, 15, 16]
print("Original lists:")
print(mums1)
print(mums2)
print(mums3)
print(mums4)
print("\nSum of the specified range:")
for i in it.product([tuple(mums1)], it.permutations(mums2), it.permutations(mums3), it.permutations(mums4)):
print(i)
| 65 |
# Write a NumPy program to compute the determinant of a given square array.
import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0], [1, 2]])
print("Original 2-d array")
print(a)
print("Determinant of the said 2-D array:")
print(np.linalg.det(a))
| 41 |
# Write a Python Dictionary | Check if binary representations of two numbers are anagram
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1,num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin(num1)[2:]
bin2 = bin(num2)[2:]
# append zeros in shorter string
zeros = abs(len(bin1)-len(bin2))
if (len(bin1)>len(bin2)):
bin2 = zeros * '0' + bin2
else:
bin1 = zeros * '0' + bin1
# convert binary representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 == dict2:
print('Yes')
else:
print('No')
# Driver program
if __name__ == "__main__":
num1 = 8
num2 = 4
checkAnagram(num1,num2)
| 130 |
# Write a NumPy program to find the closest value (to a given scalar) in an array.
import numpy as np
x = np.arange(100)
print("Original array:")
print(x)
a = np.random.uniform(0,100)
print("Value to compare:")
print(a)
index = (np.abs(x-a)).argmin()
print(x[index])
| 38 |
# Program to find the transpose of a matrix
# 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 matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
# Compute transpose of two matrices
tran_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0,row_size):
for j in range(0,col_size):
tran_matrix[i][j]=matrix[j][i]
# display transpose of the matrix
print("Transpose of the Given Matrix is:")
for m in tran_matrix:
print(m) | 89 |
# Write a Python program to get the last part of a string before a specified character.
str1 = 'https://www.w3resource.com/python-exercises/string'
print(str1.rsplit('/', 1)[0])
print(str1.rsplit('-', 1)[0])
| 24 |
# Write a Pandas program to filter those records which not appears in a given list from world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
new_w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(new_w_a_con.head())
print("\nSelect all rows which not appears in a given list:")
who_region = ["Africa", "Eastern Mediterranean", "Europe"]
flt_wine = ~new_w_a_con["WHO region"].isin(who_region)
print(new_w_a_con[flt_wine])
| 60 |
# Write a Python program to build a list, using an iterator function and an initial seed value.
def unfold(fn, seed):
def fn_generator(val):
while True:
val = fn(val[1])
if val == False: break
yield val[0]
return [i for i in fn_generator([None, seed])]
f = lambda n: False if n > 40 else [-n, n + 10]
print(unfold(f, 10))
| 58 |
# Program to Find the sum of series 3+33+333.....+N
n=int(input("Enter the range of number:"))sum=0p=3for i in range(1,n+1): sum += p p=(p*10)+3print("The sum of the series = ",sum) | 27 |
# Write a NumPy program to create a three-dimension array with shape (300,400,5) and set to a variable. Fill the array elements with values using unsigned integer (0 to 255).
import numpy as np
np.random.seed(32)
nums = np.random.randint(low=0, high=256, size=(300, 400, 5), dtype=np.uint8)
print(nums)
| 44 |
# Write a Python program to randomize the order of the values of an list, returning a new list.
from copy import deepcopy
from random import randint
def shuffle_list(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
nums = [1, 2, 3, 4, 5, 6]
print("Original list: ",nums)
print("\nShuffle the elements of the said list:")
print(shuffle_list(nums))
| 70 |
# Write a Python program to create a table and insert some records in that table. Finally selects all rows from the table and display the records.
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);
""")
conn.commit()
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("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.")
| 131 |
# Program to find the sum of series 1+X+X^2/2!+X^3/3!...+X^N/N!
print("Enter the range of number:")
n=int(input())
print("Enter the value of x:")
x=int(input())
sum=1.0
i=1
while(i<=n):
fact=1
for j in range(1,i+1):
fact*=j
sum+=pow(x,i)/fact
i+=1
print("The sum of the series = ",sum) | 39 |
# Write a Pandas program to create a time series using three months frequency.
import pandas as pd
time_series = pd.date_range('1/1/2021', periods = 36, freq='3M')
print("Time series using three months frequency:")
print(time_series)
| 32 |
# Write a Python program to find the list with maximum and minimum length using lambda.
def max_length_list(input_list):
max_length = max(len(x) for x in input_list )
max_list = max(input_list, key = lambda i: len(i))
return(max_length, max_list)
def min_length_list(input_list):
min_length = min(len(x) for x in input_list )
min_list = min(input_list, key = lambda i: len(i))
return(min_length, min_list)
list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
print("Original list:")
print(list1)
print("\nList with maximum length of lists:")
print(max_length_list(list1))
print("\nList with minimum length of lists:")
print(min_length_list(list1))
| 85 |
# Write a Python program to check if a string has at least one letter and one number
def checkString(str):
# intializing flag variable
flag_l = False
flag_n = False
# checking for letter and numbers in
# given string
for i in str:
# if string has letter
if i.isalpha():
flag_l = True
# if string has number
if i.isdigit():
flag_n = True
# returning and of flag
# for checking required condition
return flag_l and flag_n
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks')) | 83 |
# Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise, sales man wise.
import numpy as np
import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=["Region","Manager","SalesMan"], values="Sale_amt", aggfunc=np.sum))
| 37 |
# Write a Python program to create a naïve (without time zone) datetime representation of the Arrow object.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
r = arrow.now('US/Mountain')
print("\nNaive datetime representation:")
print(r.naive)
| 33 |
# Python Program to Read a Number n and Compute n+nn+nnn
n=int(input("Enter a number n: "))
temp=str(n)
t1=temp+temp
t2=temp+temp+temp
comp=n+int(t1)+int(t2)
print("The value is:",comp) | 23 |
# Write a Python program to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters.
from itertools import groupby
def modified_encode(alist):
def ctr_ele(el):
if len(el)>1: return [len(el), el[0]]
else: return el[0]
return [ctr_ele(list(group)) for key, group in groupby(alist)]
n_list = [1,1,2,3,4,4,5, 1]
print("Original list:")
print(n_list)
print("\nList reflecting the modified run-length encoding from the said list:")
print(modified_encode(n_list))
n_list = 'aabcddddadnss'
print("\nOriginal String:")
print(n_list)
print("\nList reflecting the modified run-length encoding from the said string:")
print(modified_encode(n_list))
| 84 |
# Write a Python program to get all possible combinations of the elements of a given list using itertools module.
import itertools
def combinations_list(list1):
temp = []
for i in range(0,len(list1)+1):
temp.append(list(itertools.combinations(list1,i)))
return temp
colors = ['orange', 'red', 'green', 'blue']
print("Original list:")
print(colors)
print("\nAll possible combinations of the said list’s elements:")
print(combinations_list(colors))
| 52 |
# Write a NumPy program to find the first Monday in May 2017.
import numpy as np
print("First Monday in May 2017:")
print(np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon'))
| 26 |
# Convert String to Set in Python
# create a string str
string = "geeks"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string) | 56 |
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot where each bar will represent one of the top 10 production.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('E:\coalpublic2013.xlsx')
sorted_by_production = df.sort_values(['Production'], ascending=False).head(10)
sorted_by_production['Production'].head(10).plot(kind="barh")
plt.show()
| 51 |
# Write a Python program to find four elements from a given array of integers whose sum is equal to a given number. The solution set must not contain duplicate quadruplets.
#Source: https://bit.ly/2SSoyhf
from bisect import bisect_left
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
N = 4
quadruplets = []
if len(nums) < N:
return quadruplets
nums = sorted(nums)
quadruplet = []
# Let top[i] be the sum of largest i numbers.
top = [0]
for i in range(1, N):
top.append(top[i - 1] + nums[-i])
# Find range of the least number in curr_n (0,...,N)
# numbers that sum up to curr_target, then find range
# of 2nd least number and so on by recursion.
def sum_(curr_target, curr_n, lo=0):
if curr_n == 0:
if curr_target == 0:
quadruplets.append(quadruplet[:])
return
next_n = curr_n - 1
max_i = len(nums) - curr_n
max_i = bisect_left(
nums, curr_target // curr_n,
lo, max_i)
min_i = bisect_left(
nums, curr_target - top[next_n],
lo, max_i)
for i in range(min_i, max_i + 1):
if i == min_i or nums[i] != nums[i - 1]:
quadruplet.append(nums[i])
next_target = curr_target - nums[i]
sum_(next_target, next_n, i + 1)
quadruplet.pop()
sum_(target, N)
return quadruplets
s = Solution()
nums = [-2, -1, 1, 2, 3, 4, 5, 6]
target = 10
result = s.fourSum(nums, target)
print("\nArray values & target value:",nums,"&",target)
print("Solution Set:\n", result)
| 227 |
# Write a NumPy program to find the nearest value from a given value in an array.
import numpy as np
x = np.random.uniform(1, 12, 5)
v = 4
n = x.flat[np.abs(x - v).argmin()]
print(n)
| 35 |
Subsets and Splits