code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to create a new Arrow object, representing the "floor" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute.
import arrow
print(arrow.utcnow())
print("Hour ceiling:")
print(arrow.utcnow().floor('hour'))... | 51 |
# How to lowercase column names in Pandas dataframe in Python
# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'],
'B': ['masters', 'graduate', 'graduate',
... | 50 |
# How to get values of an NumPy array at certain index positions in Python
# Importing Numpy module
import numpy as np
# Creating 1-D Numpy array
a1 = np.array([11, 10, 22, 30, 33])
print("Array 1 :")
print(a1)
a2 = np.array([1, 15, 60])
print("Array 2 :")
print(a2)
print("\nTake 1 and 15 from Array 2 and pu... | 73 |
# Write a Python program to find a triplet in an array such that the sum is closest to a given number. Return the sum of the three integers.
#Source: https://bit.ly/2SRefdb
from bisect import bisect, bisect_left
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
... | 267 |
# Write a Python program to get the number of occurrences of a specified element in an array.
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 9, 3])
print("Original array: "+str(array_num))
print("Number of occurrences of the number 3 in the said array: "+str(array_num.count(3)))
| 47 |
# Write a Python program to returns sum of all divisors of a number.
def sum_div(number):
divisors = [1]
for i in range(2, number):
if (number % i)==0:
divisors.append(i)
return sum(divisors)
print(sum_div(8))
print(sum_div(12))
| 33 |
# Write a Pandas program to find out the alcohol consumption details in the year '1986' where WHO region is 'Western Pacific' and country is 'VietNam' from the world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consu... | 78 |
# Program to Find the smallest of three numbers
print("Enter 3 numbers:")
num1=int(input())
num2=int(input())
num3=int(input())
print("The smallest number is ",min(num1,num2,num3))
| 20 |
# Write a Python program to retrieve the HTML code of the title, its text, and the HTML code of its parent.
import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print("title")
print(soup.title)
print("title text")
print(soup.ti... | 49 |
# Write a Python program to print all unique values in a dictionary.
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
print("Original List: ",L)
u_value = set( val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
| 42 |
# Write a Python program to map the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.
def map_dictionary(itr, fn):
return dict(zip(itr, map(fn, itr)))
print(map_dictionary([1, 2, 3], lambda x: x * x))
| 54 |
# Write a Python program to create a key-value list pairings in a given dictionary.
from itertools import product
def test(dictt):
result = [dict(zip(dictt, sub)) for sub in product(*dictt.values())]
return result
students = {1: ['Jean Castro'], 2: ['Lula Powell'], 3: ['Brian Howell'], 4: ['Lynne Foster'], ... | 60 |
# Retweet Tweet using Selenium in Python
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedExcep... | 43 |
# How to create filename containing date or time in Python
# import module
from datetime import datetime
# get current date and time
current_datetime = datetime.now()
print("Current date & time : ", current_datetime)
# convert datetime obj to string
str_current_datetime = str(current_datetime)
# create a fil... | 64 |
# Write a NumPy program to calculate the Frobenius norm and the condition number of a given array.
import numpy as np
a = np.arange(1, 10).reshape((3, 3))
print("Original array:")
print(a)
print("Frobenius norm and the condition number:")
print(np.linalg.norm(a, 'fro'))
print(np.linalg.cond(a, 'fro'))
| 40 |
# Write a Python program to read a given CSV files with initial spaces after a delimiter and remove those initial spaces.
import csv
print("\nWith initial spaces after a delimiter:\n")
with open('departments.csv', 'r') as csvfile:
data = csv.reader(csvfile, skipinitialspace=False)
for row in data:
print('... | 66 |
# Write a Python program using Sieve of Eratosthenes method for computing primes upto a specified number.
def prime_eratosthenes(n):
prime_list = []
for i in range(2, n+1):
if i not in prime_list:
print (i)
for j in range(i*i, n+1, i):
prime_list.append(j)
pri... | 42 |
# Write a Python program to Remove duplicate values across Dictionary Values
# Python3 code to demonstrate working of
# Remove duplicate values across Dictionary Values
# Using Counter() + list comprehension
from collections import Counter
# initializing dictionary
test_dict = {'Manjeet' : [1, 4, 5, 6],
... | 119 |
#
Please generate a random float where the value is between 10 and 100 using Python math module.
:
import random
print random.random()*100
| 23 |
# Write a Python program to find the maximum and minimum value of the three given lists.
nums1 = [2,3,5,8,7,2,3]
nums2 = [4,3,9,0,4,3,9]
nums3 = [2,1,5,6,5,5,4]
print("Original lists:")
print(nums1)
print(nums2)
print(nums3)
print("Maximum value of the said three lists:")
print(max(nums1+nums2+nums3))
print("Minimum... | 47 |
# Write a Pandas program to check if a specified column starts with a specified string in a 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... | 60 |
# How to create filename containing date or time in Python
# import module
from datetime import datetime
# get current date and time
current_datetime = datetime.now()
print("Current date & time : ", current_datetime)
# convert datetime obj to string
str_current_datetime = str(current_datetime)
# create a fil... | 64 |
# Write a Python program to replace the last element in a list with another list.
num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
| 34 |
# Write a Python program to swap comma and dot in a string.
amount = "32.054,23"
maketrans = amount.maketrans
amount = amount.translate(maketrans(',.', '.,'))
print(amount)
| 24 |
# Write a Python program to Least Frequent Character in String
# Python 3 code to demonstrate
# Least Frequent Character in String
# naive method
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print ("The original string is : " + test_str)
# using naive method to get
# Least F... | 97 |
# Write a Python program to check if a given function returns True for every element in a list.
def every(lst, fn = lambda x: x):
return all(map(fn, lst))
print(every([4, 2, 3], lambda x: x > 1))
print(every([4, 2, 3], lambda x: x < 1))
print(every([4, 2, 3], lambda x: x == 1))
| 53 |
# Numpy count_nonzero method | Python
# Python program explaining
# numpy.count_nonzero() function
# importing numpy as geek
import numpy as geek
arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]]
gfg = geek.count_nonzero(arr)
print (gfg) | 39 |
# Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
D 100
W 200
D means deposit while W means withdrawal.
netAmount = 0
while True:
s = raw_input()
if not s:
break
values = s.split(" ")
... | 71 |
# Write a NumPy program to multiply two given arrays of same size element-by-element.
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("\nMultiply said arrays of same s... | 47 |
# Write a Python program to create a flat list of all the keys in a flat dictionary.
def test(flat_dict):
return list(flat_dict.keys())
students = {
'Theodore': 19,
'Roxanne': 20,
'Mathew': 21,
'Betty': 20
}
print("\nOriginal dictionary elements:")
print(students)
print("\nCreate a flat list of all the ke... | 52 |
# Write a Python program to combine values in python list of dictionaries.
from collections import Counter
item_list = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
result = Counter()
for d in item_list:
result[d['item']] += d['amount']
print(result)
| 42 |
# Write a Python program to Check for URL in a String
# Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2... | 73 |
# Write a NumPy program to create two arrays of size bigger and smaller than a given array.
import numpy as np
x = np.arange(16).reshape(4,4)
print("Original arrays:")
print(x)
print("\nArray with size 2x2 from the said array:")
new_array1 = np.resize(x,(2,2))
print(new_array1)
print("\nArray with size 6x6 from ... | 52 |
# Program to print multiplication table of a given number
nan | 11 |
# Python Program to Print Odd Numbers Within a Given Range
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i) | 31 |
# Write a Pandas program to create a Pivot table and find survival rate by gender, age wise of various classes.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index=['sex','age'], columns='class')
print(result)
| 38 |
# Write a Python Program to Print Lines Containing Given String in File
# Python Program to Print Lines
# Containing Given String in File
# input file name with extension
file_name = input("Enter The File's Name: ")
# using try catch except to
# handle file not found error.
# entering try block
try:
#... | 223 |
# Create a dataframe of ten rows, four columns with random values. Convert some values to nan values. Write a Pandas program which will highlight the nan values.
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn... | 93 |
# Write a Python program to count characters at same position in a given string (lower and uppercase characters) as in English alphabet.
def count_char_position(str1):
count_chars = 0
for i in range(len(str1)):
if ((i == ord(str1[i]) - ord('A')) or
(i == ord(str1[i]) - ord('a'))):
... | 70 |
# Write a Python program to create a multidimensional list (lists of lists) with zeros.
nums = []
for i in range(3):
nums.append([])
for j in range(2):
nums[i].append(0)
print("Multidimensional list:")
print(nums)
| 31 |
# Write a Pandas program to append a list of dictioneries or series to a existing DataFrame and display the combined data.
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwam... | 90 |
# Write a Python program to get the unique values in a given list of lists.
def unique_values_in_list_of_lists(lst):
result = set(x for l in lst for x in l)
return list(result)
nums = [[1,2,3,5], [2,3,5,4], [0,5,4,1], [3,7,2,1], [1,2,1,2]]
print("Original list:")
print(nums)
print("Unique values of the said ... | 69 |
# How to add a border color to a button in Tkinter in Python
import tkinter as tk
root = tk.Tk()
root.geometry('250x150')
root.title("Button Border")
# Label
l = tk.Label(root, text = "Enter your Roll No. :",
font = (("Times New Roman"), 15))
l.pack()
# Entry Widget
tk.Entry(root).pack()
# fo... | 93 |
# Program to print series 6,11,21,36,56...n
n=int(input("Enter the range of number(Limit):"))i=1pr=6diff=5while i<=n: print(pr,end=" ") pr = pr + diff diff = diff + 5 i+=1 | 25 |
# Write a Python program to sort a given collection of numbers and its length in ascending order using Recursive Insertion Sort.
#Ref.https://bit.ly/3iJWk3w
from __future__ import annotations
def rec_insertion_sort(collection: list, n: int):
# Checks if the entire collection has been sorted
if len(collectio... | 180 |
# Write a Python program to Words Frequency in String Shorthands
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
# printing original string
pri... | 92 |
# Write a NumPy program to find the index of the sliced elements as follows from a given 4x4 array.
import numpy as np
x = np.reshape(np.arange(16),(4,4))
print("Original arrays:")
print(x)
print("Sliced elements:")
result = x[[0,1,2],[0,1,3]]
print(result)
| 36 |
# Python Program to Implement Floyd-Warshall Algorithm
class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
"""Add a vertex with the given key to the graph."""
vertex = Vertex(k... | 559 |
# Write a Python program to check whether the n-th element exists in a given list.
x = [1, 2, 3, 4, 5, 6]
xlen = len(x)-1
print(x[xlen])
| 28 |
# Shuffle a deck of card with OOPS in Python
# Import required modules
from random import shuffle
# Define a class to create
# all type of cards
class Cards:
global suites, values
suites = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q'... | 241 |
# Write a NumPy program to get the lower-triangular L in the Cholesky decomposition of a given array.
import numpy as np
a = np.array([[4, 12, -16], [12, 37, -53], [-16, -53, 98]], dtype=np.int32)
print("Original array:")
print(a)
L = np.linalg.cholesky(a)
print("Lower-trianglular L in the Cholesky decomposition of ... | 51 |
# Write a Python program to display your details like name, age, address in three different lines.
def personal_details():
name, age = "Simon", 19
address = "Bangalore, Karnataka, India"
print("Name: {}\nAge: {}\nAddress: {}".format(name, age, address))
personal_details()
| 36 |
#
Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
:
import random
print random.choice([i for i in range(11) if i%2==0])
| 33 |
# How to Print Multiple Arguments in Python
def GFG(name, num):
print("Hello from ", name + ', ' + num)
GFG("geeks for geeks", "25") | 24 |
# Program to check whether a matrix is symmetric 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(... | 136 |
# Write a NumPy program to create a random vector of size 10 and sort it.
import numpy as np
x = np.random.random(10)
print("Original array:")
print(x)
x.sort()
print("Sorted array:")
print(x)
| 30 |
# Write a Python program to remove None value from a given list using lambda function.
def remove_none(nums):
result = filter(lambda v: v is not None, nums)
return list(result)
nums = [12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]
print("Original list:")
print(nums)
print("\nRemove None value from t... | 54 |
# Write a Python program to create a string representation of the Arrow object, formatted according to a format string.
import arrow
print("Current datetime:")
print(arrow.utcnow())
print("\nYYYY-MM-DD HH:mm:ss ZZ:")
print(arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ'))
print("\nDD-MM-YYYY HH:mm:ss ZZ:")
print(arro... | 41 |
# Selection Sort Program in Python | Java | C | C++
size=int(input("Enter the size of the array:"));
arr=[]
print("Enter the element of the array:");
for i in range(0,size):
num = int(input())
arr.append(num)
print("Before Sorting Array Elements are: ",arr)
for out in range(0,size-1):
min = out
for ... | 67 |
# Python Program to Illustrate the Operations of Singly Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
current = self.head
for i in range(index... | 286 |
# Remove multiple elements from a list in Python
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# Iterate each element in list
# and add them in variable total
for ele in list1:
if ele % 2 == 0:
list1.remove(ele)
# printing modified list
... | 69 |
# Create a Pandas Series from array in Python
# importing Pandas & numpy
import pandas as pd
import numpy as np
# numpy array
data = np.array(['a', 'b', 'c', 'd', 'e'])
# creating series
s = pd.Series(data)
print(s) | 39 |
# Write a Python program to convert a given dictionary into a list of lists.
def test(dictt):
result = list(map(list, dictt.items()))
return result
color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Convert the said dicti... | 84 |
# Write a Python program that accept some words and count the number of distinct words. Print the number of distinct words and number of occurrences for each distinct word according to their appearance.
from collections import Counter, OrderedDict
class OrderedCounter(Counter,OrderedDict):
pass
word_array = []
n ... | 71 |
# Write a Python program to get the number of people visiting a U.S. government website right now.
#https://bit.ly/2lVhlLX
import requests
from lxml import html
url = 'https://www.us-cert.gov/ncas/alerts'
doc = html.fromstring(requests.get(url).text)
print("The number of security alerts issued by US-CERT in th... | 45 |
# Write a Python program to find the first tag with a given attribute value in an html document.
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</... | 165 |
# Write a Python program to read specific columns of a given CSV file and print the content of the columns.
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
print("ID Department Name")
print("---------------------------------")
for row in data:
print(row['departme... | 41 |
# Write a Python program to sort unsorted numbers using Timsort.
#Ref:https://bit.ly/3qNYxh9
def binary_search(lst, item, start, end):
if start == end:
return start if lst[start] > item else start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
r... | 251 |
# How to create a list of object in Python class
# Python3 code here creating class
class geeks:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# creating list
list = []
# appending instances to list
list.append( geeks('Akash', 2) )
list.append( geeks('Deepend... | 77 |
# Write a NumPy program to create a 11x3 array filled with student information (id, class and name) and shuffle the said array rows starting from 3
import numpy as np
np.random.seed(42)
student = np.array([['stident_id', 'Class', 'Name'],
['01', 'V', 'Debby Pramod'],
['02', 'V', 'Artemiy ... | 92 |
# Construct a DataFrame in Pandas using string data in Python
# importing pandas as pd
import pandas as pd
# import the StrinIO function
# from io module
from io import StringIO
# wrap the string data in StringIO function
StringData = StringIO("""Date;Event;Cost
10/2/2011;Music;10000
11/2/2011;Poetry;12... | 70 |
# Write a Pandas program to replace more than one value with other values in a given DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['A','B', 'C', 'D', 'A'],
'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, 25... | 53 |
# Write a Python program to rearrange positive and negative numbers in a given array using Lambda.
array_nums = [-1, 2, -3, 5, 7, 8, 9, -10]
print("Original arrays:")
print(array_nums)
result = sorted(array_nums, key = lambda i: 0 if i == 0 else -1 / i)
print("\nRearrange positive and negative numbers of the said ar... | 56 |
# Write a Python program to determine the largest and smallest integers, longs, floats.
import sys
print("Float value information: ",sys.float_info)
print("\nInteger value information: ",sys.int_info)
print("\nMaximum size of an integer: ",sys.maxsize)
| 30 |
# Write a Python program to find whether a given array of integers contains any duplicate element. Return true if any value appears at least twice in the said array and return false if every element is distinct.
def test_duplicate(array_nums):
nums_set = set(array_nums)
return len(array_nums) != len(nums... | 51 |
# Write a Python program to check if the elements of a given list are unique or not.
def all_unique(test_list):
if len(test_list) > len(set(test_list)):
return False
return True
nums1 = [1,2,4,6,8,2,1,4,10,12,14,12,16,17]
print ("Original list:")
print(nums1)
print("\nIs the said list contains all u... | 60 |
# Write a Python program to convert a given string to snake case.
from re import sub
def snake_case(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: ' ' + mo.group(0).lower(), s)).split())
print(snake_case('JavaScript'))
p... | 42 |
# Write a NumPy program to check whether a Numpy array contains a specified row.
import numpy as np
num = np.arange(20)
arr1 = np.reshape(num, [4, 5])
print("Original array:")
print(arr1)
print([0, 1, 2, 3, 4] in arr1.tolist())
print([0, 1, 2, 3, 5] in arr1.tolist())
print([15, 16, 17, 18, 19] in arr1.tolist())
| 51 |
# Write a NumPy program to remove specific elements in a NumPy array.
import numpy as np
x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
index = [0, 3, 4]
print("Original array:")
print(x)
print("Delete first, fourth and fifth elements:")
new_x = np.delete(x, index)
print(new_x)
| 48 |
# Write a Python program to check if the list contains three consecutive common numbers in Python
# creating the array
arr = [4, 5, 5, 5, 3, 8]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == ar... | 78 |
# Write a Python program to download and display the content of robot.txt for en.wikipedia.org.
import requests
response = requests.get("https://en.wikipedia.org/robots.txt")
test = response.text
print("robots.txt for http://www.wikipedia.org/")
print("===================================================")
print... | 28 |
# Write a Pandas program to split a dataset, group by one column and get mean, min, and max values by group, also change the column name of the aggregated metric. 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.s... | 137 |
# Write a Python program to Numpy matrix.min()
# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[64, 1; 12, 3]')
# applying matrix.min() method
geeks = gfg.min()
print(geeks) | 38 |
# Write a Pandas program to find and replace the missing values in a given DataFrame which do not have any valuable information.
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':[70001,np.nan,70002,70004,np.nan,700... | 62 |
# Python Program to Read a Text File and Print all the Numbers Present in the Text File
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(... | 46 |
# Write a NumPy program to get the floor, ceiling and truncated values of the elements of a numpy array.
import numpy as np
x = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0])
print("Original array:")
print(x)
print("Floor values of the above array elements:")
print(np.floor(x))
print("Ceil values of the above arra... | 60 |
# Write a Python program to Check if two lists have at-least one element common
# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in th... | 110 |
# Write a Python program to Group Similar items to Dictionary Values List
# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using defaultdict + loop
from collections import defaultdict
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
# printing original... | 92 |
# Controlling the Web Browser with Python
# Import the required modules
from selenium import webdriver
import time
# Main Function
if __name__ == '__main__':
# Provide the email and password
email = 'example@example.com'
password = 'password'
options = webdriver.ChromeOptions()
options.ad... | 218 |
# Find words which are greater than given length k in Python
// C++ program to find all string
// which are greater than given length k
#include <bits/stdc++.h>
using namespace std;
// function find string greater than
// length k
void string_k(string s, int k)
{
// create the empty string
string w = "";
... | 160 |
# Write a Python program to Search an Element in a Circular Linked List
# Python program to Search an Element
# in a Circular Linked List
# Class to define node of the linked list
class Node:
def __init__(self,data):
self.data = data;
self.next = None;
class CircularLi... | 386 |
# Write a NumPy program to convert an array to a float type.
import numpy as np
import numpy as np
a = [1, 2, 3, 4]
print("Original array")
print(a)
x = np.asfarray(a)
print("Array converted to a float type:")
print(x)
| 40 |
# Write a Python program to create all possible permutations from a given collection of distinct numbers.
def permute(nums):
result_perms = [[]]
for n in nums:
new_perms = []
for perm in result_perms:
for i in range(len(perm)+1):
new_perms.append(perm[:i] + [n] + perm[i:])
result_per... | 57 |
# Write a NumPy program to shuffle numbers between 0 and 10 (inclusive).
import numpy as np
x = np.arange(10)
np.random.shuffle(x)
print(x)
print("Same result using permutation():")
print(np.random.permutation(10))
| 27 |
# Write a Python program to count the number of lines in a text file.
def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print("Number of lines in the file: ",file_lengthy("test.txt"))
| 38 |
# Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array.
import numpy as np
array_nums = np.arange(0, 40, 2)
print("Original array:")
print(array_nums)
print("\nNew array of shape(5, 4):")
new_array =... | 66 |
# Write a NumPy program to count the occurrence of a specified item in a given NumPy array.
import numpy as np
nums = np.array([10, 20, 20, 20, 20, 0, 20, 30, 30, 30, 0, 0, 20, 20, 0])
print("Original array:")
print(nums)
print(np.count_nonzero(nums == 10))
print(np.count_nonzero(nums == 20))
print(np.count_nonzero(... | 54 |
# Write a Python program to find the class wise roll number from a tuple-of-tuples.
from collections import defaultdict
classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)
class_rollno = defaultdict(list)
for class_name, roll_id in classes:
class_rollno[class_... | 45 |
# Changing the colour of Tkinter Menu Bar in Python
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Set the title and geometry to your app
app.title("Geeks For Geeks")
app.geometry("800x500")
# Create menubar by setting the color
menubar = Menu(app, background='blue', fg='w... | 122 |
# Write a Pandas program to create a stacked histograms plot with more bins of opening, closing, high, low 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... | 76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.