Loading...
More Python Posts
# Python binary search functiondef binary_search(arr, target):left = 0right = len(arr) - 1while left <= right:mid = (left + right) // 2if arr[mid] == target:return midelif arr[mid] < target:left = mid + 1else:right = mid - 1return -1# Usagearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]target = 7result = binary_search(arr, target)if result != -1:print(f"Element is present at index {result}")else:print("Element is not present in array")
# Listlst = [1, 2, 3, 'Alice', 'Alice']# One-Linerindices = [i for i in range(len(lst)) if lst[i]=='Alice']# Resultprint(indices)# [3, 4]
import pandas as pdx = pd.read_excel(FILE_NAME)print(x)
class Rectangle:passclass Square(Rectangle):passrectangle = Rectangle()square = Square()print(isinstance(rectangle, Rectangle)) # Trueprint(isinstance(square, Rectangle)) # Trueprint(isinstance(square, Square)) # Trueprint(isinstance(rectangle, Square)) # False
from collections import Counterdef find_parity_outliers(nums):return [x for x in numsif x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]]find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]
# Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.# For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.# Python program to print all primes smaller than or equal to# n using Sieve of Eratosthenesdef SieveOfEratosthenes(n):# Create a boolean array "prime[0..n]" and initialize# all entries it as true. A value in prime[i] will# finally be false if i is Not a prime, else true.prime = [True for i in range(n + 1)]p = 2while (p * p <= n):# If prime[p] is not changed, then it is a primeif (prime[p] == True):# Update all multiples of pfor i in range(p * 2, n + 1, p):prime[i] = Falsep += 1prime[0]= Falseprime[1]= False# Print all prime numbersfor p in range(n + 1):if prime[p]:print (p)# driver programif __name__=='__main__':n = 30print("Following are the prime numbers smaller")print("than or equal to ", n)print("than or equal to ", n)SieveOfEratosthenes(n)