Posts

Showing posts with the label pythoncoding

Adjacency List in a Graph

Image
Understanding Graph Representation in Python with Adjacency Lists In this post, we'll explore how to represent a graph using adjacency lists in Python, utilizing the defaultdict from the collections module. Graphs are a powerful data structure that allows us to model relationships between nodes (or vertices) with connections (or edges). This representation is particularly useful when you need to store and visualize relationships, like social networks, maps, or web page links. Let's dive into the code and break it down step by step. Code Overview Here’s a Python implementation that reads a graph from user input and outputs the adjacency list representation of the graph. Python Code:  from collections import defaultdict # Initialize an empty graph as a defaultdict of lists graph = defaultdict( list ) # Read the number of vertices (v) and edges (e) v, e = map ( int , input ().split()) # Iterate over the number of edges to build the graph for i in range (e): u, v = ...

Find the single occurence of a element in the list of elements with twice repeative

Image
In this post, we’ll solve an interesting problem where we need to find the single element that appears only once in a list of integers, while all other elements appear exactly twice. Problem Explanation Consider a list of integers where every element except one appears twice. We want to efficiently find the element that occurs only once. Here’s an example: n = [23, 2, 2, 24, 7, 23, 5, 24, 5] In this list, every number except 7 appears twice. Our goal is to find that single occurrence using an efficient algorithm. Approach: Using XOR to Find the Single Element We can solve this problem in linear time O ( n ) O(n) O ( n ) and constant space O ( 1 ) O(1) O ( 1 ) using the XOR (bitwise exclusive OR) operation. How XOR Helps XOR Basics: XOR is a bitwise operation that compares the binary representation of two numbers. The key property of XOR is that when you XOR a number with itself, the result is 0 : n ⊕ n = 0 n \oplus n = 0 n ⊕ n = 0 XORing any number with 0 returns the number itself...

Check the whether the kth bit from right is SET ?

Image
    In this blog post, we’ll explore how to check whether the k-th bit (from the right) of a number is set (i.e., is equal to 1) using bitwise operations in Python. This is a common problem that’s useful in programming challenges and low-level bit manipulation. Problem Explanation We are given a number n in its binary form and an integer k , which indicates the position of the bit we want to check, starting from the right (with the least significant bit being the 1st bit). The goal is to determine whether the bit at position k is set (i.e., 1) or not set (i.e., 0). Example Walkthrough Let’s take an example to clarify the concept. Suppose we have the number n = 6 , which is 110 in binary. Now, we want to check if the 1st bit from the right is set. Convert the number to binary: The binary representation of 6 is 110 . Identify the bit position: We want to check the 1st bit from the right. Bitwise AND Operation: To check if the k-th bit is set, we perform a bitwise AND betwee...

Once's in Binary Representation of a Number

Image
Let’s explore how to count the number of 1 s (also known as ones) in the binary representation of a number. We'll take the number n = 7 as an example. Initialization : Start with a count of 0 . Binary Representation : The binary representation of 7 is 111 , which contains 3 ones. Thus, we increment our count to 1 . Bit Manipulation : Now, we perform a bitwise operation to remove the rightmost 1 : n = 7 (binary 111 ) When we apply the operation n & (n - 1) , we get: 7 - 1 = 6 (binary 110 ) 7 & 6 = 6 (binary 110 ) After this operation, the count of 1 s is now 2 (for the binary 110 ). Repeat : We continue this process: Now n = 6 (binary 110 ) 6 - 1 = 5 (binary 101 ) 6 & 5 = 4 (binary 100 ) The count increases to 3 . Final Steps : We continue until n becomes 0 : n = 5 (binary 101 ) 5 - 1 = 4 (binary 100 ) 5 & 4 = 0 (binary 000 ) At this point, n is 0 , and the final count of ones is 3 . Code Implementation Here is the code that implements this process: py...

Check the given number is power of 2 using BitWise

  # if a number is power of 2 then n&(n-1) results 0 #lets see n=4 #in binary 4 is 100 #in binary 3 is 011 #so bitwise & = 000 =>0 def ispowerof2(n):     x=n      y=n&(n-1)          print(x and not(y))      n=int(input()) ispowerof2(n)  

Find the even odd using bitwise

  We can use bitwise And to check even or odd if n is a number then  n&1 result the 1 else result the 0 def oddeven(n):     if n&1==1:         print("ODD")     else:         print("EVEN")           n=int(input()) oddeven(n)

Print all Prime numbers Using Sieve of Eratosthenes

  from math import sqrt def allPrime(n):     l=[True]*(n+1)     l[0]=False     l[1]=False     for i in range(2,int(sqrt(n))+1):         if l[i]==True:             for j in range(i*i,n+1,i):                 l[j]=False                      for i in range(n+1):         if l[i]==True:             print(i,end=" ")   n=int(input()) allPrime(n)

Is it a Prime?

  from math import sqrt def isPrime(n):     if n==0 or n==1:         return False     if n==2 or n==3:         return True     if n%2==0 or n%3==0:         return False     for i in range(5,int(sqrt(n))+1):         if n%i==0 or n%(i+2)==0:             return False     return True      n=int(input()) print("Is",n,"a Prime",isPrime(n))   

Find the Divisors of a number

  from math import sqrt def div(n):     div1=set()     for i in range(1,int(sqrt(n))+1):         if n%i==0:             div1.add(i)             div1.add(n//i)     return sorted(list(div1)) n=int(input()) print("The divisors of ",n,"is",*div(n))  

GCD and LCM using Euclid algo

  #product of two number = lcm * gcd  def gcd(a,b):     if a==0:         return b     return gcd(b%a,a) def lcm(a,b):     prod=a*b      hcf=gcd(a,b)     return prod//hcf a,b=map(int,input().split()) print("lcm: ",lcm(a,b)," ","gcd: ",gcd(a,b))