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'))
print("\nMinute ceiling:")
print(arrow.utcnow().floor('minute'))
print("\nSecond ceiling:")
print(arrow.utcnow().floor('second'))
| 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',
'Masters', 'Graduate'],
'C': [27, 23, 21, 23, 24]})
df | 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 put them in\
1st and 5th position of Array 1")
a1.put([0, 4], a2)
print("Resultant Array :")
print(a1) | 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]
:type target: int
:rtype: int
"""
nums = sorted(nums)
# Let top[i] be the sum of largest i numbers.
top = [
0,
nums[-1],
nums[-1] + nums[-2]
]
min_diff = float('inf')
three_sum = 0
# Find range of the least number in curr_n (0, 1, 2 or 3)
# numbers that sum up to curr_target, then find range of
# 2nd least number and so on by recursion.
def closest(curr_target, curr_n, lo=0):
if curr_n == 0:
nonlocal min_diff, three_sum
if abs(curr_target) < min_diff:
min_diff = abs(curr_target)
three_sum = target - curr_target
return
next_n = curr_n - 1
max_i = len(nums) - curr_n
max_i = bisect(
nums, curr_target // curr_n,
lo, max_i)
min_i = bisect_left(
nums, curr_target - top[next_n],
lo, max_i) - 1
min_i = max(min_i, lo)
for i in range(min_i, max_i + 1):
if min_diff == 0:
return
if i == min_i or nums[i] != nums[i - 1]:
next_target = curr_target - nums[i]
closest(next_target, next_n, i + 1)
closest(target, 3)
return three_sum
s = Solution()
nums = [1, 2, 3, 4, 5, -6]
target = 14
result = s.threeSumClosest(nums, target)
print("\nArray values & target value:",nums,"&",target)
print("Sum of the integers closest to target:", result)
nums = [1, 2, 3, 4, -5, -6]
target = 5
result = s.threeSumClosest(nums, target)
print("\nArray values & target value:",nums,"&",target)
print("Sum of the integers closest to target:", result)
| 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 consumption sample data:")
print(w_a_con.head())
print("\nThe world alcohol consumption details in the year 1986 where WHO region is Western Pacific and country is VietNam :")
print(w_a_con[(w_a_con['Year']==1986) & (w_a_con['WHO region']=='Western Pacific') & (w_a_con['Country']=='Viet Nam')])
| 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.title.text)
print("Parent content of the title:")
print(soup.title.parent)
| 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'], 5: ['Zachary Simon']}
print("\nOriginal dictionary:")
print(students)
print("\nA key-value list pairings of the said dictionary:")
print(test(students))
| 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 ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass | 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 file object along with extension
file_name = str_current_datetime+".txt"
file = open(file_name, 'w')
print("File created : ", file.name)
file.close() | 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(', '.join(row))
print("\n\nWithout initial spaces after a delimiter:\n")
with open('departments.csv', 'r') as csvfile:
data = csv.reader(csvfile, skipinitialspace=True)
for row in data:
print(', '.join(row))
| 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)
print(prime_eratosthenes(100));
| 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],
'Akash' : [1, 8, 9],
'Nikhil': [10, 22, 4],
'Akshat': [5, 11, 22]}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Remove duplicate values across Dictionary Values
# Using Counter() + list comprehension
cnt = Counter()
for idx in test_dict.values():
cnt.update(idx)
res = {idx: [key for key in j if cnt[key] == 1]
for idx, j in test_dict.items()}
# printing result
print("Uncommon elements records : " + str(res)) | 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 value of the said three lists:")
print(min(nums1+nums2+nums3))
| 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': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print("Original DataFrame:")
print(df)
print("\nIf a specified column starts with a specified string?")
df['company_code_starts_with'] = list(
map(lambda x: x.startswith('ze'), df['company_code']))
print(df)
| 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 file object along with extension
file_name = str_current_datetime+".txt"
file = open(file_name, 'w')
print("File created : ", file.name)
file.close() | 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 Frequent Character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = min(all_freq, key = all_freq.get)
# printing result
print ("The minimum of all characters in GeeksforGeeks is : " + str(res)) | 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(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print netAmount
| 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 size element-by-element:")
print(np.multiply(nums1, nums2))
| 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 keys of the said flat dictionary:")
print(test(students))
| 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,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)
return [x[0] for x in url]
# Driver Code
string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/'
print("Urls: ", Find(string)) | 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 the said array:")
new_array2 = np.resize(x,(6,6))
print(new_array2)
| 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:
# opening and reading the file
file_read = open(file_name, "r")
# asking the user to enter the string to be
# searched
text = input("Enter the String: ")
# reading file content line by line.
lines = file_read.readlines()
new_list = []
idx = 0
# looping through each line in the file
for line in lines:
# if line have the input string, get the index
# of that line and put the
# line into newly created list
if text in line:
new_list.insert(idx, line)
idx += 1
# closing file after reading
file_read.close()
# if length of new list is 0 that means
# the input string doesn't
# found in the text file
if len(new_list)==0:
print("\n\"" +text+ "\" is not found in \"" +file_name+ "\"!")
else:
# displaying the lines
# containing given string
lineLen = len(new_list)
print("\n**** Lines containing \"" +text+ "\" ****\n")
for i in range(lineLen):
print(end=new_list[i])
print()
# entering except block
# if input file doesn't exist
except :
print("\nThe file doesn't exist!") | 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(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
def color_negative_red(val):
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
print("\nNegative numbers red and positive numbers black:")
df.style.highlight_null(null_color='red')
| 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'))):
count_chars += 1
return count_chars
str1 = input("Input a string: ")
print("Number of characters of the said string at same position as in English alphabet:")
print(count_char_position(str1))
| 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', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
s6 = pd.Series(['S6', 'Scarlette Fisher', 205], index=['student_id', 'name', 'marks'])
dicts = [{'student_id': 'S6', 'name': 'Scarlette Fisher', 'marks': 203},
{'student_id': 'S7', 'name': 'Bryce Jensen', 'marks': 207}]
print("Original DataFrames:")
print(student_data1)
print("\nDictionary:")
print(s6)
combined_data = student_data1.append(dicts, ignore_index=True, sort=False)
print("\nCombined Data:")
print(combined_data)
| 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 list of lists:")
print(unique_values_in_list_of_lists(nums))
chars = [['h','g','l','k'], ['a','b','d','e','c'], ['j','i','y'], ['n','b','v','c'], ['x','z']]
print("\nOriginal list:")
print(chars)
print("Unique values of the said list of lists:")
print(unique_values_in_list_of_lists(chars))
| 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()
# for space between widgets
tk.Label(root, text=" ").pack()
# Frame for button border with black border color
button_border = tk.Frame(root, highlightbackground = "black",
highlightthickness = 2, bd=0)
bttn = tk.Button(button_border, text = 'Submit', fg = 'black',
bg = 'yellow',font = (("Times New Roman"),15))
bttn.pack()
button_border.pack()
root.mainloop() | 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(collection) <= 1 or n <= 1:
return
insert_next(collection, n - 1)
rec_insertion_sort(collection, n - 1)
def insert_next(collection: list, index: int):
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
collection[index - 1], collection[index] = (
collection[index],
collection[index - 1],
)
insert_next(collection, index + 1)
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Insertion Sort the said list becomes:")
rec_insertion_sort(nums, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Insertion Sort the said list becomes:")
rec_insertion_sort(nums, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Insertion Sort the said list becomes:")
rec_insertion_sort(nums, len(nums))
print(nums)
| 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
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
# printing result
print("The words frequency : " + str(res)) | 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(key)
self.vertices[key] = vertex
def get_vertex(self, key):
"""Return vertex object with the corresponding key."""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
"""Add edge from src_key to dest_key with given weight."""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key
def add_neighbour(self, dest, weight):
"""Make this vertex point to dest with given edge weight."""
self.points_to[dest] = weight
def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
def get_weight(self, dest):
"""Get weight of edge from this vertex to dest."""
return self.points_to[dest]
def does_it_point_to(self, dest):
"""Return True if this vertex points to dest."""
return dest in self.points_to
def floyd_warshall(g):
"""Return dictionaries distance and next_v.
distance[u][v] is the shortest distance from vertex u to v.
next_v[u][v] is the next vertex after vertex v in the shortest path from u
to v. It is None if there is no path between them. next_v[u][u] should be
None for all u.
g is a Graph object which can have negative edge weights.
"""
distance = {v:dict.fromkeys(g, float('inf')) for v in g}
next_v = {v:dict.fromkeys(g, None) for v in g}
for v in g:
for n in v.get_neighbours():
distance[v][n] = v.get_weight(n)
next_v[v][n] = n
for v in g:
distance[v][v] = 0
next_v[v][v] = None
for p in g:
for v in g:
for w in g:
if distance[v][w] > distance[v][p] + distance[p][w]:
distance[v][w] = distance[v][p] + distance[p][w]
next_v[v][w] = next_v[v][p]
return distance, next_v
def print_path(next_v, u, v):
"""Print shortest path from vertex u to v.
next_v is a dictionary where next_v[u][v] is the next vertex after vertex u
in the shortest path from u to v. It is None if there is no path between
them. next_v[u][u] should be None for all u.
u and v are Vertex objects.
"""
p = u
while (next_v[p][v]):
print('{} -> '.format(p.get_key()), end='')
p = next_v[p][v]
print('{} '.format(v.get_key()), end='')
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('floyd-warshall')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')
elif operation == 'floyd-warshall':
distance, next_v = floyd_warshall(g)
print('Shortest distances:')
for start in g:
for end in g:
if next_v[start][end]:
print('From {} to {}: '.format(start.get_key(),
end.get_key()),
end = '')
print_path(next_v, start, end)
print('(distance {})'.format(distance[start][end]))
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break | 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', 'K']
def __init__(self):
pass
# Define a class to categorize each card
class Deck(Cards):
def __init__(self):
Cards.__init__(self)
self.mycardset = []
for n in suites:
for c in values:
self.mycardset.append((c)+" "+"of"+" "+n)
# Method to remove a card from the deck
def popCard(self):
if len(self.mycardset) == 0:
return "NO CARDS CAN BE POPPED FURTHER"
else:
cardpopped = self.mycardset.pop()
print("Card removed is", cardpopped)
# Define a class gto shuffle the deck of cards
class ShuffleCards(Deck):
# Constructor
def __init__(self):
Deck.__init__(self)
# Method to shuffle cards
def shuffle(self):
if len(self.mycardset) < 52:
print("cannot shuffle the cards")
else:
shuffle(self.mycardset)
return self.mycardset
# Method to remove a card from the deck
def popCard(self):
if len(self.mycardset) == 0:
return "NO CARDS CAN BE POPPED FURTHER"
else:
cardpopped = self.mycardset.pop()
return (cardpopped)
# Driver Code
# Creating objects
objCards = Cards()
objDeck = Deck()
# Player 1
player1Cards = objDeck.mycardset
print('\n Player 1 Cards: \n', player1Cards)
# Creating object
objShuffleCards = ShuffleCards()
# Player 2
player2Cards = objShuffleCards.shuffle()
print('\n Player 2 Cards: \n', player2Cards)
# Remove some cards
print('\n Removing a card from the deck:', objShuffleCards.popCard())
print('\n Removing another card from the deck:', objShuffleCards.popCard()) | 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 the said array:")
print(L)
| 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([int(j) for j in input().split()])
if row_size!=col_size:
print("Given Matrix is not a Square Matrix.")
else:
#compute the transpose matrix
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]
# check given matrix elements and transpose
# matrix elements are same or not.
flag=0
for i in range(0, row_size):
for j in range(0, col_size):
if matrix[i][j] != tran_matrix[i][j]:
flag=1
break
if flag==1:
print("Given Matrix is not a symmetric Matrix.")
else:
print("Given Matrix is a symmetric Matrix.") | 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 the said list:")
print(remove_none(nums))
| 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(arrow.utcnow().format('DD-MM-YYYY HH:mm:ss ZZ'))
print(arrow.utcnow().format('\nMMMM DD, YYYY'))
print(arrow.utcnow().format())
| 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 inn in range(out+1, size):
if arr[inn] < arr[min]:
min = inn
temp=arr[out]
arr[out]=arr[min]
arr[min]=temp
print("\nAfter Sorting Array Elements are: ",arr)
| 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):
if current is None:
return None
current = current.next
return current
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_beg(self, new_node):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_llist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_llist.insert_at_beg(new_node)
elif position == 'end':
a_llist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_llist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_llist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_llist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_llist.get_node(index)
if node is None:
print('No such index.')
continue
a_llist.remove(node)
elif operation == 'quit':
break | 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
print("New list after removing all even numbers: ", list1) | 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 dictionary into a list of lists:")
print(test(color_dict))
color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Convert the said dictionary into a list of lists:")
print(test(color_dict))
| 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 = int(input("Input number of words: "))
print("Input the words: ")
for i in range(n):
word_array.append(input().strip())
word_ctr = OrderedCounter(word_array)
print(len(word_ctr))
for word in word_ctr:
print(word_ctr[word],end=' ')
| 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 the current year:")
print(len(doc.cssselect('.item-list li')))
| 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</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from
w3resource.com</a></p>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.find( href="https://www.w3resource.com/css/CSS-tutorials.php"))
| 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['department_id'], row['department_name'])
| 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:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def tim_sort(lst):
length = len(lst)
runs, sorted_runs = [], []
new_run = [lst[0]]
sorted_array = []
i = 1
while i < length:
if lst[i] < lst[i - 1]:
runs.append(new_run)
new_run = [lst[i]]
else:
new_run.append(lst[i])
i += 1
runs.append(new_run)
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(lst)
print("After applying Timsort the said list becomes:")
sorted_lst = tim_sort(lst)
print(sorted_lst)
lst = "Python"
print("\nOriginal list:")
print(lst)
print("After applying Timsort the said list becomes:")
sorted_lst = tim_sort(lst)
print(sorted_lst)
lst = (1.1, 1, 0, -1, -1.1)
print("\nOriginal list:")
print(lst)
print("After applying Timsort the said list becomes:")
sorted_lst = tim_sort(lst)
print(sorted_lst)
| 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('Deependra', 40) )
list.append( geeks('Reaper', 44) )
for obj in list:
print( obj.name, obj.roll, sep =' ' )
# We can also access instances attributes
# as list[0].name, list[0].roll and so on. | 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 Ellie'],
['03', 'V', 'Baptist Kamal'],
['04', 'V', 'Lavanya Davide'],
['05', 'V', 'Fulton Antwan'],
['06', 'V', 'Euanthe Sandeep'],
['07', 'V', 'Endzela Sanda'],
['08', 'V', 'Victoire Waman'],
['09', 'V', 'Briar Nur'],
['10', 'V', 'Rose Lykos']])
print("Original array:")
print(student)
np.random.shuffle(student[2:8])
print("Shuffle the said array rows starting from 3rd to 9th")
print(student)
| 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;12000
12/2/2011;Theatre;5000
13/2/2011;Comedy;8000
""")
# let's read the data using the Pandas
# read_csv() function
df = pd.read_csv(StringData, sep =";")
# Print the dataframe
print(df) | 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, 2566552.0, 23.0]
})
print("Original DataFrame:")
print(df)
print("\nReplace A with c:")
df = df.replace(["A", "D"], ["X", "Y"])
print(df)
| 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 array:")
print(result)
| 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_set)
print(test_duplicate([1,2,3,4,5]))
print(test_duplicate([1,2,3,4, 4]))
print(test_duplicate([1,1,2,2,3,3,4,4,5]))
| 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 unique elements!")
print(all_unique(nums1))
nums2 = [2,4,6,8,10,12,14]
print ("\nOriginal list:")
print(nums2)
print("\nIs the said list contains all unique elements!")
print(all_unique(nums2))
| 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'))
print(snake_case('GDScript'))
print(snake_case('BTW...what *do* you call that naming style? snake_case? '))
| 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] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i]) | 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(test)
| 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.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(df)
print('\nChange the name of an aggregated metric:')
grouped_single = df.groupby('school_code').agg({'age': [("mean_age","mean"), ("min_age", "min"), ("max_age","max")]})
print(grouped_single)
| 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,70005,"--",70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,"?",12.43,2480.4,250.45, 3045.6],
'ord_date': ['?','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,"--",3002,3001,3001],
'salesman_id':[5002,5003,"?",5001,np.nan,5002,5001,"?",5003,5002,5003,"--"]})
print("Original Orders DataFrame:")
print(df)
print("\nReplace the missing values with NaN:")
result = df.replace({"?": np.nan, "--": np.nan})
print(result)
| 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(letter) | 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 array elements:")
print(np.ceil(x))
print("Truncated values of the above array elements:")
print(np.trunc(x))
| 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 the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result
# driver code
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_data(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_data(a, b)) | 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 list
print("The original list : " + str(test_list))
# using defaultdict for default list
res = defaultdict(list)
for ele in test_list:
# appending Similar values
res[ele].append(ele)
# printing result
print("Similar grouped dictionary : " + str(dict(res))) | 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.add_argument("--start-maximized")
options.add_argument('--log-level=3')
# Provide the path of chromedriver present on your system.
driver = webdriver.Chrome(executable_path="C:/chromedriver/chromedriver.exe",
chrome_options=options)
driver.set_window_size(1920,1080)
# Send a get request to the url
driver.get('https://auth.geeksforgeeks.org/')
time.sleep(5)
# Finds the input box by name in DOM tree to send both
# the provided email and password in it.
driver.find_element_by_name('user').send_keys(email)
driver.find_element_by_name('pass').send_keys(password)
# Find the signin button and click on it.
driver.find_element_by_css_selector(
'button.btn.btn-green.signin-button').click()
time.sleep(5)
# Returns the list of elements
# having the following css selector.
container = driver.find_elements_by_css_selector(
'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold')
# Extracts the text from name,
# institution, email_id css selector.
name = container[0].text
try:
institution = container[1].find_element_by_css_selector('a').text
except:
institution = container[1].text
email_id = container[2].text
# Output Example 1
print("Basic Info")
print({"Name": name,
"Institution": institution,
"Email ID": email})
# Clicks on Practice Tab
driver.find_elements_by_css_selector(
'a.mdl-navigation__link')[1].click()
time.sleep(5)
# Selected the Container containing information
container = driver.find_element_by_css_selector(
'div.mdl-cell.mdl-cell--7-col.mdl-cell--12-col-phone.\
whiteBgColor.mdl-shadow--2dp.userMainDiv')
# Selected the tags from the container
grids = container.find_elements_by_css_selector(
'div.mdl-grid')
# Iterate each tag and append the text extracted from it.
res = set()
for grid in grids:
res.add(grid.text.replace('\n',':'))
# Output Example 2
print("Practice Info")
print(res)
# Quits the driver
driver.close()
driver.quit() | 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 = "";
// iterate the loop till every space
for(int i = 0; i < s.size(); i++)
{
if(s[i] != ' ')
// append this sub string in
// string w
w = w + s[i];
else {
// if length of current sub
// string w is greater than
// k then print
if(w.size() > k)
cout << w << " ";
w = "";
}
}
}
// Driver code
int main()
{
string s = "geek for geeks";
int k = 3;
s = s + " ";
string_k(s, k);
return 0;
}
// This code is contributed by
// Manish Shaw (manishshaw1) | 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 CircularLinkedList:
# Declaring Circular Linked List
def __init__(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
# Adds new nodes to the Circular Linked List
def add(self,data):
# Declares a new node to be added
newNode = Node(data);
# Checks if the Circular
# Linked List is empty
if self.head.data is None:
# If list is empty then new node
# will be the first node
# to be added in the Circular Linked List
self.head = newNode;
self.tail = newNode;
newNode.next = self.head;
else:
# If a node is already present then
# tail of the last node will point to
# new node
self.tail.next = newNode;
# New node will become new tail
self.tail = newNode;
# New Tail will point to the head
self.tail.next = self.head;
# Function to search the element in the
# Circular Linked List
def findNode(self,element):
# Pointing the head to start the search
current = self.head;
i = 1;
# Declaring f = 0
f = 0;
# Check if the list is empty or not
if(self.head == None):
print("Empty list");
else:
while(True):
# Comparing the elements
# of each node to the
# element to be searched
if(current.data == element):
# If the element is present
# then incrementing f
f += 1;
break;
# Jumping to next node
current = current.next;
i = i + 1;
# If we reach the head
# again then element is not
# present in the list so
# we will break the loop
if(current == self.head):
break;
# Checking the value of f
if(f > 0):
print("element is present");
else:
print("element is not present");
# Driver Code
if __name__ == '__main__':
# Creating a Circular Linked List
'''
Circular Linked List we will be working on:
1 -> 2 -> 3 -> 4 -> 5 -> 6
'''
circularLinkedList = CircularLinkedList();
#Adding nodes to the list
circularLinkedList.add(1);
circularLinkedList.add(2);
circularLinkedList.add(3);
circularLinkedList.add(4);
circularLinkedList.add(5);
circularLinkedList.add(6);
# Searching for node 2 in the list
circularLinkedList.findNode(2);
#Searching for node in the list
circularLinkedList.findNode(7); | 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_perms = new_perms
return result_perms
my_nums = [1,2,3]
print("Original Cofllection: ",my_nums)
print("Collection of distinct numbers:\n",permute(my_nums))
| 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 = array_nums.reshape(5, 4)
print(new_array)
print("\nRestore the reshaped array into a 1-D array:")
print(new_array.flatten())
| 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(nums == 30))
print(np.count_nonzero(nums == 0))
| 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_name].append(roll_id)
print(class_rollno)
| 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='white')
# Declare file and edit for showing in menubar
file = Menu(menubar, tearoff=False, background='yellow')
edit = Menu(menubar, tearoff=False, background='pink')
# Add commands in in file menu
file.add_command(label="New")
file.add_command(label="Exit", command=app.quit)
# Add commands in edit menu
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
# Display the file and edit declared in previous step
menubar.add_cascade(label="File", menu=file)
menubar.add_cascade(label="Edit", menu=edit)
# Displaying of menubar in the app
app.config(menu=menubar)
# Make infinite loop for displaying app on screen
app.mainloop() | 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_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(30,30))
df2.hist();
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc., From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()
| 76 |