code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to traverse a given list in reverse order, also print the elements with original index.
color = ["red", "green", "white", "black"]
print("Original list:")
print(color)
print("\nTraverse the said list in reverse order:")
for i in reversed(color):
print(i)
print("\nTraverse the said list i... | 58 |
# Program to Convert Binary to Hexadecimal
print("Enter a binary number:")
binary=input()
if(len(binary)%4==1):
binary="000"+binary
if(len(binary)%4==2):
binary="00"+binary
if(len(binary)%4==3):
binary="0"+binary
hex=""
len=int(len(binary)/4)
print("len:",len)
i=0
j=0
k=4
decimal=0
while(i<len):
... | 68 |
# Write a Python program to insert a given string at the beginning of all items in a list.
num = [1,2,3,4]
print(['emp{0}'.format(i) for i in num])
| 27 |
# Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension.
import numpy as np
a = np.array([1,2,5])
b = np.array([2,1,0])
print("Original 1-d arrays:")
print(a)
print(b)
print
result = np.inner(a, b)
print("Inner product of the said vectors:... | 73 |
# Write a Python program to break a given list of integers into sets of a given positive number. Return true or false.
import collections as clt
def check_break_list(nums, n):
coll_data = clt.Counter(nums)
for x in sorted(coll_data.keys()):
for index in range(1, n):
coll_data[x+index] = c... | 87 |
# Write a NumPy program to convert the raw data in an array to a binary string and then create an array.
import numpy as np
x = np.array([10, 20, 30], float)
print("Original array:")
print(x)
s = x.tostring()
print("Binary string array:")
print(s)
print("Array using fromstring():")
y = np.fromstring(s)
print(y)
| 49 |
# How to add a border around a NumPy array in Python
# importing Numpy package
import numpy as np
# Creating a 2X2 Numpy matrix
array = np.ones((2, 2))
print("Original array")
print(array)
print("\n0 on the border and 1 inside the array")
# constructing border of 0 around 2D identity matrix
# using np.pad... | 61 |
# Write a NumPy program to combine last element with first element of two given ndarray with different shapes.
import numpy as np
array1 = ['PHP','JS','C++']
array2 = ['Python','C#', 'NumPy']
print("Original arrays:")
print(array1)
print(array2)
result = np.r_[array1[:-1], [array1[-1]+array2... | 42 |
# Write a Pandas program to split the following given dataframe into groups based on school code and call a specific group with the name of the group.
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002... | 119 |
# Write a NumPy program to access an array by column.
import numpy as np
x= np.arange(9).reshape(3,3)
print("Original array elements:")
print(x)
print("Access an array by column:")
print("First column:")
print(x[:,0])
print("Second column:")
print(x[:,1])
print("Third column:")
print(x[:,2])
| 35 |
# Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org.
#https://bit.ly/2lVhlLX
# via: https://analytics.usa.gov/
import requests
url = 'https://analytics.usa.gov/data/live/realtime.json'
j = requests.get(url).json()
print("Number of people ... | 47 |
# Python Program to Sort a List According to the Length of the Elements
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=input("Enter element:")
a.append(b)
a.sort(key=len)
print(a) | 28 |
# Write a Python program to read a matrix from console and print the sum for each column. Accept matrix rows, columns and elements for each column separated with a space(for every row) as input from the user.
rows = int(input("Input rows: "))
columns = int(input("Input columns: "))
matrix = [[0]*columns for row in r... | 105 |
# Write a Python program to create a new list dividing two given lists of numbers.
def dividing_two_lists(l1,l2):
result = [x/y for x, y in zip(l1,l2)]
return result
nums1 = [7,2,3,4,9,2,3]
nums2 = [9,8,2,3,3,1,2]
print("Original list:")
print(nums1)
print(nums1)
print(dividing_two_lists(nums1, nums2))
| 40 |
# Write a Python program to find a first even and odd number in a given list of numbers.
def first_even_odd(nums):
first_even = next((el for el in nums if el%2==0),-1)
first_odd = next((el for el in nums if el%2!=0),-1)
return first_even,first_odd
nums= [1,3,5,7,4,1,6,8]
print("Original list:")
print(nu... | 58 |
# Write a Python program to find the maximum and minimum values in a given list of tuples.
from operator import itemgetter
def max_min_list_tuples(class_students):
return_max = max(class_students,key=itemgetter(1))[1]
return_min = min(class_students,key=itemgetter(1))[1]
return return_max, return_min
... | 63 |
# Write a Python program to delete the last 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... | 168 |
# Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string.
def count_chars(str):
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1
elif str[i] >= 'a... | 101 |
# Write a Pandas program to create a Pivot table and separate the gender according to whether they traveled alone or not to get the probability of survival.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table( 'survived' , [ 'sex' , 'alone' ] , 'class' )
print(result)
| 53 |
# Write a Python program to shuffle the elements of a given list. Use random.shuffle()
import random
nums = [1, 2, 3, 4, 5]
print("Original list:")
print(nums)
random.shuffle(nums)
print("Shuffle list:")
print(nums)
words = ['red', 'black', 'green', 'blue']
print("\nOriginal list:")
print(words)
random.shuffle(words... | 44 |
# Write a Pandas program to compute the autocorrelations of a given numeric series.
import pandas as pd
import numpy as np
num_series = pd.Series(np.arange(15) + np.random.normal(1, 10, 15))
print("Original series:")
print(num_series)
autocorrelations = [num_series.autocorr(i).round(2) for i in range(11)]
print("\nA... | 45 |
# Write a NumPy program to get the powers of an array values element-wise.
import numpy as np
x = np.arange(7)
print("Original array")
print(x)
print("First array elements raised to powers from second array, element-wise:")
print(np.power(x, 3))
| 36 |
# Write a Python dictionary with keys having multiple inputs
# Python code to demonstrate a dictionary
# with multiple inputs in a key.
import random as rn
# creating an empty dictionary
dict = {}
# Insert first triplet in dictionary
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z;
# Insert second triplet in dic... | 85 |
# Write a Python program to find the most common element of a given list.
from collections import Counter
language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python','PHP', 'Python']
print("Original list:")
print(language)
cnt = Counter(language)
print("\nMost common element of the said list:")
pri... | 44 |
# Program to find the normal and trace of a matrix
import math
# 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.appe... | 107 |
# Python Program to Create a Class and Compute the Area and the Perimeter of the Circle
import math
class circle():
def __init__(self,radius):
self.radius=radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius
r=int(input("Enter r... | 44 |
# Write a Python program to find maximum length of consecutive 0's in a given binary string.
def max_consecutive_0(input_str):
return max(map(len,input_str.split('1')))
str1 = '111000010000110'
print("Original string:" + str1)
print("Maximum length of consecutive 0’s:")
print(max_consecutive_0(str1))
str1 = '... | 47 |
# Write a Pandas program to create a Pivot table and find the maximum sale value of the items.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=np.max)
print(table)
| 37 |
# Write a Pandas program to compute the Euclidean distance between two given series.
import pandas as pd
import numpy as np
x = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = pd.Series([11, 8, 7, 5, 6, 5, 3, 4, 7, 1])
print("Original series:")
print(x)
print(y)
print("\nEuclidean distance between two said series:")
... | 57 |
# Write a NumPy program to remove the trailing whitespaces of all the elements of a given array.
import numpy as np
x = np.array([' python exercises ', ' PHP ', ' java ', ' C++'], dtype=np.str)
print("Original Array:")
print(x)
rstripped_char = np.char.rstrip(x)
print("\nRemove the trailing whitespaces : ", rstri... | 50 |
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot comparing year, MSHA ID, Production and Labor_hours of first ten records.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.head(10).plot(kind... | 48 |
# Write a Python program to find the k
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def kth_smallest(root, k):
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
... | 86 |
# Write a Pandas program to add some data to an existing Series.
import pandas as pd
s = pd.Series(['100', '200', 'python', '300.12', '400'])
print("Original Data Series:")
print(s)
print("\nData Series after adding some data:")
new_s = s.append(pd.Series(['500', 'php']))
print(new_s)
| 39 |
# Write a Python program to round the numbers of a given list, print the minimum and maximum numbers and multiply the numbers by 5. Print the unique numbers in ascending order separated by space.
nums = [22.4, 4.0, 16.22, 9.10, 11.00, 12.22, 14.20, 5.20, 17.50]
print("Original list:", nums)
numbers=list(map(round,nu... | 66 |
# Write a Python program to remove a key from a dictionary.
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
| 23 |
# Automate Youtube with Python
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import speech_recognition as sr
import pyttsx3
im... | 170 |
# Write a Python program to iterate over two lists simultaneously.
num = [1, 2, 3]
color = ['red', 'white', 'black']
for (a,b) in zip(num, color):
print(a, b)
| 28 |
# Write a Python program to Queue using Doubly Linked List
# A complete working Python program to demonstrate all
# Queue operations using doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.n... | 350 |
# Write a NumPy program to create a new array which is the average of every consecutive triplet of elements of a given array.
import numpy as np
arr1 = np.array([1,2,3, 2,4,6, 1,2,12, 0,-12,6])
print("Original array:")
print(arr1)
result = np.mean(arr1.reshape(-1, 3), axis=1)
print("Average of every consecutive trip... | 54 |
# Creating a Pandas Series from Lists in Python
# import pandas as pd
import pandas as pd
# create Pandas Series with default index values
# default index ranges is from 0 to len(list) - 1
x = pd.Series(['Geeks', 'for', 'Geeks'])
# print the Series
print(x) | 47 |
# numpy.poly1d() in Python
# Python code explaining
# numpy.poly1d()
# importing libraries
import numpy as np
# Constructing polynomial
p1 = np.poly1d([1, 2])
p2 = np.poly1d([4, 9, 5, 4])
print ("P1 : ", p1)
print ("\n p2 : \n", p2)
# Solve for x = 2
print ("\n\np1 at x = 2 : ", p1(2))
print ("p2 at x = 2... | 120 |
# Write a Python program to get the maximum and minimum value in a dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_mi... | 39 |
# Python Program to Sum All the Items in a Dictionary
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values())) | 20 |
# Write a NumPy program to find elements within range from a given array of numbers.
import numpy as np
a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29])
print("Original array:")
print(a)
result = np.where(np.logical_and(a>=7, a<=20))
print("\nElements within range: index position")
print(result)
| 44 |
# Write a Pandas program to create a plot of distribution of UFO (unidentified flying object) observation time.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'ufo.csv')
df['duration_sec'] = (df['length_of_encounter_seconds'].astype(float))/60
s = df["duration_sec"].quant... | 65 |
# Write a Python Program to print digit pattern
# function to print the pattern
def pattern(n):
# traverse through the elements
# in n assuming it as a string
for i in n:
# print | for every line
print("|", end = "")
# print i number of * s in
# each line
... | 68 |
# Write a Python program to extract h1 tag from example.com.
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://en.wikipedia.org/wiki/Main_Page')
bs = BeautifulSoup(html, "html.parser")
titles = bs.find_all(['h1', 'h2','h3','h4','h5','h6'])
print('List all the header tags :... | 38 |
# Write a Pandas program to convert given series into a dataframe with its index as another column on the dataframe.
import numpy as np
import pandas as pd
char_list = list('ABCDEFGHIJKLMNOP')
num_arra = np.arange(8)
num_dict = dict(zip(char_list, num_arra))
num_ser = pd.Series(num_dict)
df = num_ser.to_frame().rese... | 46 |
# Sum a list of numbers. Write a Python program to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.
#Source: shorturl.at/csxLM
def test(list1):
result = [(x + y) / 2.0 for (x, y) in zip(list1[:-1], list1[1:])]
return list(result)
nums ... | 82 |
# rite a NumPy program to create a null vector of size 10 and update sixth value to 11.
import numpy as np
x = np.zeros(10)
print(x)
print("Update sixth value to 11")
x[6] = 11
print(x)
| 36 |
# Write a Python program to create a two-dimensional list from given list of lists.
def two_dimensional_list(nums):
return list(zip(*nums))
print(two_dimensional_list([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]))
print(two_dimensional_list([[1, 2], [4, 5]]))
| 35 |
# Write a Python function that takes a list and returns a new list with unique elements of the first list.
def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,3,3,3,3,4,5]))
| 39 |
# Write a Python program to sort Counter by value.
from collections import Counter
x = Counter({'Math':81, 'Physics':83, 'Chemistry':87})
print(x.most_common())
| 20 |
# Write a Python program to count the number occurrence of a specific character in a string.
s = "The quick brown fox jumps over the lazy dog."
print("Original string:")
print(s)
print("Number of occurrence of 'o' in the said string:")
print(s.count("o"))
| 41 |
# Clean the string data in the given Pandas Dataframe 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'],
'U... | 51 |
# Write a Python Program for Odd-Even Sort / Brick Sort
# Python Program to implement
# Odd-Even / Brick Sort
def oddEvenSort(arr, n):
# Initially array is unsorted
isSorted = 0
while isSorted == 0:
isSorted = 1
temp = 0
for i in range(1, n-1, 2):
if arr[i] > arr[i+... | 106 |
# Write a Python program to All substrings Frequency in String
# Python3 code to demonstrate working of
# All substrings Frequency in String
# Using loop + list comprehension
# initializing string
test_str = "abababa"
# printing original string
print("The original string is : " + str(test_str))
# list compr... | 108 |
# Count the number of vowels, consonants, numbers, and special characters present in a string
str=input("Enter the String:")
v_count = 0
s_count = 0
n_count = 0
for i in range(len(str)):
if str[i] == 'a' or str[i] == 'A' or str[i] == 'e' or str[i] == 'E' or str[i] == 'i' or str[i] == 'I' or str[i] == 'o' or str[... | 135 |
# Write a Python program to calculate the product of the unique numbers of a given list.
def unique_product(list_data):
temp = list(set(list_data))
p = 1
for i in temp:
p *= i
return p
nums = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",nums)
print("Product of the unique numbers ... | 58 |
# Write a Python program to compute the sum of digits of each number of a given list.
def sum_of_digits(nums):
return sum(int(el) for n in nums for el in str(n) if el.isdigit())
nums = [10,2,56]
print("Original tuple: ")
print(nums)
print("Sum of digits of each number of the said list of integers:")
print(sum_... | 92 |
# Write a Python program to display some information about the OS where the script is running.
import platform as pl
os_profile = [
'architecture',
'linux_distribution',
'mac_ver',
'machine',
'node',
'platform',
'processor',
'python_build',
'py... | 53 |
# Write a Python program to get the minimum value of a list, after mapping each element to a value using a given function.
def min_by(lst, fn):
return min(map(fn, lst))
print(min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
| 50 |
# Write a NumPy program to find the indices of the maximum and minimum values along the given axis of an array.
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
print("Original array: ",x)
print("Maximum Values: ",np.argmax(x))
print("Minimum Values: ",np.argmin(x))
| 43 |
# Write a Python program to check if first digit/character of each element in a given list is same or not.
def test(lst):
result = all(str(x)[0] == str(lst[0])[0] for x in lst)
return result
nums = [1234, 122, 1984, 19372, 100]
print("\nOriginal list:")
print(nums)
print("Check if first digit in each elemen... | 140 |
# Write a Python program to sort unsorted numbers using Random Pivot Quick Sort. Picks the random index as the pivot.
#Ref.https://bit.ly/3pl5kyn
import random
def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j... | 280 |
# Write a Python program to that retrieves an arbitary Wikipedia page of "Python" and creates a list of links on that page.
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
... | 81 |
# How to read multiple text files from folder in Python
# Import Module
import os
# Folder Path
path = "Enter Folder Path"
# Change the directory
os.chdir(path)
# Read text File
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
# iterate through all file
f... | 72 |
# Write a NumPy program to stack arrays in sequence vertically.
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.vstack((x,y))
print("\nStack arrays in sequence vertically:")
print(new_array)
| 36 |
# Write a Python program to check if all the elements of a list are included in another given list.
def test_includes_all(nums, lsts):
for x in lsts:
if x not in nums:
return False
return True
print(test_includes_all([10, 20, 30, 40, 50, 60], [20, 40]))
print(test_includes_all([10, 20, 30, 40, 50, 60],... | 52 |
# Count of groups having largest size while grouping according to sum of its digits in Python
// C++ implementation to Count the
// number of groups having the largest
// size where groups are according
// to the sum of its digits
#include <bits/stdc++.h>
using namespace std;
// function to return sum of digits of ... | 221 |
# Building an undirected graph and finding shortest path using Dictionaries in Python
# Python3 implementation to build a
# graph using Dictonaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
["A", "B"], ["A", "E"],
["A", "C"], ["B", "D"],
... | 98 |
# Write a Python program to check if a function is a user-defined function or not. Use types.FunctionType, types.LambdaType()
import types
def func():
return 1
print(isinstance(func, types.FunctionType))
print(isinstance(func, types.LambdaType))
print(isinstance(lambda x: x, types.FunctionType))
print(isinstanc... | 45 |
# Write a Python program to Dictionary with maximum count of pairs
# Python3 code to demonstrate working of
# Dictionary with maximum keys
# Using loop + len()
# initializing list
test_list = [{"gfg": 2, "best" : 4},
{"gfg": 2, "is" : 3, "best" : 4},
{"gfg": 2}]
# printing original ... | 95 |
# Python Program to Print Numbers in a Range (1,upper) Without Using any Loops
def printno(upper):
if(upper>0):
printno(upper-1)
print(upper)
upper=int(input("Enter upper limit: "))
printno(upper) | 24 |
# Check whether two strings are equal or not
str=input("Enter the 1st String:")
str1=input("Enter the 2nd String:")
if(len(str)==len(str1)):
print("Two strings are equal.")
else:
print("Two strings are not equal.") | 28 |
# Write a Python program to print the following floating numbers upto 2 decimal places with a sign.
x = 3.1415926
y = -12.9999
print("\nOriginal Number: ", x)
print("Formatted Number with sign: "+"{:+.2f}".format(x));
print("Original Number: ", y)
print("Formatted Number with sign: "+"{:+.2f}".format(y));
print()
| 43 |
# numpy matrix operations | rand() function in Python
# Python program explaining
# numpy.matlib.rand() function
# importing matrix library from numpy
import numpy as geek
import numpy.matlib
# desired 3 x 4 random output matrix
out_mat = geek.matlib.rand((3, 4))
print ("Output matrix : ", out_mat) | 46 |
# Write a Python program to extract values from a given dictionaries and create a list of lists from those values.
def test(dictt,keys):
return [list(d[k] for k in keys) for d in dictt]
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell'... | 97 |
# Write a NumPy program to create a two-dimensional array of specified format.
import numpy as np
print("Create an array of shape (15,10):")
print("Command-1")
print(np.arange(1, 151).reshape(15, 10))
print("\nCommand-2")
print(np.arange(1, 151).reshape(-1, 10))
print("\nCommand-3")
print(np.arange(1, 151).res... | 35 |
# Write a Pandas program to convert integer or float epoch times to Timestamp and DatetimeIndex.
import pandas as pd
dates1 = pd.to_datetime([1329806505, 129806505, 1249892905,
1249979305, 1250065705], unit='s')
print("Convert integer or float epoch times to Timestamp and DatetimeIndex upto second:")... | 62 |
# Write a NumPy program to change the sign of a given array to that of a given array, element-wise.
import numpy as np
x1 = np.array([-1, 0, 1, 2])
print("Original array: ")
print(x1)
x2 = -2.1
print("\nSign of x1 to that of x2, element-wise:")
print(np.copysign(x1, x2))
| 47 |
# Write a NumPy program to check whether two arrays are equal (element wise) or not.
import numpy as np
nums1 = np.array([0.5, 1.5, 0.2])
nums2 = np.array([0.4999999999, 1.500000000, 0.2])
np.set_printoptions(precision=15)
print("Original arrays:")
print(nums1)
print(nums2)
print("\nTest said two arrays are equal (e... | 75 |
# Write a Python program to find the specified number of largest products from two given list, multiplying an element from each list.
def top_product(nums1, nums2, N):
result = sorted([x*y for x in nums1 for y in nums2], reverse=True)[:N]
return result
nums1 = [1, 2, 3, 4, 5, 6]
nums2 = [3, 6, 8, 9, 10, 6]
p... | 91 |
# Write a NumPy program (using NumPy) to sum of all the multiples of 3 or 5 below 100.
import numpy as np
x = np.arange(1, 100)
# find multiple of 3 or 5
n= x[(x % 3 == 0) | (x % 5 == 0)]
print(n[:1000])
# print sum the numbers
print(n.sum())
| 53 |
# Write a Python program to computing square roots using the Babylonian method.
def BabylonianAlgorithm(number):
if(number == 0):
return 0;
g = number/2.0;
g2 = g + 1;
while(g != g2):
n = number/ g;
g2 = g;
g = (g + n)/2;
return g;
print('The Square root of 0.3 =... | 52 |
# Handling missing keys in Python dictionaries
# Python code to demonstrate Dictionary and
# missing value error
# initializing Dictionary
d = { 'a' : 1 , 'b' : 2 }
# trying to output value of absent key
print ("The value associated with 'c' is : ")
print (d['c']) | 51 |
# Write a Python program to check if a given function is a generator or not. Use types.GeneratorType()
import types
def a(x):
yield x
def b(x):
return x
def add(x, y):
return x + y
print(isinstance(a(456), types.GeneratorType))
print(isinstance(b(823), types.GeneratorType))
print(isinstance(add... | 41 |
# Write a Python program to remove the first occurrence of a specified element from an array.
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
print("Original array: "+str(array_num))
print("Remove the first occurrence of 3 from the said array:")
array_num.remove(3)
print("New array: "+str(array_... | 49 |
# How to count the frequency of unique values in NumPy array in Python
# import library
import numpy as np
ini_array = np.array([10, 20, 5,
10, 8, 20,
8, 9])
# Get a tuple of unique values
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array... | 68 |
# Write a Pandas program to check whether alphabetic values present in a given column of a DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['Company','Company a001','Company 123', 'abcd', 'Company 12'],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
... | 58 |
# Write a Python program to change the position of every n-th value with the (n+1)th in a list.
from itertools import zip_longest, chain, tee
def replace2copy(lst):
lst1, lst2 = tee(iter(lst), 2)
return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))
n = [0,1,2,3,4,5]
print(replace2copy(n))
| 39 |
# Write a Python program to Numpy dstack() method
# import numpy
import numpy as np
gfg1 = np.array([1, 2, 3])
gfg2 = np.array([4, 5, 6])
# using numpy.dstack() method
print(np.dstack((gfg1, gfg2))) | 32 |
# Check whether an alphabet is vowel or consonant
alphabet=input("Enter an alphabet:")
if(alphabet=='a' or alphabet=='A' or alphabet=='e' or alphabet=='E' or alphabet=='i' or alphabet=='I' or alphabet=='o' or alphabet=='O' or alphabet=='u' or alphabet=='U'):
print("It is Vowel")
else:
print("It is Consonant") | 38 |
# Check whether number is Sunny Number or Not.
import math
num=int(input("Enter a number:"))
root=math.sqrt(num+1)
if int(root)==root:
print("It is a Sunny Number.")
else:
print("It is Not a Sunny Number.") | 29 |
# Getting the time since OS startup using Python
# for using os.popen()
import os
# sending the uptime command as an argument to popen()
# and saving the returned result (after truncating the trailing \n)
t = os.popen('uptime -p').read()[:-1]
print(t) | 41 |
# Write a Python program to create a ctime formatted representation of the date and time using arrow module.
import arrow
print("Ctime formatted representation of the date and time:")
a = arrow.utcnow().ctime()
print(a)
| 33 |
# Write a Python program to convert an integer to binary keep leading zeros.
x = 12
print(format(x, '08b'))
print(format(x, '010b'))
| 21 |
# Program to Find nth Neon Number
rangenumber=int(input("Enter a Nth Number:"))
c = 0
letest = 0
num = 1
while c != rangenumber:
sqr = num * num
# Sum of digit
sum = 0
while sqr != 0:
rem = sqr % 10
sum += rem
sqr //= 10
if sum == num:
... | 69 |
# Write a Python program to chunk a given list into smaller lists of a specified size.
from math import ceil
def chunk_list(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(ceil(len(lst) / size)))))
print(chunk_list([1, 2, 3, 4, 5, 6, 7, 8], 3))
| 47 |
# Write a Python program to convert a pair of values into a sorted unique array.
L = [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1, 2), (3, 4), (3, 4),
(7, 8), (9, 10)]
print("Original List: ", L)
print("Sorted Unique Data:",sorted(set().union(*L)))
| 45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.