• Nov 19, 2022 •CodeCatch
0 likes • 0 views
# 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 Eratosthenes def 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 = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False # Print all prime numbers for p in range(n + 1): if prime[p]: print (p) # driver program if __name__=='__main__': n = 30 print("Following are the prime numbers smaller") print("than or equal to ", n) print("than or equal to ", n) SieveOfEratosthenes(n)
# Python program for implementation of Selection # Sort import sys A = [64, 25, 12, 22, 11] # Traverse through all array elements for i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test above print ("Sorted array") for i in range(len(A)): print("%d" %A[i]),
0 likes • 16 views
def sum_of_powers(end, power = 2, start = 1): return sum([(i) ** power for i in range(start, end + 1)]) sum_of_powers(10) # 385 sum_of_powers(10, 3) # 3025 sum_of_powers(10, 3, 5) # 2925
0 likes • 3 views
def clamp_number(num, a, b): return max(min(num, max(a, b)), min(a, b)) clamp_number(2, 3, 5) # 3 clamp_number(1, -1, -5) # -1
• May 31, 2023 •CodeCatch
class Rectangle: pass class Square(Rectangle): pass rectangle = Rectangle() square = Square() print(isinstance(rectangle, Rectangle)) # True print(isinstance(square, Rectangle)) # True print(isinstance(square, Square)) # True print(isinstance(rectangle, Square)) # False
• Jul 24, 2024 •AustinLeath
from statistics import median, mean, mode def print_stats(array): print(array) print("median =", median(array)) print("mean =", mean(array)) print("mode =", mode(array)) print() print_stats([1, 2, 3, 3, 4]) print_stats([1, 2, 3, 3])