Skip to main content

Posts

Adjacency List in a Graph

   from collections import defaultdict graph=defaultdict(list) v,e=map(int,input().split()) for i in range(e):     u,v=map(str,input().split())     graph[u].append(v)     graph[v].append(u)      for i in graph:     print(i,"->",graph[i]) Input: 7 9 A B A C A F C E C F C D D E D G G F Output: F -> ['A', 'C', 'G'] C -> ['A', 'E', 'F', 'D'] G -> ['D', 'F'] D -> ['C', 'E', 'G'] A -> ['B', 'C', 'F'] E -> ['C', 'D'] B -> ['A']       
Recent posts

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

  """ n=[23, 2, 2, 24, 7, 23, 5, 24, 5] printing  res n[i] res^n[i] 23  2       21 21  2       23 23  24      15 15  7       8 8   23      31 31  5       26 26  24      2 2   5       7 so the res = 7  we know that n^n=0 where n^0 = n this is how the repeated elements are vanised """ def find(n):     res=n[0]          for i in range(1,len(n)):         res=res^ n[i]     return res n=list(map(int,input().split())) s=find(n) print(s)

Check the whether the kth bit from right is SET ?

  #  #lets see n=6 # #in binary 6 is 101 =>6  #lets check at 1 from right # 1<<(1-1) => its left shift so it multiplies 1 with 2**(1-1) thats 2**0  # so 2**0 is 1  #1*1=>1 #in binary 6 is 101 #in binary 1 is 001 # #so bitwise & = 001 =>1 SET # # Ex2 #In binary 6 is 101 =>6  #lets check at 2 from right # 1<<(2-1) => its left shift so it multiplies 1 with 2**(2-1) thats 2**1 # so 2**1 is 2  #1*2=>2 #in binary 6 is 101 #in binary 1 is 010 # #so bitwise & = 000 =>0 NOT SET def kthbit(n,k):          if n&(1<<(k-1)):         print("SET")     else:         print("Not Set")              n,k=map(int,input().split()) print("The bit in ",bin(n)[2:],"at",k,"from right is") kthbit(n,k)

Once's in Binary Representation of a Number

  #  #lets see n=7 #count =0 #in binary 7 is 111 =>7 count =1 #in binary 6 is 101 # #so bitwise & = 101 =>6 count =2 #in binary 6 is 101 #in binary 5 is 100 # #so bitwise & = 100 =>5 count =3 #in binary 5 is 100 #in binary 4 is 011 # #so bitwise & = 000 =>0 def onces(n):     cnt=0      while(n):         cnt+=1         n=n&(n-1)          return cnt                     n=int(input()) print("Onces in ",bin(n)[2:],"is",onces(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)