├── .idea
├── .gitignore
├── misc.xml
├── modules.xml
├── python_practice_codes.iml
└── vcs.xml
├── 01-12-23--002
├── MinOp.py
├── PrefixSum.py
└── RotateList.py
├── 01-12-23
├── MinOperation.py
├── PrefixSum.py
└── SlidingWindow.py
├── 2021-2025
├── 01-05-2023
│ ├── Diagonal.py
│ └── Permute.py
├── 02-05-2024
│ ├── MultiSolver.py
│ ├── RevString.py
│ ├── Stack.py
│ └── ValidPara.py
├── 03-04-2024
│ └── MissingNumber.py
├── 04-04-2024
│ └── TwoUnique.py
├── 10-04-2024
│ ├── PrefixSum.py
│ └── TwoPointer.py
├── 18-04-2024
│ ├── KadanesAlgo.py
│ ├── PrefixSum.py
│ └── SlidingWindow.py
├── 24-04-2024
│ └── Fibonaci.py
└── 25-04-2024
│ ├── IsPalindrome.py
│ └── Toh.py
├── 21-04-23
├── exception.py
└── index.py
├── 24-04-23
└── index.py
├── 25-04-23
└── index.py
├── 26-04-23
├── index.py
└── library_management.py
├── NITB1
├── 15-07-2024
│ ├── BitManipulation.py
│ ├── MissingNumber.py
│ └── TwoUnique.py
├── 16-07-2024
│ ├── AsPowerOfTwo.py
│ └── MinimumOps.py
├── 18-07-2024
│ ├── BinarySearch.py
│ ├── DistinctWindowSum.py
│ ├── Divide.py
│ ├── Kadanes.py
│ ├── SlidingWindow.py
│ └── TwoPointr.py
├── 19-07-2024
│ ├── Diagonal.py
│ └── PrefixSum.py
├── 20-07-2024
│ ├── ClimbSatirs.py
│ ├── MergeSortedArray.py
│ ├── Permute.py
│ ├── RotateArray.py
│ ├── Spiral.py
│ └── SubSequence.py
├── 22-07-2024
│ ├── IsValid.py
│ └── Toh.py
├── 23-07-2024
│ ├── LinkedList.py
│ └── NQueen.py
├── 24-07-2024
│ └── Graph.py
├── 26-07-2024
│ └── Tree.py
└── B2
│ ├── 01-08-2024
│ ├── Kadanes.py
│ ├── PrefixSum.py
│ └── SlidingWindow.py
│ ├── 05-08-2024
│ ├── DiagonalParsing.py
│ ├── IsValid.py
│ └── StringMultiSolver.py
│ ├── 06-08-2024
│ ├── NumberOfWays.py
│ ├── Permute.py
│ └── Recursion.py
│ ├── 07-08-2024
│ └── NQueen.py
│ ├── 08-08-2024
│ ├── DistinctWindowSum.py
│ ├── LinkedList.py
│ ├── MaximumSum.java
│ └── Spriral.py
│ ├── 09-08-2024
│ ├── Graph.py
│ └── TrappingRainWater.py
│ ├── 10-08-2024
│ └── Graph.py
│ ├── 13-08-2024
│ ├── .vscode
│ │ └── settings.json
│ ├── Graph.py
│ ├── Graph2.py
│ └── NumberOfIslands.py
│ ├── 30-07-2024
│ ├── MissingNumber.py
│ └── TwoUniqueNumber.py
│ └── 31-07-2024
│ ├── MinimumDecrement.py
│ └── TargetSum.py
├── PB2
├── ClimbStairs.py
├── IsPalindrome.py
├── Permute.py
└── Toh.py
├── algorithms-1
└── 06-11-23
│ ├── MissingNumber.py
│ └── TwoUniqueNumber.py
├── algorithms
├── batch2
│ ├── 07-11-23
│ │ ├── missing_number.py
│ │ ├── two_pointer.py
│ │ └── two_unique_number.py
│ ├── 08-11-23
│ │ ├── Kadanes.py
│ │ ├── MultiSolver.py
│ │ └── SlidingWindow.py
│ ├── 11-11-23
│ │ ├── LinkedList.py
│ │ └── MergKSortedList.py
│ └── 14-11-23
│ │ └── graph.py
└── batchB6
│ ├── 06-11-23
│ ├── MissingNumber.py
│ └── TwoUniqueNumber.py
│ ├── 07-11-23
│ ├── MergeSortedArray.py
│ ├── PrefixSum.py
│ └── Substring.py
│ ├── 08-11-23
│ ├── permute.py
│ └── toh.py
│ ├── 11-11-23
│ ├── LinkedList.py
│ └── MergeKSortedList.py
│ └── 14-11-23
│ ├── NQueen.py
│ └── graph.py
├── coding-problems
├── .idea
│ ├── SRU.iml
│ ├── misc.xml
│ ├── modules.xml
│ ├── vcs.xml
│ └── workspace.xml
├── 10-10-23
│ ├── kadanes.py
│ ├── merge_sorted_arr.py
│ ├── missing_number.py
│ ├── query_subarray_sum.py
│ ├── sliding_window.py
│ └── two_pointer.py
├── 11-10-23
│ ├── all_palindrome.py
│ ├── recursion_time.py
│ ├── test_arr.py
│ └── unique_Position.py
├── 12-10-23
│ ├── all_permutation.py
│ ├── fib.py
│ ├── n_queen.py
│ ├── n_ways.py
│ └── single_linked_list.py
├── 13-10-23
│ └── single_linked_list.py
├── 14-10-23
│ └── pattern.py
├── 16-10-23
│ ├── graph.py
│ ├── hash_map.py
│ ├── heap_impl.py
│ └── test.txt
├── 17-10-23
│ ├── graph.py
│ ├── leetcode_1967.py
│ ├── stack.py
│ └── test.txt
├── 18-10-23
│ ├── chaining.py
│ └── linear_probing.py
└── 19-10-23
│ ├── Encapsulation.py
│ ├── Father.py
│ ├── Son.py
│ ├── __pycache__
│ └── Father.cpython-312.pyc
│ ├── inheritance.py
│ ├── polymorphism.py
│ ├── quadratic_probing.py
│ └── set_bits.py
├── cseab
└── 28-05-2024
│ └── MissingNumber.py
├── ece
├── 01-05-2024
│ ├── ClimbStairs.py
│ └── TraceDiagonally.py
├── 02-05-2024
│ ├── MultiSolver.py
│ ├── Permute.py
│ └── Toh.py
├── 03-04-2024
│ └── TwoPointer.py
├── 04-04-2024
│ ├── KadanesAlgo.py
│ └── SlidingWindow.py
├── 18-04-2024
│ └── PrefixSum.py
└── 24-04-2024
│ └── Palindrome.py
├── mlr-online-batch
├── .vscode
│ └── settings.json
├── BinarySearch.py
├── IsPowerOf2.py
├── Kadanes.py
├── MissingNumber.py
├── Queries.py
├── SubarraySum.py
├── TargetSum.py
└── TwoUnique.py
├── noNotebookNoPen
├── 02-01-24
│ ├── BinarySearch.py
│ ├── PrioritySum.py
│ └── SmallestMissingNumber.py
├── 02-04-24
│ └── TwoPointer.py
├── 08-01-24
│ ├── IsPalindromeUsingStack.py
│ ├── Stack.py
│ └── ValidParanthesis.py
├── 09-01-24
│ ├── AllPermutation.py
│ ├── IsValid.py
│ ├── Queue.py
│ └── RotateStack.py
├── 11-12-23
│ ├── BitManipulation.py
│ ├── MinOperation.py
│ ├── MissingNumber.py
│ ├── TwoUniqueNumber.py
│ └── UniqueNumber.py
├── 12-12-23
│ ├── SlidingWindow.py
│ └── TargetSum.py
├── 18-12-23
│ ├── Kadanes.py
│ ├── MergeSortedArray.py
│ └── rotateArray.py
├── 19-12-23
│ └── IsPalindrome.py
├── Next
│ ├── 04-03-2024
│ │ ├── Count.py
│ │ └── Pattern.py
│ ├── 05-03-2024
│ │ └── Array.py
│ ├── 08-04-2024
│ │ ├── Kadanes.py
│ │ └── SlidingWindow.py
│ ├── 11-03-2024
│ │ ├── CountFrequency.py
│ │ ├── Remove.py
│ │ └── ReverseArray.py
│ ├── 12-03-2024
│ │ ├── Fib.py
│ │ └── Function.py
│ ├── 15-04-2024
│ │ ├── Matrix.py
│ │ └── PrefixSum.py
│ └── 19-03-2024
│ │ ├── CountFrequency.py
│ │ └── DataStructure.py
└── csecd
│ └── MissingNumber.py
├── pyramid-3-2
└── 01-03-2024
│ ├── Graph.py
│ └── ListGraph.py
└── saturday
├── AllPermutation.py
├── MergeSortedList.py
└── Test.py
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/python_practice_codes.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/01-12-23--002/MinOp.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def main():
4 | arr = [5,7,8]
5 | wholeXor ,isAnsPossible =0, -1
6 | for e in arr: wholeXor = wholeXor^e
7 | ans = float('+inf')
8 | for e in arr:
9 | exceptThisElementXor = wholeXor^e
10 | if exceptThisElementXor < e:
11 | isAnsPossible = 1
12 | currentAns = e - exceptThisElementXor
13 | if currentAns < ans:
14 | ans = currentAns
15 | if isAnsPossible == -1:
16 | print(-1)
17 | else:
18 | print(ans)
19 |
20 | main()
21 |
--------------------------------------------------------------------------------
/01-12-23--002/PrefixSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def main():
4 | arr = [-2,3,4,-23,4,54,-67,78]
5 | queries = [[0,3],[1,3],[2,6],[4,7],[3,6]]
6 | ps = [0 for i in range(len(arr))]
7 | for i in range(len(arr)):
8 | if i == 0:ps[i] = arr[i]
9 | else: ps[i] = ps[i-1]+arr[i]
10 | for q in queries:
11 | si = q[0]
12 | ei = q[1]
13 | if si == 0:
14 | print(ps[ei])
15 | else:
16 | print(ps[ei]-ps[si-1])
--------------------------------------------------------------------------------
/01-12-23--002/RotateList.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def rotateList(head,k):
4 | temp, stack, queue, count = head, [], [], 1
5 | while temp is not None:
6 | if count < k:
7 | queue.append(temp.value)
8 | temp = temp.next
9 | else:
10 | stack.append(temp.value)
11 | temp = temp.next
12 | count+=1
13 | temp = head
14 | while len(stack) > 0:
15 | temp.val = stack.pop()
16 | temp = temp.next
17 | while len(queue) > 0:
18 | temp.val = queue.pop(0)
19 | temp = temp.next
20 |
21 | return head
--------------------------------------------------------------------------------
/01-12-23/MinOperation.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [5,7,8]
3 | wholeXor = 0
4 | ans = float('+inf')
5 | for e in arr:
6 | wholeXor = wholeXor^e
7 | isAnsPossible = -1
8 | for e in arr:
9 | exceptThisElementXor = wholeXor^e
10 | if e > exceptThisElementXor:
11 | isAnsPossible = 1
12 | currentAns = e - exceptThisElementXor
13 | if currentAns < ans:
14 | ans = currentAns
15 | if isAnsPossible == 1:
16 | print(ans)
17 | else:
18 | print(-1)
19 |
20 |
21 |
22 |
23 | main()
--------------------------------------------------------------------------------
/01-12-23/PrefixSum.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-3,4,5,2,3,-89,45,98]
3 | queries = [[0,2],[1,3],[2,5]]
4 | ans=[]
5 | ps=[0 for i in range(len(arr))]
6 | for i in range(len(arr)):
7 | if i ==0 :
8 | ps[i] = arr[i]
9 | else:
10 | ps[i]=ps[i-1]+arr[i]
11 | for query in queries:
12 | si = query[0]
13 | ei = query[1]
14 | currAns = ps[ei]-ps[si-1]
15 | ans.append(currAns)
16 | print(ans)
17 | main()
--------------------------------------------------------------------------------
/01-12-23/SlidingWindow.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr =[-2,3,2,3,45,67,-98,-4, ]
3 | k = 3
4 | ans = float('-inf')
5 | ps = 0
6 | i,j = 0,k-1
7 | while j < len(arr):
8 | if i == 0:
9 | currSum = sum(arr[i:j+1])
10 | ps = currSum
11 | else:
12 | currSum = ps-arr[i-1]+arr[j]
13 | i+=1
14 | j+=1
15 | ans = max(ans,currSum)
16 | print(ans)
17 |
18 | main()
19 |
--------------------------------------------------------------------------------
/2021-2025/01-05-2023/Diagonal.py:
--------------------------------------------------------------------------------
1 | def traceDiagonally(arr):
2 | n = len(arr)
3 | i,j = 0,0
4 | while j< n:
5 | i = 0
6 | jFlag = j
7 | while jFlag < n:
8 | print(arr[i][jFlag],end= " ")
9 | i+=1
10 | jFlag+=1
11 | print()
12 | j+=1
13 |
14 | traceDiagonally([[3,9,2,1],[0,6,8,-3],[0,0,5,2],[0,0,0,0]])
15 |
--------------------------------------------------------------------------------
/2021-2025/01-05-2023/Permute.py:
--------------------------------------------------------------------------------
1 | def permute(arr):
2 | if len(arr) == 1:
3 | return [arr]
4 | ans = []
5 | for i in range(len(arr)):
6 | fe = arr[i]
7 | subArr = arr[0:i]+arr[i+1:]
8 | _all = permute(subArr)
9 | for v in _all:
10 | ans.append([fe]+v)
11 | return ans
12 |
13 | ans = permute([3,2,8])
14 | print(ans)
--------------------------------------------------------------------------------
/2021-2025/02-05-2024/MultiSolver.py:
--------------------------------------------------------------------------------
1 | def traceDiagonally(_str):
2 | n = len(_str)
3 | dp = [[0 for i in range(n)] for j in range(n)]
4 | i,j = 0,0
5 | while j< n:
6 | i = 0
7 | jFlag = j
8 | while jFlag < n:
9 | if i == jFlag:
10 | dp[i][jFlag] = 1
11 | elif abs(i-jFlag) <= 2:
12 | if _str[i] == _str[jFlag]:
13 | dp[i][jFlag] = 1
14 | else:
15 | if _str[i] == _str[jFlag] and dp[i+1][jFlag-1] ==1:
16 | dp[i][jFlag] = 1
17 | i+=1
18 | jFlag+=1
19 | j+=1
20 | return dp
21 | _str = "malyalam"
22 | dp = traceDiagonally(_str)
23 | for row in dp:
24 | for v in row:
25 | print(v,end=" ")
26 | print()
--------------------------------------------------------------------------------
/2021-2025/02-05-2024/RevString.py:
--------------------------------------------------------------------------------
1 | def reverse(_str):
2 | stack = []
3 | ans = ""
4 | for i in range(len(_str)):
5 | stack.append(_str[i])
6 | for i in range(len(_str)):
7 | ans+=stack.pop()
8 | return ans
9 | _str = "sudhanshu"
10 | ans = reverse(_str)
11 | print(ans)
--------------------------------------------------------------------------------
/2021-2025/02-05-2024/Stack.py:
--------------------------------------------------------------------------------
1 | stack = []
2 |
3 | # append() method is the push for stack
4 |
5 | stack.append(19)
6 | stack.append(34)
7 | stack.append(67)
8 | print(stack)
9 | poppedElement = stack.pop()
10 | print(poppedElement,"popped element")
11 | print(stack)
12 | print(stack[-1],"top pf stack")
13 | print(len(stack),"size")
--------------------------------------------------------------------------------
/2021-2025/02-05-2024/ValidPara.py:
--------------------------------------------------------------------------------
1 | def isValid(_str):
2 | stack=[]
3 | for i in range(len(_str)):
4 | if _str[i] == '(':
5 | stack.append("(")
6 | elif _str[i] == ')' and len(stack) == 0:
7 | return False
8 | else: stack.pop()
9 | return len(stack) == 0
--------------------------------------------------------------------------------
/2021-2025/03-04-2024/MissingNumber.py:
--------------------------------------------------------------------------------
1 | def main():
2 | n = 8
3 | arr = [2,1,4,3,6,8,5]
4 | ans = 0
5 | for i in range(1,n+1): ans = ans^i
6 | for i in range(n-1): ans = ans^arr[i]
7 | print(ans)
8 | main()
--------------------------------------------------------------------------------
/2021-2025/04-04-2024/TwoUnique.py:
--------------------------------------------------------------------------------
1 | def getFirstSetBitPos(num):
2 | if num == 0 : return -1
3 | ans = 1
4 | while num%2 != 1:
5 | num = num>>1
6 | ans+=1
7 | return ans
8 | def checkIthBit(num, i):
9 | return (num>>(i-1))%2 == 1
10 | def getBothUniqueNumber(arr):
11 | ans1, ans2 = 0,0
12 | wholeXor = 0
13 | for e in arr: wholeXor = wholeXor^e
14 | pos = getFirstSetBitPos(wholeXor)
15 | for e in arr:
16 | if checkIthBit(e,pos) == True:
17 | ans1 = ans1^e
18 | else:
19 | ans2 = ans2^e
20 | return ans1,ans2
21 |
22 | def main():
23 | arr = [1,1,3,2,3,4,7,7,8,2]
24 | print(getBothUniqueNumber(arr))
25 | main()
26 |
--------------------------------------------------------------------------------
/2021-2025/10-04-2024/PrefixSum.py:
--------------------------------------------------------------------------------
1 | def getAllQueryAns(arr,query):
2 | ps = [0 for i in range(len(arr))]
3 | for i in range(len(arr)):
4 | if i == 0:
5 | ps[i] = arr[i]
6 | else:
7 | ps[i] = ps[i-1]+arr[i]
8 | for q in query:
9 | si,ei = q[0],q[1]
10 | if si == 0: print(ps[ei])
11 | else: print(ps[ei]-ps[si-1])
12 |
13 | def main():
14 | arr = [2,3,1,-5,-3,2,4,-5]
15 | query = [[0,4],[2,5],[1,6]]
16 | ans = getAllQueryAns(arr,query)
17 | print(ans)
18 | main()
--------------------------------------------------------------------------------
/2021-2025/10-04-2024/TwoPointer.py:
--------------------------------------------------------------------------------
1 | def isPairExist(a,t):
2 | a.sort()
3 | i,j = 0, len(a)-1
4 | while i target: j-=1
7 | if a[i]+a[j] < target: i+=1
8 | return False
9 |
10 |
11 | def main():
12 | arr = [6,6,1,-3,9,-3,-23,4,-56,9,13,24,35]
13 | target = 6
14 | ans = isPairExist(arr,target)
15 | print(ans)
16 | main()
--------------------------------------------------------------------------------
/2021-2025/18-04-2024/KadanesAlgo.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-3,-2,5,-6,8,9,2,-1,-6]
3 | ans = float("-inf")
4 | cts = 0
5 | for i in range(len(arr)):
6 | cts+=arr[i]
7 | ans = max(ans,cts)
8 | if cts < 0:
9 | cts = 0
10 | print(ans)
--------------------------------------------------------------------------------
/2021-2025/18-04-2024/PrefixSum.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-1,3,-2,5,6,-1,8,-3]
3 | queries = [[0,4],[1,6],[3,7],[0,4],[1,4]]
4 | ps = [0 for i in range(len(arr))]
5 | for i in range(len(arr)):
6 | if i == 0:
7 | ps[i] = arr[i]
8 | else:
9 | ps[i] = ps[i-1]+arr[i]
10 | for q in queries:
11 | si,ei = q[0],q[1]
12 | if si == 0: print(ps[ei])
13 | else:
14 | print(ps[ei]-ps[si-1])
15 | main()
16 |
--------------------------------------------------------------------------------
/2021-2025/18-04-2024/SlidingWindow.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-1,2,4,-2,4,2,-6,7,-8,3]
3 | ws = 4
4 | ans = float("-inf")
5 | ps = 0
6 | i,j = 0, ws-1
7 | si, ei = 0, ws-1
8 | while j < len(arr):
9 | if i == 0:
10 | cs = sum(arr[i:j+1])
11 | ans = cs
12 | ps = cs
13 | else:
14 | cs = ps - arr[i-1]+arr[j]
15 | ps = cs
16 | if cs > ans:
17 | si = i
18 | ei = j
19 | ans = cs
20 | i+=1
21 | j+=1
22 | print(ans,si,ei)
23 | main()
24 |
--------------------------------------------------------------------------------
/2021-2025/24-04-2024/Fibonaci.py:
--------------------------------------------------------------------------------
1 | import time
2 | def getNthNumber(n):
3 | if n == 1: return 0
4 | if n == 2: return 1
5 | return getNthNumber(n-1)+getNthNumber(n-2)
6 |
7 | n = 5
8 | dp = [-1 for i in range(n+1)]
9 | _sum = 0
10 | startTime = time.time()
11 | for i in range(1,n+1):
12 | if dp[i] != -1:
13 | _sum+=dp[i]
14 | else:
15 | nthNumber = getNthNumber(i)
16 | dp[i] = nthNumber
17 | _sum+=nthNumber
18 | print(_sum)
19 | endTime = time.time()
20 | print("total time taken = ", endTime-startTime)
21 |
--------------------------------------------------------------------------------
/2021-2025/25-04-2024/IsPalindrome.py:
--------------------------------------------------------------------------------
1 | def isPalindrome(_str):
2 | i ,j = 0, len(_str)-1
3 | while i",des)
6 | toh(n-1,aux,des,src)
7 |
8 | toh(4,'A','C','B')
--------------------------------------------------------------------------------
/21-04-23/exception.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | # print(1/0)
4 |
5 |
6 | #arr = [1,2,3]
7 | #print(arr[9])
8 |
9 |
10 |
11 |
12 | try:
13 | x = 23/10
14 | except:
15 | print("excetion occured")
16 |
17 |
18 |
19 | try:
20 | x = 1/2
21 | except ZeroDivisionError:
22 | print("zero divisio error occured")
23 |
24 |
25 |
26 |
27 | try:
28 | x = 1/52
29 | except EOFError:
30 | print("end of file occured")
31 | except ImportError:
32 | print("import error exception occured")
33 | except RuntimeError:
34 | print("zero didision error occured")
35 | else:
36 | x = 20
37 | #print("control is inside else")
38 | #else will be execeuted after try when there is no exception occured
39 |
40 |
41 | #This is a dummy comment
42 |
43 |
44 | try:
45 | x = 1/8
46 | except ZeroDivisionError as err:
47 | print(err)
48 |
49 |
50 | #this is a dummy comment
51 |
52 |
53 |
54 | try:
55 | x = 1/80
56 | except ZeroDivisionError as err:
57 | print(err)
58 | finally:
59 | print("finally will always gets executed")
60 | #finnalyy block will always gets executed
61 |
62 |
63 | #this is a dummy coment
64 |
65 |
66 |
67 | arr = [1,2,3]
68 |
69 | try:
70 | if len(arr) >=4:
71 | raise ValueError("array length is greater or equal to 4")
72 | else:
73 | print("everything is fine")
74 | except ValueError as err:
75 | print(err)
76 |
77 |
78 | #how to define custom exceptions in python
79 |
80 |
81 |
82 | class CustomException(Exception):
83 | "This is a custom exeption"
84 | pass
85 |
86 | try:
87 | x = 20
88 | if x==20:
89 | raise CustomException
90 | else:
91 | print("x is not 20")
92 | except CustomException as err:
93 | print("exception occured")
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 | #this is a dummy comment
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 | #this is a dummy comment
124 |
--------------------------------------------------------------------------------
/21-04-23/index.py:
--------------------------------------------------------------------------------
1 | arr = [1,2,3,4,5]
2 |
3 | # print(type(arr))
4 |
5 |
6 | from array import *
7 |
8 |
9 | arr = array('i',[10,20,30])
10 |
11 | # print(type(arr))
12 | list1 = [1,2,3,45,5]
13 | # print(list1)
14 |
15 | list1.append('a')
16 | # print(list1)
17 |
18 | # list1.clear()
19 | # print(list1)
20 |
21 | copied_list = list1.copy()
22 | print(copied_list)
23 |
24 | print(list1.count('a'))
25 | print(list1.count(122))
26 |
27 |
28 | print(list1.pop()) # pop method will remove the last element of list
29 | print(list1.pop())
30 | print(list1)
31 |
32 | print(list1.pop(0))
33 | print(list1)
34 |
35 |
36 |
37 | list2 = [2,2,10,23,43]
38 | print(list2)
39 | list2.reverse()
40 | print(list2)
41 |
42 |
43 | list2.sort() # sort the list in increasing order
44 | print(list2 , "this is the list after sorting")
45 |
46 |
47 | list2.sort(reverse = True)
48 | print(list2)
49 |
50 |
51 | list3 = [1,2,2,3,4,5]
52 | list3.remove(2)
53 | print(list3)
54 |
--------------------------------------------------------------------------------
/24-04-23/index.py:
--------------------------------------------------------------------------------
1 |
2 | def add():
3 | try:
4 | a = int(input())
5 | except ValueError as err:
6 | print(err)
7 | try:
8 | b = int(input())
9 | except ValueError as err:
10 | print(err)
11 | print(a+b)
12 |
13 |
14 | #add()
15 |
16 | def addNumbers():
17 | a = 10
18 | b = 20
19 | return (a+b)
20 |
21 |
22 | sum = addNumbers()
23 | #print(sum)
24 |
25 |
26 | def addNumber(a,b):
27 | return a+b
28 |
29 |
30 | sum = addNumber(10,30)
31 |
32 |
33 |
34 | def returningMultipleValues():
35 | return 10,20,30
36 |
37 | output = returningMultipleValues()
38 | #print(output)
39 |
40 |
41 |
42 |
43 | def printFibonaciSequence(n):
44 | if n<=0:
45 | print("invalid argument")
46 | return -1
47 | if n==1:
48 | print(0)
49 | return -1
50 | if n==2:
51 | print(0," ",1)
52 | return -1
53 | a = 0
54 | b = 1
55 | print(a," ",b)
56 | count = 3
57 | while count <=n:
58 | next = a+b
59 | print(next , end = " ")
60 | a = b
61 | b= next
62 | count+=1
63 | #printFibonaciSequence(10)
64 |
65 |
66 | def findLcm(a,b):
67 | if a>b:
68 | greater = a
69 | else:
70 | greater = b
71 |
72 | while True:
73 | if((greater % a == 0) and (greater%b) == 0):
74 | lcm = greater
75 | break
76 | greater+=1
77 | return lcm
78 |
79 | #print(findLcm(18,20))
80 |
81 |
82 |
83 |
84 |
85 | def doJob(n):
86 | if n<=2:
87 | return
88 | print(n)
89 | doJob(n-1)
90 | print(n)
91 |
92 |
93 | #doJob(10)
94 |
95 |
96 |
97 | def doJob2(n):
98 | if n<=5:
99 | return
100 | doJob2(n-1)
101 | print(n,end=" ")
102 | doJob2(n-1)
103 | print(n,end=" ")
104 | #doJob2(8)
105 |
106 |
107 |
108 | def printSteps(source,helper,destination,n):
109 | if n<=0:
110 | return
111 | print(source,"to",helper)
112 | printSteps(source,)
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 | #this is a dummy comment
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 | #This is a dummy comment
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 | #This is a dummy comment
172 |
--------------------------------------------------------------------------------
/25-04-23/index.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def nthFibonaciNumber(n):
5 | if n<=0:
6 | return -1
7 | if n == 1:
8 | return 0
9 | if n == 2:
10 | return 1
11 |
12 | return nthFibonaciNumber(n-1)+nthFibonaciNumber(n-2)
13 |
14 | #print(nthFibonaciNumber(10))
15 |
16 |
17 |
18 |
19 |
20 | def sumOfNFibonaciNumber(n):
21 | if n<=0:
22 | return -1
23 | if n == 1:
24 | return 0
25 | if n==2:
26 | return 1
27 | first , second = 0 , 1
28 | result = first + second
29 | for i in range(0,n-2):
30 | next = first + second
31 | result+=next
32 | first = second
33 | second = next
34 | print(result)
35 |
36 | #sumOfNFibonaciNumber(10)
37 |
38 |
39 |
40 | arr = [1,2,1,2,1,2,3,4,5,3,4,5,6,7]
41 | my_set = set(arr)
42 |
43 | #for ele in my_set:
44 | #print(ele,end=" ")
45 |
46 |
47 | my_set.add(34) # add 34 to the my_set
48 |
49 | my_set.clear() # clear all the values of my_set
50 |
51 | my_set.copy() # return a copy of set
52 |
53 |
54 | # This is a dictionary
55 |
56 |
57 | my_dict = {
58 | "name":"sudhanshu",
59 | "age":24,
60 | "Occupation":"Developer"
61 | }
62 |
63 |
64 | #print(type(my_dict))
65 | #print(my_dict["name"])
66 | my_dict["name"] = "sudhanshu kumar"
67 | #print(my_dict["name"])
68 |
69 | updated_name = {
70 | "name":"Twenkel sen"
71 | }
72 | my_dict.update(updated_name)
73 | print(my_dict["name"])
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | #This is a dummy comment
85 |
86 | class Car:
87 | engineType = "strongest Engine"
88 | numberOfTyers = 4
89 | numberOfWindow = 6
90 | isFridgeAValble = True
91 |
92 |
93 | def getNumberOfWindows(self):
94 | return self.numberOfWindow
95 |
96 | def getNumberOfTyres(self):
97 | return self.numberOfTyers
98 |
99 | car1 = Car()
100 | print(car1.getNumberOfWindows())
101 | print(car1.getNumberOfTyres())
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 | #This is a dummy comment
119 |
--------------------------------------------------------------------------------
/26-04-23/index.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | class Book:
6 | numberOfPages = 145
7 | author = "sudhanshu"
8 | scope = "To be sold in india"
9 |
10 | def __init__(self , zone , dob):
11 | self.zone = zone
12 | self.dob = dob
13 | def __del__(self):
14 | print("destructor is called")
15 |
16 | #my_book = Book("Mystery","25-10-1998")
17 | #print(my_book.zone)
18 | #print(my_book.dob)
19 | #del my_book
20 | #_------------------------------------------------------------_#
21 |
22 | # OOPS PILLARS
23 | class School:
24 | name = "RJSIS"
25 | age = 34
26 | #def __init__(self , age):
27 | #self.age = age
28 | def getAge(self):
29 | return self.age
30 | class SubSchool(School):
31 | def __init__(self):
32 | print("child constructor")
33 | def getParentName(self):
34 | return "RJSIS"
35 | def getName(self):
36 | return "Gyan Sagar"
37 |
38 | #my_school = SubSchool()
39 | #print(my_school.getParentName())
40 | #print(my_school.getName())
41 | #print(my_school.getAge())
42 |
43 | class Parent1:
44 | def getName(self):
45 | return "parent1"
46 | class Parent2:
47 | def defName():
48 | return "Parent2"
49 | class Parent3:
50 | def getName():
51 | return "Parent 3"
52 |
53 | class Child(Parent1 , Parent2 , Parent3):
54 | def __init__(self):
55 | self.getAllParent()
56 | def getAllParent(self):
57 | print("trying to get all parents of this class")
58 | parent_list = []
59 | for base in Child.__bases__:
60 | parent_list.append(base)
61 | print(parent_list)
62 | #my_child = Child()
63 | #parent_list = []
64 | #print(my_child.__bases__)
65 | #for base in Child.__bases__:
66 | #print(base,end=" ")
67 |
68 | #print(my_child.getName())
69 |
70 |
71 | #print("sudhanshu","Kumar","nityanand","singh")
72 | #print("sudhansu")
73 |
74 |
75 | def addNumbers(a,b):
76 | print(a+b)
77 |
78 | def addNumbers2(*args):
79 | sum = 0
80 | for value in args:
81 | sum+=value
82 | print(sum)
83 |
84 | #addNumbers2(10)
85 | #addNumbers2(10,20)
86 |
87 | #addNumbers2(10,20)
88 | #addNumbers2(10,20,30)
89 |
90 |
91 | # def addNumbers3(arg1 , arg2 , *arg3):
92 | # print(arg1,arg2,arg3)
93 |
94 | #addNumbers3(10,20,30)
95 | #addNumbers3(10,20,30,40,50,60)
96 |
97 |
98 | def addNumbers(a,b,c=2):
99 | print(a+b+c)
100 |
101 | #addNumbers(10,20)
102 | #addNumbers(10,20,30)
103 |
104 |
105 | #def doJob(agr1,agr2,agr3):
106 | print("sudhanshu")
107 |
108 | #def doJob(arg1):
109 | #print("sudhanshu kumar nityanand singh")
110 |
111 | #doJob(10)
112 | #oJob(10,20,30)
113 |
114 | class Animal:
115 | def printSomething(self):
116 | print("Animals are good by nature")
117 | def canFly(self,name):
118 | if(name == "tarak"):
119 | print("animal tarak can fly")
120 | else:
121 | print("no animals can fly")
122 | class Dog(Animal):
123 | def canFly(self):
124 | print("dogs can not fly")
125 | class Tarak(Animal):
126 | def canFly(self):
127 | print("tarak can fly")
128 | #my_tarak.canFly()
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 | # This is a dummy comment
145 |
--------------------------------------------------------------------------------
/26-04-23/library_management.py:
--------------------------------------------------------------------------------
1 | class Library:
2 | book = ["The fault in our stars" , "Abang" , "Citadel"]
3 | author_book = {
4 | "Pablo":["escobar","escobar returns","escobar part 3"]
5 | }
6 | def getAllBooks():
7 | pass
8 | def addBook():
9 | pass
10 | def getBookByAuthorName(authorName):
11 | for key in author_book:
12 | if key == authorName:
13 | print(author_book[key])
14 |
15 |
16 | def sortBooksInTopologicalOrder(self):
17 | book_copy = []
18 | for books in self.book:
19 | book_copy.append(books)
20 |
21 | return book_copy.sort()
22 |
23 | def getAllSubscribers():
24 | pass
25 | def getAllEarnings():
26 | pass
27 | def getUnavailableBooks():
28 | pass
29 | def mapAuthorWithABook():
30 | pass
31 | class MyLibrary(Library):
32 | # it can not have it's own data structure to store book , authors , subscribers , unvailable books
33 | def getFaviourtBook():
34 | pass
35 | def getFaviourtCustomer():
36 |
--------------------------------------------------------------------------------
/NITB1/15-07-2024/BitManipulation.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getFirstSetBitPosition(n):
4 | ans = 1
5 | while n%2 != 1:
6 | n = n>>1
7 | ans+=1
8 | return ans
9 |
10 | def getIthBit(n,i):
11 | return int((n>>(i-1))% 2 == 1)
12 |
13 | def main():
14 | n = int(input())
15 | i = int(input())
16 | #ans = getFirstSetBitPosition(n)
17 | ans = getIthBit(n,i)
18 | print(ans)
19 |
20 | main()
--------------------------------------------------------------------------------
/NITB1/15-07-2024/MissingNumber.py:
--------------------------------------------------------------------------------
1 |
2 | def getMissingNumber(n,arr):
3 | ans = 0
4 | for i in range(1,n+1):
5 | ans = ans^i
6 | for e in arr : ans = ans^e
7 |
8 | return ans
9 |
10 |
11 | def main():
12 | n = 10
13 | arr = [3,2,4,8,9,10,1,5,8,7]
14 |
15 | ans = getMissingNumber(n,arr)
16 | print(ans)
--------------------------------------------------------------------------------
/NITB1/15-07-2024/TwoUnique.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getFirstSetBitPosition(n):
4 | if n == 0:
5 | return -1
6 | ans = 1
7 | while n%2 != 1:
8 | n = n>>1
9 | ans+=1
10 | return ans
11 |
12 | def getIthBit(n,i):
13 | return int((n>>(i-1))% 2 == 1)
14 |
15 | def main():
16 | arr = [2,4,2,67,67,8,4,3,3,17]
17 | wholeXor = 0
18 | for e in arr : wholeXor = wholeXor^e
19 | firstPos = getFirstSetBitPosition(wholeXor)
20 | ans1 , ans2 = 0, 0
21 | for i in range(len(arr)):
22 | e = arr[i]
23 | if getIthBit(e,firstPos) == 1:
24 | ans1 = ans1^e
25 | else:
26 | ans2 = ans2^e
27 | print(ans1,ans2)
28 |
29 |
30 | main()
--------------------------------------------------------------------------------
/NITB1/16-07-2024/AsPowerOfTwo.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def writeAsPowerOfTwo(n):
4 | if n < 0 :
5 | return
6 | powerOfTwo = []
7 | exponent = 0
8 |
9 | while n > 0:
10 | if n&1 == True:
11 | powerOfTwo.append(2**exponent)
12 | exponent+=1
13 | n = n>>1
14 | print(powerOfTwo)
15 |
16 |
17 |
18 | def main():
19 | n = 28
20 | writeAsPowerOfTwo(n)
21 |
22 | main()
--------------------------------------------------------------------------------
/NITB1/16-07-2024/MinimumOps.py:
--------------------------------------------------------------------------------
1 |
2 | def getMinimumNumberOfOps(arr):
3 | wholeXor = 0
4 | for e in arr : wholeXor = wholeXor ^ e
5 | ans = float('+inf')
6 | for e in arr:
7 | wholeXorExceptE = wholeXor ^ e
8 | if wholeXorExceptE > e:
9 | continue
10 | else:
11 | currAns = e-wholeXorExceptE
12 | if currAns < ans:
13 | ans = currAns
14 | if ans == float("+inf"):
15 | return -1
16 | return ans
17 |
18 |
19 |
20 | def main():
21 | arr = [3,9,8,17,12]
22 | ans = getMinimumNumberOfOps(arr)
23 | print(ans)
24 | main()
--------------------------------------------------------------------------------
/NITB1/18-07-2024/BinarySearch.py:
--------------------------------------------------------------------------------
1 |
2 | def binarySearch(ele,arr):
3 | i,j = 0, len(arr)-1
4 | while i ele: j = mid-1
8 | if arr[mid] < ele: i = mid+1
9 | return False
10 |
11 | def main():
12 | arr = [3,2,6,7,8,9,12,14,56,-78,-98]
13 | queries = [3,3,7,8,2,56,76,876,984,12,34]
14 | arr.sort()
15 | for e in queries:
16 | print(binarySearch(e,arr),end=" ")
17 | main()
--------------------------------------------------------------------------------
/NITB1/18-07-2024/DistinctWindowSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def getMaximumSubarraySumWithDistinceElement(arr,k):
5 | i = 0
6 | j = k-1
7 | ans = float("-inf")
8 | ps = 0
9 | _map = {}
10 | while j < len(arr):
11 | cs = 0
12 | if i == 0:
13 | cs = 0
14 | for k1 in range(i,j+1):
15 | cs+=arr[k1]
16 | if arr[k1] in _map:
17 | value = _map[arr[k1]]
18 | value+=1
19 | _map[arr[k1]] = value
20 | else:
21 | _map[arr[k1]] = 1
22 | ps = cs
23 | else:
24 | key = arr[i-1]
25 | if _map[key] == 1:
26 | del _map[arr[i-1]]
27 | else:
28 | _map[key] = _map[key]-1
29 | if arr[j] in _map:
30 | _map[arr[j]]+=1
31 | else:
32 | _map[arr[j]] = 1
33 | cs = ps-arr[i-1]+arr[j]
34 | ps = cs
35 | i+=1
36 | j+=1
37 | if len(_map) == k and cs>ans:
38 | ans = cs
39 |
40 | return ans
41 |
42 |
43 |
44 | def main():
45 | arr = [2,2,-3,9,9,-3,9,-2,4,6,-5,9]
46 | k = 3
47 | ans = getMaximumSubarraySumWithDistinceElement(arr,k)
48 | print(ans)
49 | main()
--------------------------------------------------------------------------------
/NITB1/18-07-2024/Divide.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getResult(dividend,divisor):
4 | if dividend == divisor:
5 | return 1
6 | sign = 1
7 | if dividend > 0 and divisor < 0:
8 | sign = -1
9 | if divisor > 0 and dividend < 0:
10 | sign = -1
11 | n = abs(dividend)
12 | d = abs(divisor)
13 | quotient = 0
14 | while n >= d:
15 | count = 0
16 | while n >= d<<(count+1):
17 | count+=1
18 | n = n - (d< target: j-=1
7 | if arr[i]+arr[j] < target: i+=1
8 | return False
9 |
10 | def main():
11 | arr = [3,-2,5,6,9,13,5,-12,8]
12 | target = 1400
13 | ans = isPairExist(arr,target)
14 | print(ans)
15 | main()
--------------------------------------------------------------------------------
/NITB1/19-07-2024/Diagonal.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def buildMatrix(_str,dp):
4 | si,ei = 0,0
5 | n = len(dp)
6 | count = 0
7 | k = 3
8 | kCount = 0
9 | largest = ""
10 | smallest = ""
11 | while ei < n:
12 | ce = ei
13 | while ce < n:
14 | if si == ce:
15 | dp[si][ce] = 1
16 | count+=1
17 | largest = _str[si:ce+1]
18 | if abs(si-ce) == k-1:
19 | kCount+=1
20 | elif abs(ce-si) <= 2:
21 | if _str[si] == _str[ce]:
22 | dp[si][ce] = 1
23 | count+=1
24 | largest = _str[si:ce+1]
25 | if smallest == "":
26 | smallest = _str[si:ce+1]
27 | if abs(si-ce) == k-1:
28 | kCount+=1
29 | else:
30 | if _str[si] == _str[ce] and dp[si+1][ce-1] == 1:
31 | dp[si][ce] = 1
32 | count+=1
33 | largest = _str[si:ce+1]
34 | if smallest == "":
35 | smallest = _str[si:ce+1]
36 | if abs(si-ce) == k-1:
37 | kCount+=1
38 |
39 | si+=1
40 | ce+=1
41 | si = 0
42 | ei+=1
43 | return [dp,count,largest,smallest,kCount]
44 |
45 | def main():
46 | _str = "abcdcbcbaudbz"
47 | n = len(_str)
48 | dp = [[0 for i in range(n)] for j in range(n)]
49 | ans = buildMatrix(_str,dp)
50 | dp = ans[0]
51 | totalNumberOfPalindromicSubstring = ans[1]
52 | largest = ans[2]
53 | smallest = ans[3]
54 | kCount = ans[4]
55 | print(totalNumberOfPalindromicSubstring)
56 | print(largest)
57 | print(smallest)
58 | print(kCount)
59 | main()
--------------------------------------------------------------------------------
/NITB1/19-07-2024/PrefixSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | def main():
7 | arr = [-3,2,9,8,-3,5,2,1]
8 | n = len(arr)
9 | queries = [[5,7],[2,7],[1,6],[3,7],[0,4]]
10 | prefixSum = [0 for i in range(n)]
11 | for i in range(n):
12 | if i == 0: prefixSum[i] = arr[i]
13 | else: prefixSum[i] = prefixSum[i-1]+arr[i]
14 | for query in queries:
15 | si = query[0]
16 | ei = query[1]
17 |
18 | if si == 0:
19 | print(prefixSum[ei],end= " ")
20 | else:
21 | print(prefixSum[ei]-prefixSum[si-1],end=" ")
22 |
23 | main()
24 |
--------------------------------------------------------------------------------
/NITB1/20-07-2024/ClimbSatirs.py:
--------------------------------------------------------------------------------
1 | def findNuberOfWaysToClimbStairs(n,dp):
2 | if dp[n] != 0:
3 | return dp[n]
4 | if n<=3:
5 | return n
6 | ans1 = findNuberOfWaysToClimbStairs(n-1,dp)
7 | dp[n-1] = ans1
8 | ans2 = findNuberOfWaysToClimbStairs(n-2,dp)
9 | dp[n-2] = ans2
10 | return ans1+ans2
11 |
12 | def main():
13 | n = 50
14 | dp = [0 for i in range(n+1)]
15 | ans = findNuberOfWaysToClimbStairs(n,dp)
16 | print(ans)
17 | main()
--------------------------------------------------------------------------------
/NITB1/20-07-2024/MergeSortedArray.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def mergeArrays(arr1,arr2):
4 | n1 = len(arr1)
5 | n2 = len(arr2)
6 | arr3 = [0 for i in range(len(arr1)+len(arr2))]
7 | i,j,k = 0,0,0
8 |
9 | while i< len(arr1) and j 0:
11 | arr[i] = st.pop()
12 | i+=1
13 | while len(queue) > 0:
14 | arr[i] = queue.pop(0)
15 | i+=1
16 | return arr
17 |
18 |
19 |
20 |
21 | def main():
22 | arr = [2,3,4,8,9,12,5]
23 | pi = 3
24 | arr = rotateArr(arr,3)
25 | print(arr)
26 | main()
--------------------------------------------------------------------------------
/NITB1/20-07-2024/Spiral.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def printSpiral(arr):
4 | turn = 1
5 | count = 0
6 | n = len(arr)
7 | totalPrint = len(arr)*len(arr[0])
8 | fdri,fdcsi,fdcei = 0,0,n-1
9 | sdci,sdrsi,sdrei = n-1,1,n-1
10 | tdri, tdcsi, tdcei = n-1, n-2, 0
11 | fdci, fdrsi,fdrei = 0, n-2, 1
12 | while count < totalPrint:
13 | if turn == 1:
14 | #print("first")
15 | for i in range(fdcsi,fdcei+1):
16 | print(arr[fdri][i],end=" ")
17 | count+=1
18 | fdri+=1
19 | fdcsi+=1
20 | fdcei-=1
21 | turn = 2
22 | elif turn == 2:
23 | #print("second")
24 | for i in range(sdrsi,sdrei+1):
25 | print(arr[i][sdci],end=" ")
26 | count+=1
27 | sdci-=1
28 | sdrsi+=1
29 | sdrei-=1
30 | turn = 3
31 | elif turn == 3:
32 | #print("third")
33 | for i in range(tdcsi,tdcei-1,-1):
34 | print(arr[tdri][i],end=" ")
35 | count+=1
36 | tdri-=1
37 | tdcsi-=1
38 | tdcei+=1
39 | turn = 4
40 | else:
41 | #print("fourth")
42 | for i in range(fdrsi,fdrei-1,-1):
43 | print(arr[i][fdci],end=" ")
44 | count+=1
45 | fdci+=1
46 | fdrsi-=1
47 | fdrei+=1
48 | turn = 1
49 |
50 | def main():
51 | arr = [[8,-3,9,2],[9,3,2,8],[1,10,11,15],[8,9,15,14]]
52 | printSpiral(arr)
53 |
54 | main()
--------------------------------------------------------------------------------
/NITB1/20-07-2024/SubSequence.py:
--------------------------------------------------------------------------------
1 |
2 | def printAllSubsequence(arr,index,ans):
3 | if len(arr) == index:
4 | print(ans)
5 | return
6 | printAllSubsequence(arr,index+1,ans)
7 | printAllSubsequence(arr,index+1,ans+[arr[index]])
8 |
9 |
10 | def main():
11 | arr = [1,2,3]
12 | printAllSubsequence(arr,0,[])
13 |
14 | main()
--------------------------------------------------------------------------------
/NITB1/22-07-2024/IsValid.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def isValid(s):
5 | st = []
6 | for i in range(len(s)):
7 | if s[i] == '(' or s[i] == '{' or s[i] == '[':
8 | st.append(s[i])
9 | elif s[i] == ')' and st[-1] != '(': return False
10 | elif s[i] == '}' and st[-1] != '{' : return False
11 | elif s[i] == ']' and st[-1] != '[' : return False
12 | else:
13 | st.pop()
14 |
15 | return len(st) == 0
16 |
17 |
18 |
19 |
20 |
21 | def main():
22 | _str = "(((({}[] ())))"
23 | ans = isValid(_str)
24 | print(ans)
25 |
26 | main()
--------------------------------------------------------------------------------
/NITB1/22-07-2024/Toh.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def toh(n,src,des,aux):
4 | if n <= 0:
5 | return
6 | toh(n-1,src,aux,des)
7 | print("Move ",src," ",des)
8 | toh(n-1,aux,des,src)
9 |
10 |
11 |
12 |
13 |
14 | def main():
15 | n = 3
16 | src,des,aux = 'A','C','B'
17 | toh(n,src,des,aux)
18 |
19 | main()
--------------------------------------------------------------------------------
/NITB1/23-07-2024/LinkedList.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Node:
4 | def __init__(self,val):
5 | self.val = val
6 | self.next = None
7 | class LinkedList:
8 | def createList(self,arr):
9 | head = None
10 | temp = None
11 | for i in range(len(arr)):
12 | if i == 0:
13 | head = Node(arr[i])
14 | temp = head
15 | else:
16 | temp.next = Node(arr[i])
17 | temp = temp.next
18 | return head
19 |
20 | def printList(self,head):
21 | while head != None:
22 | print(head.val,end=" ")
23 | head = head.next
24 |
25 | def deleteValue(self,head, value):
26 | while head.val == value:
27 | head = head.next
28 | print(head.val)
29 | temp = head
30 | while temp.next != None and temp != None:
31 | if temp.next.val == value:
32 | temp.next = temp.next.next
33 | else:
34 | temp = temp.next
35 |
36 | return head
37 |
38 |
39 |
40 | def main():
41 | arr = [12,12,12,12,12,4,6,7,-43,56,12,12,90,-78,12]
42 | myListOperator = LinkedList()
43 | head = myListOperator.createList(arr)
44 | myListOperator.printList(head)
45 | print()
46 | head = myListOperator.deleteValue(head,12)
47 | myListOperator.printList(head)
48 |
49 | main()
50 |
--------------------------------------------------------------------------------
/NITB1/23-07-2024/NQueen.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def nQueen(n,board,row,diag,revDiag,col,csf):
5 | if row == n:
6 | print(csf)
7 | return
8 | for i in range(n):
9 | if col[i] == 0 and diag[n+row-i] == 0 and revDiag[row+i] == 0:
10 | col[i] = 1
11 | diag[n+row-i] = 1
12 | revDiag[row+i] = 1
13 | nQueen(n,board,row+1,diag,revDiag,col,csf+str(row)+str(i)+"->")
14 | col[i] = 0
15 | diag[n+row-i] = 0
16 | revDiag[row+i] = 0
17 |
18 |
19 |
20 |
21 | def main():
22 | n = 4
23 | board = [[0 for i in range(n)] for j in range(n)]
24 | col = [0 for i in range(n)]
25 | revDiag = [0 for i in range(2*n-1)]
26 | diag = [0 for i in range(2*n-1)]
27 | nQueen(n,board,0,diag,revDiag,col,"")
28 |
29 | main()
--------------------------------------------------------------------------------
/NITB1/24-07-2024/Graph.py:
--------------------------------------------------------------------------------
1 |
2 | largestPath = ""
3 | smallestPath = ""
4 |
5 |
6 | def buildGraph(edges,n):
7 | graph = [[0 for i in range(n)] for j in range(n)]
8 | for edge in edges:
9 | src = edge[0]
10 | des = edge[1]
11 |
12 | graph[src][des] = 1
13 | graph[des][src] = 1
14 | return graph
15 |
16 | def printGraph(graph):
17 | for row in graph:
18 | for e in row:
19 | print(e,end=" ")
20 | print()
21 |
22 |
23 | def hasPath(graph,src,des,visited):
24 | if src == des:
25 | return True
26 | nbrs = graph[src]
27 | for i in range(len(nbrs)):
28 | if nbrs[i] == 1:
29 | if visited[i] == 0:
30 | visited[i] = 1
31 | ans = hasPath(graph,i,des,visited)
32 | if ans == True:
33 | return True
34 | return False
35 |
36 | def printAllPath(graph,src,des,visited,psf):
37 | global largestPath
38 | global smallestPath
39 | if src == des:
40 | if len(psf) > len(largestPath):
41 | largestPath = psf
42 | if smallestPath == "" or len(psf) < len(smallestPath):
43 | smallestPath = psf
44 | #print(psf)
45 | return
46 | nbrs = graph[src]
47 | for i in range(len(nbrs)):
48 | if nbrs[i] == 1:
49 | if visited[i] == 0:
50 | visited[i] = 1
51 | printAllPath(graph,i,des,visited,
52 | str(src)+"->"+str(i) if psf == "" else psf+"->"+str(i),
53 | )
54 | visited[i] = 0
55 |
56 | def buildGraphWithAdjacencyList(edges,n):
57 | graph = [[] for i in range(n)]
58 | for edge in edges:
59 | src = edge[0]
60 | des = edge[1]
61 | wt = edge[2]
62 | graph[src].append([src,des,wt])
63 | # graph[des].append([des,src,wt])
64 | return graph
65 |
66 | def printGraphInAdjacencyList(graph):
67 | for node in graph:
68 | for edges in node:
69 | print(edges ,end=" ")
70 |
71 |
72 | def hasPath(graph,src,des,visited):
73 | if src == des:
74 | return True
75 | nbrs = graph[src]
76 | for nbr in nbrs:
77 | if visited[nbr[1]] == 0:
78 | visited[nbr[1]] = 1
79 | ans = hasPath(graph,nbr[1],des,visited)
80 | if ans == True:
81 | return True
82 | return False
83 |
84 | def bfs(graph,src,visited,queue):
85 | while len(queue) > 0:
86 | popepedElement = queue.pop(0)
87 | currentNode = popepedElement[0]
88 | psf = popepedElement[1]
89 | visited[currentNode] = 1
90 | print(currentNode,"->",psf)
91 | nbrs = graph[currentNode]
92 | for i in range(len(nbrs)):
93 | if nbrs[i] == 1 and visited[i] == 0:
94 | queue.append([i,psf+str(i)])
95 |
96 | def getCurrentComponent(graph,src,visited,currentComponent):
97 | visited[src] = 1
98 | currentComponent.append(src)
99 | nbrs = graph[src]
100 | for i in range(len(nbrs)):
101 | if nbrs[i] == 1 and visited[i] == 0:
102 | getCurrentComponent(graph,i,visited,currentComponent)
103 |
104 | def getAllCompoents(graph,n):
105 | visited = [0 for i in range(n)]
106 | ans = []
107 | for i in range(n):
108 | if visited[i] == 0:
109 | visited[i] = 1
110 | currentComponent = []
111 | getCurrentComponent(graph,i,visited,currentComponent)
112 | ans.append(currentComponent)
113 | return ans
114 |
115 | def isCyclic(graph,n):
116 | sc = -1
117 | queue = []
118 | queue.append([0,"0"])
119 | visited = [0 for i in range(n)]
120 | while len(queue) > 0:
121 | popepedElement = queue.pop(0)
122 | currentNode = popepedElement[0]
123 | if visited[currentNode] == 1:
124 | print(popepedElement[1])
125 | # if sc == -1:
126 | # sc = popepedElement[1]+str(currentNode)
127 | # elif len(popepedElement[1]+str(currentNode)) < len(sc):
128 | # sc = popepedElement[1]+str(currentNode)
129 | psf = popepedElement[1]
130 | visited[currentNode] = 1
131 | #print(currentNode,"->",psf)
132 | nbrs = graph[currentNode]
133 | for i in range(len(nbrs)):
134 | if nbrs[i] == 1 and visited[i] == 0:
135 | queue.append([i,psf+str(i)])
136 |
137 | return sc
138 | def expandNode(graph,i,j,visited,n):
139 | if i>=n or i<0 or j>=n or j<0 or graph[i][j] == 0 or visited[i][j] == 1:
140 | return
141 | visited[i][j] = 1
142 |
143 | expandNode(graph,i+1,j,visited,n)
144 | expandNode(graph,i-1,j,visited,n)
145 | expandNode(graph,i,j+1,visited,n)
146 | expandNode(graph,i,j-1,visited,n)
147 |
148 |
149 |
150 |
151 | def getNumberOfIsland(graph,n):
152 | count = 0
153 | visited = [[0 for i in range(n)] for j in range(n)]
154 | for i in range(n):
155 | for j in range(n):
156 | if graph[i][j] == 1 and visited[i][j] == 0:
157 | expandNode(graph,i,j,visited,n)
158 | count+=1
159 | return count
160 |
161 |
162 |
163 | def main():
164 | global smallestPath
165 | global largestPath
166 | edges = [[0,1],[0,2],[2,1],[3,6],[3,4],[6,5],[4,5],[7,8],[9,10],[9,11],[10,11]]
167 | n = 12
168 | graph = buildGraph(edges,n)
169 | # #printGraph(graph)
170 | src = 0
171 | visited = [0 for i in range(n)]
172 | queue = [[0,"0"]]
173 | #bfs(graph,src,visited,queue)
174 | # visited[src] = 1
175 | # #ans = hasPath(graph,src,des,visited)
176 | # #print(ans)
177 | # printAllPath(graph,src,des,visited,"")
178 | # print(smallestPath)
179 | # print(largestPath)
180 | #graph = buildGraphWithAdjacencyList(edges,n)
181 | #printGraphInAdjacencyList(graph)
182 | #ans = hasPath(graph,src,des,visited)
183 | #print(ans)
184 | #ans = isCyclic(graph,n)
185 | #print(ans)
186 | matrix = [[1,1,1,0,0,1],[0,0,0,0,0,1],[0,1,1,0,0,1],[1,1,1,1,0,1],[1,0,0,1,1,0],
187 | [0,0,0,1,1,0]
188 | ]
189 | # ans = getAllCompoents(graph,n)
190 | # print(ans)
191 | ans = getNumberOfIsland(matrix,6)
192 | print(ans)
193 | main()
--------------------------------------------------------------------------------
/NITB1/26-07-2024/Tree.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Node:
4 | def __init__(self,data):
5 | self.data = data
6 | self.index = 1
7 | self.left = None
8 | self.right = None
9 |
10 | class Tree:
11 | def buildTree(self,arr):
12 | st = []
13 | node = Node(arr[0])
14 | st.append(node)
15 | i = 1
16 | while len(st) > 0 and i len(largest)):
20 | largest = _str[row:column+1]
21 | elif abs(row-column) <= 2:
22 | if _str[row] == _str[column]:
23 | dp[row][column] = 1
24 | count+=1
25 | if(abs(column-row) > len(largest)):
26 | largest = _str[row:column+1]
27 | if(abs(column-row) < smallestLength):
28 | smallestLength = abs(column-row)
29 | smallest = _str[row:column+1]
30 | else:
31 | if _str[row] == _str[column] and dp[row+1][column-1] == 1:
32 | dp[row][column] = 1
33 | count+=1
34 | if(abs(column-row) > len(largest)):
35 | largest = _str[row:column+1]
36 | if(abs(column-row) < smallestLength):
37 | smallestLength = abs(column-row)
38 | smallest = _str[row:column+1]
39 | row+=1
40 | column+=1
41 | columnIndex+=1
42 |
43 | print("total number of palindromic substring ",count)
44 | print("largest palindromic substring ",largest)
45 | print("smallest palindromic substring",smallest)
46 | return dp
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | def main():
55 | _str = "malayala"
56 | n = len(_str)
57 |
58 |
59 | dp = buildMatrix(_str)
60 | for row in dp:
61 | for val in row:
62 | print(val,end=" ")
63 | print()
64 | main()
65 |
66 |
67 |
--------------------------------------------------------------------------------
/NITB1/B2/06-08-2024/NumberOfWays.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def fnw(n,dp):
5 | if n <= 3:
6 | dp[n] = n
7 | return n
8 |
9 | if dp[n] != 0:
10 | return dp[n]
11 |
12 | ans1 = fnw(n-1,dp)
13 | dp[n-1] = ans1
14 |
15 | ans2 = fnw(n-2,dp)
16 | dp[n-2] = ans2
17 |
18 | return ans1+ans2
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | def main():
28 | n = 50
29 | dp = [0 for i in range(n+1)]
30 | ans = fnw(n,dp)
31 | print(ans)
32 |
33 | main()
--------------------------------------------------------------------------------
/NITB1/B2/06-08-2024/Permute.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def permute(arr):
4 | if len(arr) == 1:
5 | return [arr]
6 | ans = []
7 |
8 | for i in range(len(arr)):
9 | fixedElement = arr[i]
10 | subSequence = arr[0:i]+arr[i+1:]
11 | allPermutation = permute(subSequence)
12 | for per in allPermutation:
13 | per.append(fixedElement)
14 | ans.append(per)
15 |
16 | return ans
17 |
18 |
19 |
20 |
21 | def main():
22 | arr = [1,2,3]
23 | ans = permute(arr)
24 | print(ans)
25 |
26 | main()
--------------------------------------------------------------------------------
/NITB1/B2/06-08-2024/Recursion.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | def fun(n,dp):
7 | if n<=2:
8 | dp[n] = -1
9 | return -1
10 |
11 | if dp[n] != 0:
12 | return dp[n]
13 |
14 | ans1 = fun(n-2,dp)
15 | dp[n-2] = ans1
16 |
17 | ans2 = fun(n-4,dp)
18 | dp[n-4] = ans2
19 |
20 | return n+ans1+ans2
21 |
22 |
23 |
24 | def main():
25 | n = 10
26 | dp = [0 for i in range(n+1)]
27 | ans = fun(n,dp)
28 | print(ans)
29 |
30 | main()
--------------------------------------------------------------------------------
/NITB1/B2/07-08-2024/NQueen.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def nQueen(n,row,col,dia,revDiag,psf):
5 | #base condition
6 | if row == n:
7 | print(psf)
8 | return
9 |
10 | for i in range(n):
11 | if col[i] == 0 and revDiag[i+row] == 0 and dia[i-row+n-1] == 0:
12 | col[i]=1
13 | revDiag[i+row]=1
14 | dia[i-row+n-1]=1
15 | nQueen(n,row+1,col,dia,revDiag, psf+str(row)+"->"+str(i)+",")
16 | col[i]=0
17 | revDiag[i+row]=0
18 | dia[i-row+n-1]=0
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | def main():
28 | n = 4
29 | col = [0 for i in range(n)]
30 | dia = [0 for i in range((2*n)-1)]
31 | revDiag = [0 for i in range((2*n)-1)]
32 | nQueen(n,0,col,dia,revDiag,"")
33 |
34 |
35 | main()
36 |
--------------------------------------------------------------------------------
/NITB1/B2/08-08-2024/DistinctWindowSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def getMaximumSubArraySumWithDistinctElement(arr,k):
5 | ans = float("-inf")
6 | cs , ps = 0, 0
7 | i,j = 0, k-1
8 | myDict = {}
9 | while j < len(arr):
10 | if i == 0:
11 | for k in range(i,j+1):
12 | if arr[k] not in myDict:
13 | myDict[arr[k]] = 1
14 | else:
15 | oldValue = myDict[arr[k]]
16 | oldValue+=1
17 | myDict[arr[k]] = oldValue
18 | # myDict[key]+=1
19 | cs+=arr[k]
20 | if len(myDict) == k and cs > ans:
21 | print("triggered")
22 | print(ans)
23 | ans = cs
24 | ps = cs
25 | else:
26 | removedValueFrequency = myDict[arr[i-1]]
27 | if removedValueFrequency == 1:
28 | del myDict[arr[i-1]]
29 | else:
30 | myDict[arr[i-1]]-=1
31 |
32 | if arr[j] in myDict:
33 | myDict[arr[j]]+=1
34 | else:
35 | myDict[arr[j]] = 1
36 | cs = (ps- arr[i-1])+arr[j]
37 | if len(myDict) == k and cs > ans:
38 | print("triggere")
39 | ans = cs
40 | print(ans)
41 | ps = cs
42 | i+=1
43 | j+=1
44 | #print(ans)
45 | #print(myDict)
46 | return ans
47 |
48 |
49 |
50 |
51 | def main():
52 | arr = [-3,-3,2,9,12,8,16,7,16,-3,2]
53 | k = 5
54 | ans = getMaximumSubArraySumWithDistinctElement(arr,k)
55 | print(ans)
56 |
57 |
58 | main()
--------------------------------------------------------------------------------
/NITB1/B2/08-08-2024/LinkedList.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class Node:
5 | def __init__(self,data):
6 | self.data = data
7 | self.next = None
8 | class LinkedList:
9 | def generateList(self,arr):
10 | head = None
11 | temp = None
12 | for e in arr:
13 | if head == None:
14 | head = Node(e)
15 | temp = head
16 | else:
17 | temp.next = Node(e)
18 | temp = temp.next
19 | return head
20 |
21 | def printList(self,head):
22 | while head is not None:
23 | print(head.data,end=" ")
24 | head = head.next
25 | print()
26 |
27 |
28 | def reverseList(self,head):
29 | st = []
30 | temp = head
31 | while temp is not None:
32 | st.append(temp.data)
33 | temp = temp.next
34 | temp = head
35 | while temp is not None:
36 | temp.data = st.pop()
37 | temp = temp.next
38 | return head
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | def main():
47 | arr = [2,5,7,45,35,38]
48 | myListOperator = LinkedList()
49 | head = myListOperator.generateList(arr)
50 | myListOperator.printList(head)
51 | head = myListOperator.reverseList(head)
52 | myListOperator.printList(head)
53 |
54 | main()
--------------------------------------------------------------------------------
/NITB1/B2/08-08-2024/MaximumSum.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 |
3 | class MaximumSum{
4 | public static void main(String[] args) {
5 | int[] arr = {-3,-3,2,9,12,8,16,7,16,-3,2};
6 | int ws = 5;
7 | int ans = getMaximumSum(arr,ws);
8 | System.out.println(ans);
9 | }
10 |
11 | private static int getMaximumSum(int[] arr, int ws) {
12 | int ans = Integer.MIN_VALUE;
13 | int cs = 0, ps = 0;
14 | int i = 0, j = ws-1;
15 | HashMap myMap = new HashMap<>();
16 | while (j < arr.length) {
17 | if(i == 0){
18 | for(int k=i;k<=j;k++){
19 | cs+=arr[k];
20 | int oldValue = myMap.getOrDefault(arr[k], 0);
21 | oldValue+=1;
22 | myMap.put(arr[k],oldValue);
23 | }
24 | if(cs > ans && myMap.size() == ws){
25 | ans = cs;
26 | }
27 | ps = cs;
28 | }else{
29 |
30 | cs = ps - arr[i-1]+arr[j];
31 | int oldFrequency = myMap.get(arr[i-1]);
32 | if(oldFrequency == 1){
33 | myMap.remove(arr[i-1]);
34 | }else{
35 | oldFrequency-=1;
36 | myMap.put(arr[i-1],oldFrequency);
37 | }
38 |
39 | if(myMap.containsKey(arr[j])){
40 | int oFrequency = myMap.get(arr[j]);
41 | oFrequency+=1;
42 | myMap.put(arr[j],oFrequency);
43 | }else{
44 | myMap.put(arr[j],1);
45 | }
46 |
47 | if(myMap.size() == ws && cs > ans){
48 | ans = cs;
49 | }
50 |
51 | ps = cs;
52 |
53 | }
54 | i+=1;
55 | j+=1;
56 | }
57 |
58 | return ans;
59 |
60 | }
61 |
62 |
63 |
64 |
65 |
66 | }
--------------------------------------------------------------------------------
/NITB1/B2/08-08-2024/Spriral.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def printSpiral(arr,n):
4 | fdri, fdcsi, fdcei = 0, 0, n-1
5 | sdci, sdrsi, sdrei = n-1, 1, n-1
6 | tdri, tdcsi, tdcei = n-1, n-2, 0
7 | fdci, fdrsi, fdrei = 0, n-2, 1
8 | turn = 1
9 |
10 | total = n*n
11 | count = 0
12 |
13 | while count <= total:
14 | if turn == 1:
15 | for col in range(fdcsi,fdcei+1):
16 | print(arr[fdri][col],end=" ")
17 | count+=1
18 | fdri+=1
19 | fdcsi+=1
20 | fdcei-=1
21 | turn = 2
22 | elif turn == 2:
23 | for row in range(sdrsi,sdrei+1):
24 | print(arr[row][sdci],end=" ")
25 | count+=1
26 | sdci-=1
27 | sdrei-=1
28 | sdrsi+=1
29 | turn = 3
30 | elif turn == 3:
31 | for col in range(tdcsi,tdcei-1,-1):
32 | print(arr[tdri][col],end=" ")
33 | count+=1
34 | tdri-=1
35 | tdcei+=1
36 | tdcsi-=1
37 | turn = 4
38 | else:
39 | for row in range(fdrsi,fdrei-1,-1):
40 | print(arr[row][fdci],end=" ")
41 | count+=1
42 | fdci+=1
43 | fdrei+=1
44 | fdrsi-=1
45 | turn = 1
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | def main():
56 | arr = [[3,2,1,4],[9,3,4,5],[-3,2,6,7],[10,9,8,-1]]
57 | n = len(arr)
58 | printSpiral(arr,n)
59 |
60 | main()
--------------------------------------------------------------------------------
/NITB1/B2/09-08-2024/Graph.py:
--------------------------------------------------------------------------------
1 |
2 | def printAllPath(graph,src,des,visited,psf):
3 | if src == des:
4 | print(psf)
5 | return
6 | nbrs = graph[src]
7 |
8 | for i in range(len(nbrs)):
9 | if nbrs[i] == 1:
10 | if visited[i] == 0:
11 | visited[i] = 1
12 | printAllPath(graph,i,des,visited, psf+"->"+str(i))
13 | visited[i] = 0
14 | return False
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | def hasPath(graph,src,des,visited):
24 | if src == des:
25 | return True
26 |
27 | nbrs = graph[src]
28 |
29 | for i in range(len(nbrs)):
30 | if nbrs[i] == 1:
31 | if visited[i] == 0:
32 | visited[i] = 1
33 | ans = hasPath(graph,i,des,visited)
34 | if ans == True:
35 | return True
36 | return False
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | def buildGraph(edges,n):
45 | graph = [[0 for i in range(n)] for j in range(n)]
46 | for edge in edges:
47 | src = edge[0]
48 | des = edge[1]
49 | graph[src][des] = 1
50 | graph[des][src] = 1
51 |
52 | return graph
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | def printGraph(graph):
63 | for row in graph:
64 | for e in row:
65 | print(e,end=" ")
66 | print()
67 |
68 |
69 |
70 |
71 | def main():
72 | edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[4,5],[4,6],[6,7],[5,7]]
73 | n = 8
74 | # bidirectional, non-weighted no self cycle graph
75 | graph = buildGraph(edges,n)
76 | #printGraph(graph)
77 | src = 0
78 | des = 7
79 | visited = [0 for i in range(n)]
80 | visited[src] = 1
81 |
82 | #isPathExist = hasPath(graph,src,des,visited)
83 | #print(isPathExist)
84 |
85 | printAllPath(graph,src,des,visited,str(src))
86 |
87 |
88 | main()
89 |
--------------------------------------------------------------------------------
/NITB1/B2/09-08-2024/TrappingRainWater.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | def getQuantityOfWaterThatsTrapped(arr):
6 | n = len(arr)
7 | left = [0 for i in range(n)]
8 | right = [0 for i in range(n)]
9 |
10 | for i in range(n):
11 | if i == 0:
12 | left[i] = arr[i]
13 | else:
14 | left[i] = max(arr[i],left[i-1])
15 |
16 | for i in range(n-1,-1,-1):
17 | if i == n-1:
18 | right[i] = arr[i]
19 | else:
20 | right[i] = max(arr[i],right[i+1])
21 |
22 | ans = 0
23 | for i in range(n):
24 | currentTrappedWater = min(left[i],right[i]) - arr[i]
25 | if currentTrappedWater > 0:
26 | ans+=currentTrappedWater
27 | return ans
28 |
29 |
30 |
31 |
32 |
33 | def main():
34 | arr = [3,2,9,5,1,3,2,6]
35 | ans = getQuantityOfWaterThatsTrapped(arr)
36 | print(ans)
37 |
38 | main()
--------------------------------------------------------------------------------
/NITB1/B2/10-08-2024/Graph.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | maxCost = float("-inf")
4 | minCost = float("+inf")
5 |
6 | largestPath = ""
7 | smallestPath = -1
8 |
9 |
10 |
11 | def multiSolver(graph,src,des,visited,psf,csf):
12 | global maxCost
13 | global minCost
14 | global smallestPath
15 | global largestPath
16 | if src == des:
17 | if len(psf) > len(largestPath):
18 | largestPath = psf
19 | if smallestPath == -1 or len(psf) < len(smallestPath):
20 | smallestPath = psf
21 |
22 | if csf > maxCost:
23 | maxCost = csf
24 | if csf < minCost:
25 | minCost = csf
26 | return
27 | nbrs = graph[src]
28 |
29 | for i in range(len(nbrs)):
30 | if nbrs[i] != 0:
31 | if visited[i] == 0:
32 | visited[i] = 1
33 | multiSolver(graph,i,des,visited, psf+"->"+str(i), csf + nbrs[i])
34 | visited[i] = 0
35 | return False
36 |
37 |
38 |
39 |
40 | def buildGraph(edges,n):
41 | graph = [[0 for i in range(n)] for j in range(n)]
42 |
43 |
44 | for edge in edges:
45 | src = edge[0]
46 | des = edge[1]
47 | graph[src][des] = 1
48 | graph[des][src] = 1
49 |
50 | return graph
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | def printGraph(graph):
62 | for row in graph:
63 | for e in row:
64 | print(e,end=" ")
65 | print()
66 |
67 |
68 | def bfs(graph,src,visited,queue):
69 | while len(queue) > 0:
70 | removedElement = queue.pop(0)
71 | currentDestination = removedElement[0]
72 | psf = removedElement[1]
73 | visited[currentDestination] = 1
74 | print(str(currentDestination)+"|"+psf)
75 | nbrs = graph[currentDestination]
76 | for i in range(len(nbrs)):
77 | if nbrs[i] == 1 and visited[i] == 0:
78 | queue.append([i,psf+"->"+str(i)])
79 |
80 |
81 | def isCyclic(graph,n):
82 | queue = []
83 | queue.append([0,"0"])
84 | visited = [0 for i in range(n)]
85 | while len(queue) > 0:
86 | removedElement = queue.pop(0)
87 | currentDestination = removedElement[0]
88 | psf = removedElement[1]
89 | if visited[currentDestination] == 1:
90 | return True
91 | visited[currentDestination] = 1
92 | #print(str(currentDestination)+"|"+psf)
93 | nbrs = graph[currentDestination]
94 | for i in range(len(nbrs)):
95 | if nbrs[i] == 1 and visited[i] == 0:
96 | queue.append([i,psf+"->"+str(i)])
97 | return False
98 |
99 |
100 | def expandNode(graph,n,src,currComponent,visited):
101 | nbrs = graph[src]
102 | for i in range(len(nbrs)):
103 | if nbrs[i] == 1 and visited[i] == 0:
104 | visited[i] = 1
105 | currComponent.append(i)
106 | expandNode(graph,n,i,currComponent,visited)
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 | def getAllComponents(graph,n):
116 | visited = [0 for i in range(n)]
117 | ans = []
118 | for i in range(n):
119 | if visited[i] == 0:
120 | visited[i] = 1
121 | currComponent = [i]
122 | expandNode(graph,n,i,currComponent,visited)
123 | ans.append(currComponent)
124 | return ans
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 | def main():
136 | n = 12
137 | edges = [[0,2],[0,3],[1,3],[4,5],[6,7],[6,8],[8,9],[10,11]]
138 |
139 |
140 | graph = buildGraph(edges,n)
141 |
142 | queue = [[0,"0"]]
143 | visited = [0 for i in range(n)]
144 | src = 0
145 | #bfs(graph,src,visited,queue)
146 | # ans = isCyclic(graph,n)
147 | # print(ans)
148 |
149 | ans = getAllComponents(graph,n)
150 | print(ans)
151 |
152 |
153 |
154 | #src = 0
155 | #des = 7
156 | #visited = [0 for i in range(n)]
157 | #visited[src] = 1
158 | #printGraph(graph)
159 |
160 | #multiSolver(graph,src,des,visited,str(src),0)
161 | #print(maxCost," max cost ")
162 | #print(minCost, "min cost")
163 | # print(smallestPath, "smallest path")
164 | # print(largestPath, "largest path")
165 |
166 | main()
--------------------------------------------------------------------------------
/NITB1/B2/13-08-2024/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.REPL.enableREPLSmartSend": false
3 | }
--------------------------------------------------------------------------------
/NITB1/B2/13-08-2024/Graph.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def buildGraph(edges,n):
4 | graph = [[] for i in range(n)]
5 |
6 | for edge in edges:
7 | src1 = edge[0]
8 | src2 = edge[1]
9 |
10 | des1 = edge
11 | des2 = edge[::-1]
12 |
13 | graph[src1].append(des1)
14 | graph[src2].append(des2)
15 |
16 | return graph
17 |
18 |
19 |
20 | def hasPath(graph,n,src,des,visited):
21 | if src == des:
22 | return True
23 | nbrs = graph[src]
24 |
25 | for nbr in nbrs:
26 | currentNbr = nbr[1]
27 | if visited[currentNbr] == 0:
28 | visited[currentNbr] = 1
29 | ans = hasPath(graph,n,currentNbr,des,visited)
30 | if ans == True:
31 | return True
32 |
33 | return False
34 |
35 |
36 |
37 | def main():
38 | edges = [[0,1],[0,2],[1,3],[3,2], [4,6],[4,5],[5,7],[6,7]]
39 | n = 8
40 | graph = buildGraph(edges,n)
41 | src = 0
42 | des = 7
43 | visited = [0 for i in range(n)]
44 | visited[src] = 1
45 | ans = hasPath(graph,n,src,des,visited)
46 | print(ans)
47 |
48 |
49 | main()
--------------------------------------------------------------------------------
/NITB1/B2/13-08-2024/Graph2.py:
--------------------------------------------------------------------------------
1 |
2 | def buildGraph(edges,n):
3 | graph = [[] for i in range(n)]
4 |
5 | for i in range(len(edges)):
6 | edge = edges[i]
7 | src = i
8 | nbr = edge[0]
9 | wt = edge[1]
10 |
11 | graph[src].append([nbr,wt])
12 | graph[nbr].append([src,wt])
13 |
14 | return graph
15 |
16 |
17 |
18 |
19 | def main():
20 | edges = [[0,1,2],[1,2,2],[1,3,3],[3,4,10],[4,5,6],[5,7,3],[4,6,18],[6,7,-5]]
21 | n = 8
22 |
23 | graph = buildGraph(edges,n)
24 | print(graph)
25 |
26 | main()
--------------------------------------------------------------------------------
/NITB1/B2/13-08-2024/NumberOfIslands.py:
--------------------------------------------------------------------------------
1 |
2 | def expandNode(matrix,i,j,visited,n):
3 |
4 | if i<0 or i>=n or j < 0 or j>=n or matrix[i][j] == 0 or visited[i][j] == 1:
5 | return
6 |
7 | visited[i][j] = 1
8 | expandNode(matrix,i+1,j,visited,n)
9 | expandNode(matrix,i-1,j,visited,n)
10 | expandNode(matrix,i,j+1,visited,n)
11 | expandNode(matrix,i,j-1,visited,n)
12 |
13 |
14 |
15 |
16 | def getNumberOfIsland(matrix,n):
17 | visited = [[0 for i in range(n)] for j in range(n)]
18 |
19 | ans = 0
20 | # 1- land, 0- water
21 | for i in range(n):
22 | for j in range(n):
23 | if visited[i][j] == 0 and matrix[i][j] == 1:
24 | expandNode(matrix,i,j,visited,n)
25 | ans+=1
26 |
27 | return ans
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | def main():
36 | matrix = [[1,1,1,1,0,0],[0,0,0,1,1,1],[0,1,1,0,0,0],[1,1,1,1,1,0],[0,0,1,1,1,0],
37 | [0,0,1,1,1,0]
38 | ]
39 | n = len(matrix)
40 | ans = getNumberOfIsland(matrix,n)
41 | print(ans)
42 |
43 | main()
--------------------------------------------------------------------------------
/NITB1/B2/30-07-2024/MissingNumber.py:
--------------------------------------------------------------------------------
1 | def getMissingNumber(n,arr):
2 | ans = 0
3 | for i in range(1,n+1): ans = ans^i
4 |
5 | for i in range(len(arr)):
6 | ans = ans^arr[i]
7 |
8 | return ans
9 |
10 |
11 | def main():
12 | n = 10
13 | arr = [3,9,1,10,7,4,2,5,6]
14 | ans = getMissingNumber(n,arr)
15 | print(ans)
16 |
17 | main()
--------------------------------------------------------------------------------
/NITB1/B2/30-07-2024/TwoUniqueNumber.py:
--------------------------------------------------------------------------------
1 |
2 | def getFirstSetBitPosition(num):
3 | ans = 1
4 | while num%2 != 1:
5 | num = num>>1
6 | ans+=1
7 | return ans
8 |
9 |
10 | def getIthBit(num,i):
11 | return True if (((num>>(i-1))%2 == 1)) else False
12 |
13 | def getBothUniqueNumber(arr):
14 | allXor = 0
15 | for e in arr: allXor = allXor ^ e
16 |
17 | firstSetBit = getFirstSetBitPosition(allXor)
18 | ans1, ans2 = 0, 0
19 |
20 | for e in arr:
21 | if getIthBit(e,firstSetBit) == True:
22 | ans1 = ans1 ^e
23 | else:
24 | ans2 = ans2^e
25 | return ans1, ans2
26 |
27 |
28 |
29 | def main():
30 | arr = [2,3,7,3,7,9]
31 | ans = getBothUniqueNumber(arr)
32 | print(ans)
33 |
34 | main()
--------------------------------------------------------------------------------
/NITB1/B2/31-07-2024/MinimumDecrement.py:
--------------------------------------------------------------------------------
1 | def getMinDecrement(arr):
2 | allXor = 0
3 | for e in arr: allXor = allXor ^ e
4 |
5 | ans = -1
6 |
7 | for e in arr:
8 | allXorExceptE = allXor ^ e
9 |
10 | if allXorExceptE <= e:
11 | currAns = e - allXorExceptE
12 | if ans == -1 or currAns < ans:
13 | ans = currAns
14 |
15 | return ans
16 |
17 |
18 |
19 |
20 |
21 | def main():
22 | arr = [7,3,8,9,5,12]
23 | ans = getMinDecrement(arr)
24 | print(ans)
25 |
26 | main()
--------------------------------------------------------------------------------
/NITB1/B2/31-07-2024/TargetSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def isPairExist(arr,target):
5 | arr.sort()
6 | i = 0
7 | j = len(arr)-1
8 |
9 | while i target: j-=1
13 |
14 | return False
15 |
16 |
17 |
18 |
19 |
20 | def main():
21 | arr = [3,-1,-5,9,12,13,8,6,5,-6,9]
22 | target = 11
23 | ans = isPairExist(arr,target)
24 | print(ans)
25 |
26 | main()
--------------------------------------------------------------------------------
/PB2/ClimbStairs.py:
--------------------------------------------------------------------------------
1 | def getAns(n):
2 | if n<=3:
3 | return n
4 | return getAns(n-1)+getAns(n-2)
5 | print(getAns(6))
--------------------------------------------------------------------------------
/PB2/IsPalindrome.py:
--------------------------------------------------------------------------------
1 | def isPalindrome(_str):
2 | if len(_str) <=1: return True
3 | if _str[0] != _str[-1]: return False
4 | subStr = _str[1:len(_str)-1]
5 | return isPalindrome(subStr)
6 | print(isPalindrome("malaydsalam"))
7 |
--------------------------------------------------------------------------------
/PB2/Permute.py:
--------------------------------------------------------------------------------
1 | def permute(arr):
2 | if len(arr) == 0:return []
3 | if len(arr) == 1:return [arr]
4 | ans = []
5 | for i in range(len(arr)):
6 | fixedEle = arr[i]
7 | subArray = arr[0:i]+arr[i+1:]
8 | allPer = permute(subArray)
9 | for per in allPer:
10 | ans.append([fixedEle]+per)
11 | return ans
12 |
13 |
14 | arr = [1,2,3]
15 | print(permute(arr))
--------------------------------------------------------------------------------
/PB2/Toh.py:
--------------------------------------------------------------------------------
1 | def toh(n,src,des,aux):
2 | if n == 1:
3 | print(src,"->",des)
4 | return
5 | toh(n-1,src,aux,des)
6 | print(src,"->",des)
7 | toh(n-1,aux,des,src)
8 |
9 |
10 | toh(3,"A","C","B")
--------------------------------------------------------------------------------
/algorithms-1/06-11-23/MissingNumber.py:
--------------------------------------------------------------------------------
1 | def missingNumber(arr,n):
2 | ans = 0
3 | for i in range(1,n+1): ans = ans^i
4 | for e in arr: ans = ans^e
5 | return ans
6 |
7 | n = 10
8 | arr = [2,1,3,6,7,4,9,10,8]
9 |
10 | print(missingNumber(arr,n))
11 |
12 |
13 | # print(type(missingNumber))
14 |
--------------------------------------------------------------------------------
/algorithms-1/06-11-23/TwoUniqueNumber.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def findBothUniqueNumbers(arr):
5 | ansXor = 0
6 | segment1 = []
7 | segment2 = []
8 | for e in arr: ansXor = ansXor^e
9 | position = getFirstSetBitPosition(ansXor)
10 | for e in arr:
11 | if isIthBitSet(e,position) == True:
12 | segment1.append(e)
13 | else:
14 | segment2.append(e)
15 | print(segment1)
16 | print(segment2)
17 |
18 | def getFirstSetBitPosition(n):
19 | ans = 1
20 | while n%2 == 0:
21 | n = n>>1
22 | ans+=1
23 | return ans
24 |
25 | def isIthBitSet(n,i):
26 | return (n>>(i-1) % 2 == 1)
27 |
28 |
29 | arr = [2,3,5,2,5,7,15,17,15,34,17]
30 | findBothUniqueNumbers(arr)
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/algorithms/batch2/07-11-23/missing_number.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def missingNumber(arr,n):
4 | ans = 0
5 | for i in range(1,n+1): ans = ans^i
6 | for e in arr: ans = ans^e
7 | return ans
8 |
9 | arr = [1,7,8,3,5,2,4]
10 | n = 8
11 | print(missingNumber(arr,n))
--------------------------------------------------------------------------------
/algorithms/batch2/07-11-23/two_pointer.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def getOrDeafaultPairs(arr,target):
5 | arr.sort()
6 | i,j = 0, len(arr)-1
7 | while i target: j-=1
11 |
12 | return False
13 |
14 | arr = [2,5,-3,65,23]
15 | target = 200
16 | print(getOrDeafaultPairs(arr,target))
--------------------------------------------------------------------------------
/algorithms/batch2/07-11-23/two_unique_number.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def getBothUniqueNumber(arr):
5 | ansXor = 0
6 | for e in arr: ansXor = ansXor^e
7 | pos = getFirstSetBitPosition(ansXor)
8 | segment1 = []
9 | segment2 = []
10 | ans1,ans2 = 0,0
11 | for e in arr:
12 | if isIthBitIsSet(e,pos) == True:
13 | ans1 = ans1^e
14 | else:
15 | ans2 = ans2^e
16 | return ans1,ans2
17 |
18 | def getFirstSetBitPosition(n):
19 | ans = 1
20 | while n % 2 !=1:
21 | n = n>>1
22 | ans+=1
23 | return ans
24 |
25 |
26 |
27 |
28 |
29 | def isIthBitIsSet(n,i):
30 | return ((n>>(i-1))%2 == 1)
31 |
32 |
33 | arr = [2,6,2,7,6,9,1,99,65,9,1,99]
34 | print(getBothUniqueNumber(arr))
35 |
--------------------------------------------------------------------------------
/algorithms/batch2/08-11-23/Kadanes.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getMaximumSubarraySum(arr):
4 | ans = float('-inf')
5 | i = 0
6 | flag = True
7 | cs = 0
8 | for i in range(len(arr)):
9 | if cs < 0:
10 | cs = 0
11 | if arr[i] >=0 :
12 | cs+= arr[i]
13 | ans = max(ans,cs)
14 | flag = False
15 | else:
16 | ans = max(ans,cs)
17 | cs+=arr[i]
18 | if flag == True:
19 | return max(arr)
20 | return max(ans,cs)
21 |
22 |
23 | arr = [-3,-2,-1,-5,-7,-8,-9,-11,-13,-6,-12]
24 | print(getMaximumSubarraySum(arr))
25 |
26 |
27 |
--------------------------------------------------------------------------------
/algorithms/batch2/08-11-23/MultiSolver.py:
--------------------------------------------------------------------------------
1 | def multiSolver(str):
2 | n = len(str)
3 | dp = [[0 for i in range(n)] for j in range(n)]
4 | j = 0
5 | ans = 0
6 | while j < n:
7 | i = 0
8 | jflag = j
9 |
10 | while jflag None:
4 | self.next = None
5 | self.value = value
6 |
7 |
8 |
9 |
10 | def getLength(head):
11 | count = 0
12 | while head:
13 | count+=1
14 | head = head.next
15 | return count
16 |
17 |
18 |
19 | def getMedian(head):
20 | _legth = getLength(head)
21 | median = 0
22 | temp = head
23 | k = (_legth//2 - 1)
24 | while k != 0:
25 | temp = temp.next
26 | k-=1
27 | if _legth % 2 == 0:
28 | median = (temp.value + temp.next.value) //2
29 | else:
30 | median = temp.value
31 | return median
32 |
33 |
34 | def reverseList(head):
35 | st = []
36 | temp = head
37 |
38 | while temp:
39 | st.append(temp.value)
40 | temp = temp.next
41 |
42 | temp = head
43 | while temp:
44 | temp.value = st.pop()
45 | temp = temp.next
46 |
47 |
48 | return head
49 |
50 | def addToStart(head,ele):
51 | temp = Node(ele)
52 | temp.next = head
53 | head = temp
54 |
55 | return head
56 |
57 |
58 |
59 |
60 | def rotateListAtK(head,k):
61 | temp = head
62 | tempK = k
63 | while tempK != 0:
64 | temp = temp.next
65 | tempK-=1
66 | queue = []
67 | while temp:
68 | queue.append(temp.value)
69 | temp = temp.next
70 |
71 | while len(queue) != 0:
72 | ele = queue.pop(0)
73 | head = addToStart(head,ele)
74 |
75 | tempK = 2*k - 1
76 | temp = head
77 | while tempK != 0:
78 | temp = temp.next
79 |
80 | temp.next = None
81 |
82 | return head
83 |
84 |
--------------------------------------------------------------------------------
/algorithms/batch2/11-11-23/MergKSortedList.py:
--------------------------------------------------------------------------------
1 |
2 | # arr = [[1,2,3,4]]
3 |
4 | def mergeTwoSortedList(arr1,arr2):
5 | ans = [0 for i in range(len(arr1)+len(arr2))]
6 | i,j,k = 0,0,0
7 | while i < len(arr1) and j < len(arr2):
8 | if arr1[i] < arr2[j]:
9 | ans[k] = arr1[i]
10 | i+=1
11 | k+=1
12 | else:
13 | ans[k] = arr2[j]
14 | j+=1
15 | k+=1
16 | if i < len(arr1):
17 | while i < len(arr1):
18 | ans[k] = arr1[i]
19 | i+=1
20 | k+=1
21 |
22 | if j < len(arr2):
23 | while j < len(arr2):
24 | ans[k] = arr2[j]
25 | j+=1
26 | k+=1
27 | return ans
28 |
29 |
30 |
31 |
32 |
33 | def mergeKSortedList(arr):
34 | if len(arr) == 1:
35 | return arr[0]
36 | i = 0
37 | ans = []
38 | while i < len(arr):
39 | if i == 0:
40 | ans = mergeTwoSortedList(arr[0],arr[1])
41 | i = 2
42 | else:
43 | ans = mergeTwoSortedList(ans,arr[i])
44 | i+=1
45 | print(ans)
46 |
47 |
48 | arr = [[1,3,5,7],[2,4,7,9,11],[101,202,303],[45],[116]]
49 | mergeKSortedList(arr)
50 |
51 |
--------------------------------------------------------------------------------
/algorithms/batch2/14-11-23/graph.py:
--------------------------------------------------------------------------------
1 |
2 | def printGraphOfMatrix(graph):
3 | for row in graph:
4 | for val in row:
5 | print(val,end=" ")
6 | print()
7 |
8 |
9 | def printGraphOfList(graph):
10 | for node in graph:
11 | for edge in node:
12 | print(edge,end=" ")
13 | print()
14 |
15 |
16 |
17 |
18 | def buildGraphUsingMartrix(edges,n):
19 | graph = [[0 for i in range(n+1)] for j in range(n+1)]
20 |
21 | for edge in edges:
22 | src = edge[0]
23 | des = edge[1]
24 | wt = edge[2]
25 | graph[src][des] = wt
26 | graph[des][src] = wt
27 |
28 | return graph
29 |
30 |
31 | def buildGraphUsingList(edges,n):
32 | graph = [[] for i in range(n+1)]
33 | for edge in edges:
34 | src = edge[0]
35 | des = edge[1]
36 | wt = edge[2]
37 | graph[src].append([src,des,wt])
38 | graph[des].append([des,src,wt])
39 | return graph
40 |
41 |
42 |
43 | def isPathExist(graph,src,des,visited):
44 | if src == des:
45 | return True
46 | visited.append(src)
47 | for edge in graph[src]:
48 | nbr = edge[1]
49 | if nbr not in visited:
50 | visited.append(nbr)
51 | flag = isPathExist(graph,nbr,des,visited)
52 | if flag == True:
53 | return True
54 | return False
55 |
56 | def printAllPaths(graph,src,des,psf,visited):
57 | if src == des:
58 | psf+=str(src)
59 | print(psf)
60 | return
61 | psf+=str(src)
62 | visited[src] = True
63 | for edge in graph[src]:
64 | nbr = edge[1]
65 | if visited[nbr] == False:
66 | printAllPaths(graph,nbr,des,psf,visited)
67 | visited[src] = False
68 |
69 | longestPath, shortestPath = "",""
70 | maximumWeightPath, minimumWeightPath = float('-inf'), float('inf')
71 |
72 | def multiSolver(graph,src,des,psf,visited,wsf):
73 | global longestPath, shortestPath, maximumWeightPath, minimumWeightPath
74 | if src == des:
75 | psf+=str(src)
76 | if len(psf) > len(longestPath):
77 | longestPath = psf
78 | if wsf > maximumWeightPath:
79 | maximumWeightPath = wsf
80 | if wsf < minimumWeightPath:
81 | minimumWeightPath = wsf
82 | if len(psf) < len(shortestPath) or len(shortestPath) == 0:
83 | shortestPath = psf
84 | return
85 | psf+=str(src)
86 | visited[src] = True
87 | for edge in graph[src]:
88 | nbr = edge[1]
89 | if visited[nbr] == False:
90 | multiSolver(graph,nbr,des,psf,visited,wsf+edge[2])
91 |
92 | visited[src] = False
93 |
94 |
95 | def isGraphConnectedOrDisconnected(graph,n):
96 | src = 1
97 | for i in range(1,n+1):
98 | flag = isPathExist(graph,src,i,[])
99 | if flag == False:
100 | return "Disconnected"
101 | return "connected"
102 |
103 |
104 |
105 |
106 |
107 | def isCentric(graph,n):
108 | for node in graph:
109 | if len(graph[node]) == n-1:
110 | return True
111 | return False
112 |
113 |
114 |
115 | n = 8
116 | visited = [False for i in range(n+1)]
117 | edges = [[1,2,10],[1,4,8],[2,3,7],[4,3,10],[6,5,10],[6,7,23],[7,8,56],[5,8,78]]
118 |
119 | # graphUsingMatrix = buildGraphUsingMartrix(edges,n)
120 | # printGraphOfMatrix(graphUsingMatrix)
121 |
122 |
123 | graph = buildGraphUsingList(edges,n)
124 | #printGraphOfList(graph)
125 |
126 | #print(isPathExist(graph,1,6,[]))
127 |
128 | #printAllPaths(graph,1,7,"",visited)
129 | #visited = [False for i in range(n+1)]
130 | #multiSolver(graph,1,2,"",visited,0)
131 | #print(longestPath,shortestPath,maximumWeightPath,minimumWeightPath)
132 |
133 | print(isGraphConnectedOrDisconnected(graph,n))
134 |
135 |
136 |
137 |
--------------------------------------------------------------------------------
/algorithms/batchB6/06-11-23/MissingNumber.py:
--------------------------------------------------------------------------------
1 |
2 | def getMissingNumber(arr,n):
3 | result = 0
4 | for i in range(1,n+1): result = result ^ i
5 | for e in arr: result = result ^ e
6 |
7 | return result
8 |
9 |
10 | arr = [1,4,2,3,5,8,6]
11 | n = 8
12 |
13 | print(getMissingNumber(arr,n))
--------------------------------------------------------------------------------
/algorithms/batchB6/06-11-23/TwoUniqueNumber.py:
--------------------------------------------------------------------------------
1 | def getBothUniqueNumber(arr):
2 | ansXor = 0
3 | for e in arr: ansXor = ansXor ^ e
4 | pos = getFirstSetBitPosition(ansXor)
5 | ans1 , ans2 = 0, 0
6 | for e in arr:
7 | if isIthBitSet(e,pos) == True:
8 | ans1 = ans1 ^ e
9 | else:
10 | ans2 = ans2 ^e
11 | return ans1, ans2
12 |
13 | def isIthBitSet(n,i):
14 | return ((n>>(i-1)) %2 == 1)
15 |
16 |
17 | def getFirstSetBitPosition(n):
18 | pos = 1
19 | while n%2 != 1:
20 | n = n>>1
21 | pos+=1
22 | return pos
23 |
24 |
25 | arr = [2,4,2,6,4,7,14,15,15,17,6,17]
26 | print(getBothUniqueNumber(arr))
--------------------------------------------------------------------------------
/algorithms/batchB6/07-11-23/MergeSortedArray.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def mergeSortedArray(arr1,arr2):
5 | n1 =len(arr1)
6 | n2 =len(arr2)
7 | ans = [0 for i in range(n1+n2)]
8 | i,j,k = 0,0,0
9 | while i=n1:
11 | while j=n2:
16 | while i",des)
6 | toh(n-1,aux,des,src)
7 |
8 |
9 | src,des,aux = 'A','C','B'
10 | n = 3
11 | toh(n,src,des,aux)
--------------------------------------------------------------------------------
/algorithms/batchB6/11-11-23/LinkedList.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def rotateList(head,k):
4 | stack = []
5 | queue = []
6 | counter = 0
7 | temp = head
8 | while temp :
9 | if counter < k:
10 | queue.append(temp.value)
11 | else:
12 | stack.append(temp.value)
13 | counter+=1
14 | temp = temp.next
15 | temp = head
16 | while stack:
17 | temp.value = stack.pop()
18 | temp = temp.next
19 | while queue:
20 | temp.value = queue.pop(0)
21 | temp = temp.next
22 |
23 | return head
24 |
25 |
26 | def getLength(head):
27 | count = 0
28 | while head:
29 | count+=1
30 | head = head.next
31 | return count
32 |
33 | def getMedian(head):
34 | temp = head
35 | lenght = getLength(head)
36 | k = lenght//2 - 1
37 | while k != 0:
38 | temp = temp.next
39 | if lenght % 2 == 1:
40 | return temp.value
41 | return (temp.value+temp.next.value)//2
42 |
43 |
--------------------------------------------------------------------------------
/algorithms/batchB6/11-11-23/MergeKSortedList.py:
--------------------------------------------------------------------------------
1 |
2 | def mergeTwoSortedList(arr1,arr2):
3 | ans = []
4 | return ans
5 |
6 |
7 |
8 |
9 |
10 | def mergeKSortedList(arr):
11 | ans = []
12 | if len(arr) == 1:
13 | return arr[0]
14 | else:
15 | ans = mergeTwoSortedList(arr[0],arr[1])
16 |
17 | i = 2
18 | while i < len(arr):
19 | ans = mergeTwoSortedList(ans,arr[i])
20 | i+=1
21 |
22 | print(ans)
23 |
24 |
25 |
--------------------------------------------------------------------------------
/algorithms/batchB6/14-11-23/NQueen.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def NQueen(n,board,row,col,diag,revDiag,csf):
4 | if row == n-1:
5 | print(csf)
6 | return
7 | for i in range(n):
8 | if col[i] == 0 and diag[row-i] == 0 and revDiag[row-i+n-1]==0:
9 | col[i]=1
10 | diag[row-i]=1
11 | revDiag[row-i+n+1]=1
12 | NQueen(n,board,row+1,col,diag,revDiag,csf+str(row)+"->"+str(i))
13 | col[i]=0
14 | diag[row-i]=0
15 | revDiag[row-i+n+1]=0
16 |
17 | n = 4
18 | board = [[0 for i in range(n)] for j in range(n)]
19 | col = [0 for i in range(n)]
20 | diag = [0 for i in range(2*n+1)]
21 | revDiag = [0 for i in range(2*n+1)]
22 |
23 | NQueen(n,board,0,col,diag,revDiag,"")
24 |
--------------------------------------------------------------------------------
/algorithms/batchB6/14-11-23/graph.py:
--------------------------------------------------------------------------------
1 |
2 | def buildGraphWithMatrix(edges,n):
3 | graph = [[0 for i in range(n+1)] for j in range(n+1)]
4 | for edge in edges:
5 | src = edge[0]
6 | des = edge[1]
7 | wt = edge[2]
8 | graph[src][des] = wt
9 | graph[des][src] = wt
10 |
11 | return graph
12 |
13 | def printMatrixGraph(graph):
14 | for row in graph:
15 | for val in row:
16 | print(val,end=" ")
17 | print()
18 |
19 | def printListGraph(graph):
20 | for node in graph:
21 | for nbr in node:
22 | print(nbr[2],end=" ")
23 | print()
24 |
25 |
26 | def buildGraphWithList(edges,n):
27 | graph = [[] for i in range(n+1)]
28 |
29 | for edge in edges:
30 | src = edge[0]
31 | des = edge[1]
32 | wt = edge[2]
33 | graph[src].append([src,des,wt])
34 | graph[des].append([des,src,wt])
35 |
36 | return graph
37 |
38 |
39 | def hasPath(graph,src,des,visited):
40 | if src == des:
41 | return True
42 | for edge in graph[src]:
43 | if visited[edge[1]] == False:
44 | visited[edge[1]] = True
45 | flag = hasPath(graph,edge[1],des,visited)
46 | if flag == True:
47 | return True
48 | return False
49 |
50 |
51 | def isGraphConnected(graph,n):
52 | src = 1
53 | for i in range(1,n+1):
54 | flag = hasPath(graph,src,i,[False for i in range(n+1)])
55 | if flag == False:
56 | return "Disconnected"
57 | return "Connected"
58 |
59 | def printAllPath(graph,src,des,psf,visited):
60 | if src == des:
61 | psf+=str(src)
62 | print(psf)
63 | return
64 | psf+=str(src)
65 | visited[src] = True
66 | for edge in graph[src]:
67 | if visited[edge[1]] == False:
68 | printAllPath(graph,edge[1],des,psf,visited)
69 | visited[src] = False
70 |
71 | longestPath , shortestPath = "",""
72 | minimumWeight, maximumWeight= float('inf'), float('-inf')
73 |
74 | def multiSolver(graph,src,des,psf,visited,wsf):
75 | global longestPath,shortestPath,minimumWeight,maximumWeight
76 | if src == des:
77 | psf+=str(src)
78 | if len(psf) > len(longestPath):
79 | longestPath = psf
80 | if len(psf) < len(shortestPath) or len(shortestPath) == 0:
81 | shortestPath = psf
82 | if wsf > maximumWeight:
83 | maximumWeight = wsf
84 | if wsf < minimumWeight:
85 | minimumWeight = wsf
86 | return
87 | psf+=str(src)
88 | visited[src] = True
89 | for edge in graph[src]:
90 | if visited[edge[1]] == False:
91 | multiSolver(graph,edge[1],des,psf,visited,wsf+edge[2])
92 | visited[src] = False
93 |
94 |
95 |
96 |
97 | n = 8
98 | edges = [[1,2,4],[1,4,10],
99 | [2,3,56],[2,5,78],
100 | [4,3,24],[5,8,13],
101 | [5,6,78],[8,7,23],
102 | [6,7,45]]
103 |
104 | visited = [False for i in range(n+1)]
105 | graph = buildGraphWithList(edges,n)
106 | #graphUsingMatrix = buildGraphWithMatrix(edges,n)
107 |
108 | # printListGraph(graphUsingList)
109 | # printMatrixGraph(graphUsingMatrix)
110 | print(hasPath(graph,1,8,visited))
111 | print(isGraphConnected(graph,n))
112 |
113 | printAllPath(graph,1,8,"",[False for i in range(n+1)])
114 |
115 |
116 | multiSolver(graph,1,8,"",[False for i in range(n+1)],0)
117 | print(longestPath,shortestPath,maximumWeight,minimumWeight)
--------------------------------------------------------------------------------
/coding-problems/.idea/SRU.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/coding-problems/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/coding-problems/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/coding-problems/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/coding-problems/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | {
20 | "associatedIndex": 0
21 | }
22 |
23 |
24 |
25 |
26 |
27 | {
28 | "keyToString": {
29 | "RunOnceActivity.OpenProjectViewOnStart": "true",
30 | "RunOnceActivity.ShowReadmeOnStart": "true",
31 | "git-widget-placeholder": "master",
32 | "last_opened_file_path": "D:/codes/python_practice_codes/SRU"
33 | }
34 | }
35 |
36 |
37 |
38 |
39 | 1697428440120
40 |
41 |
42 | 1697428440120
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/coding-problems/10-10-23/kadanes.py:
--------------------------------------------------------------------------------
1 | def kadanes(arr):
2 | _sum = float("-inf")
3 | cs = arr[0]
4 | n = len(arr)
5 | for i in range(1,n):
6 | if cs < 0:
7 | cs = 0
8 | if arr[i] < 0:
9 | _sum = max(_sum,cs+arr[i])
10 | cs = cs+arr[i]
11 | return max(_sum,cs)
12 |
13 | print(kadanes([-1,-2,3,-4,-6,18,65,110]))
14 |
15 |
16 |
--------------------------------------------------------------------------------
/coding-problems/10-10-23/merge_sorted_arr.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr1 = [-2,4,13,45,65,76,98,109]
3 | arr2 = [-30,-1,23,54,67,87,99,199,301]
4 | ans=[]
5 | i,j = 0,0
6 | while i=len(arr1):
8 | while j=len(arr2):
12 | while i [-1,2,32,4,5,5,4,3,2]
19 | ''' queires=[
20 | [0,4],
21 | [2,5],
22 | [3,6]
23 | ]
24 | '''
25 | query_subarray_sum([
26 | 2,4,5,1,6,3,7,8
27 | ],
28 | [
29 | [0,4],[1,3],[4,6]
30 | ]
31 | )
32 |
--------------------------------------------------------------------------------
/coding-problems/10-10-23/sliding_window.py:
--------------------------------------------------------------------------------
1 | def sliding_window(arr,k):
2 | _sum = 0
3 | ps = 0
4 | i,j = 0,k-1
5 | while j target: j-=1
8 | return False
9 |
10 |
--------------------------------------------------------------------------------
/coding-problems/11-10-23/all_palindrome.py:
--------------------------------------------------------------------------------
1 | def main():
2 | _str = "madammadam"
3 | #a = int(input())
4 | n = len(_str)
5 | dp = [[0 for i in range(n)] for j in range(n)]
6 | #print(dp)
7 | i,j = 0,0
8 | count = 0
9 | while j < n:
10 | jflag = j
11 | while jflag < n:
12 | if i == jflag:
13 | dp[i][jflag] = 1
14 | count+=1
15 |
16 | elif abs(i-jflag) == 1:
17 | if _str[i]==_str[jflag]:
18 | dp[i][jflag]=1
19 | count+=1
20 | else:
21 | dp[i][jflag]=0
22 | else:
23 | if _str[i]==_str[jflag]:
24 | if dp[i+1][jflag-1]==1:
25 | dp[i][jflag]=1
26 | count+=1
27 | else:
28 | dp[i][jflag]=0
29 | else:
30 | dp[i][jflag]=0
31 | i+=1
32 | jflag+=1
33 | j+=1
34 | i=0
35 | #print(dp)
36 | return count
37 |
38 | print(main())
39 |
40 |
--------------------------------------------------------------------------------
/coding-problems/11-10-23/recursion_time.py:
--------------------------------------------------------------------------------
1 | from time import *
2 |
3 | def fun(n):
4 | if n<=2: return n
5 | return fun(n-2)+fun(n-4)
6 | # start_time = perf_counter()
7 | # ans = fun(16)
8 | # sleep(0)
9 | # end_time = perf_counter()
10 | # print((end_time-start_time)*1000," ms")
11 |
12 | dp = [-100 for i in range(17)]
13 | def optimised_fun(n):
14 | global dp
15 | if dp[n] != -100:
16 | return dp[n]
17 | if n<=2:
18 | dp[n] = n
19 | return n
20 | ans1 = fun(n-2)
21 | ans2 = fun(n-4)
22 | dp[n-2] = ans1
23 | dp[n-4] = ans2
24 | return ans1+ans2
25 | print(optimised_fun(16))
26 |
--------------------------------------------------------------------------------
/coding-problems/11-10-23/test_arr.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | n = 3
4 | dp = [[0]*n]*n
5 | #print(dp)
6 |
7 | dp[0][1] = 5
8 | #print(dp)
9 |
10 |
11 | dp2 = [[0 for i in range(n)] for j in range(n)]
12 | print(dp2)
13 | dp2[0][1] = 5
14 | print(dp2)
--------------------------------------------------------------------------------
/coding-problems/11-10-23/unique_Position.py:
--------------------------------------------------------------------------------
1 | def main():
2 | _str = "bfbfbfbbfbbfbfbfb"
3 | visited = [0 for i in range(1000)]
4 | cp = 0
5 | visited[cp]=1
6 | ans = 1
7 | for ch in _str:
8 | if ch == 'b':
9 | if cp-1>=0:
10 | cp-=1
11 | else:
12 | cp+=2
13 | if visited[cp]!=1:
14 | ans+=1
15 | visited[cp]=1
16 | return ans
17 |
18 | print(main())
--------------------------------------------------------------------------------
/coding-problems/12-10-23/all_permutation.py:
--------------------------------------------------------------------------------
1 | def permute(arr):
2 | if len(arr) == 1:
3 | return [arr]
4 | ans = []
5 | for i in range(len(arr)):
6 | temp_ans = [arr[i]]
7 | sub_arr = arr[0:i]+arr[i+1 :]
8 | p_arr = permute(sub_arr)
9 | for e in p_arr:
10 | ans.append(temp_ans+e)
11 | return ans
12 |
13 | print(permute([1,2,3]))
--------------------------------------------------------------------------------
/coding-problems/12-10-23/fib.py:
--------------------------------------------------------------------------------
1 |
2 | def sum_till_nth(n):
3 |
4 |
5 |
6 |
7 |
8 | def nth_fibonaci_number(n):
9 | if n==1 or n==2:
10 | return n-1
11 | return nth_fibonaci_number(n-1)+nth_fibonaci_number(n-2)
12 |
13 | print(nth_fibonaci_number(10))
--------------------------------------------------------------------------------
/coding-problems/12-10-23/n_queen.py:
--------------------------------------------------------------------------------
1 | def solve_n_queen(n,board,row,col,diag,rev_diag,asf):
2 | if row == n:
3 | print(asf)
4 | return
5 | for i in range(n):
6 | if col[i] == 0 and diag[row+i] == 0 and rev_diag[row-i+n-1]==0:
7 | board[row][i] = 1
8 | col[i] = 1
9 | diag[row+i] = 1
10 | rev_diag[row-i+n-1]=1
11 | solve_n_queen(n,board,row+1,col,diag,rev_diag,asf+str(row)+"->"+str(i)+" ")
12 | col[i] = 0
13 | diag[row+i] = 0
14 | rev_diag[row-i+n-1]=0
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | def main():
24 | n = 4
25 | board = [[0 for i in range(n)] for j in range(n)]
26 | col = [0 for i in range(n)]
27 | diag = [0 for i in range(2*n-1)]
28 | rev_diag = [0 for i in range(2*n-1)]
29 | solve_n_queen(n,board,0,col,diag,rev_diag,"")
30 |
31 |
32 | main()
--------------------------------------------------------------------------------
/coding-problems/12-10-23/n_ways.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def find_number_of_ways(n):
4 | if n==1:
5 | return 1
6 | if n<=0:
7 | return 0
8 | return find_number_of_ways(n-1)+find_number_of_ways(n-2)+find_number_of_ways(n-3)
9 |
10 | print(find_number_of_ways(5))
--------------------------------------------------------------------------------
/coding-problems/12-10-23/single_linked_list.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self,data):
3 | self.data = data
4 | self.next = None
5 |
6 | class LinkedList:
7 | def __init__(self):
8 | self.start = None
9 | self.temp = None
10 | def create_list(self):
11 | for i in range(11):
12 | new_node = Node(i)
13 | if self.start is None:
14 | self.start = new_node
15 | self.temp = self.start
16 | else:
17 | self.temp.next = new_node
18 | self.temp = self.temp.next
19 | return self.start
20 | def print_list(self):
21 | self.temp = self.start
22 | while self.temp:
23 | print(self.temp.data,end=" ")
24 | self.temp = self.temp.next
25 | print()
26 | def reverse_list(self):
27 | self.temp = self.start
28 | arr = []
29 | while self.temp is not None:
30 | arr.append(self.temp.data)
31 | self.temp = self.temp.next
32 | arr = arr[::-1]
33 | self.temp = self.start
34 | i = 0
35 | #print("arr",arr)
36 | while self.temp is not None:
37 | self.temp.data = arr[i]
38 | i+=1
39 | self.temp = self.temp.next
40 |
41 |
42 |
43 | # def find_median(self):
44 | # self.temp = self.start
45 | # print("self.temp-check1",self.temp)
46 | # length = self.find_length()
47 | # counter = length//2
48 | # counter-=1
49 | # print("counter",counter)
50 | # i = 1
51 | # while i!= counter:
52 | # print(i,end=" ")
53 | # self.temp = self.temp.next
54 | # i+=1
55 | # print("self.temp-check2",self.temp)
56 | # if length % 2 == 1 and self.temp is not None:
57 | # return self.temp.next.data
58 | # elif self.temp is not None and self.temp.next is not None:
59 | # return (self.temp.data + self.temp.next.data) // 2
60 |
61 | def find_length(self):
62 | self.temp = self.start
63 | ans = 0
64 | while self.temp is not None:
65 | ans+=1
66 | self.temp = self.temp.next
67 | return ans
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | object_ = LinkedList()
76 | start = object_.create_list()
77 | object_.print_list()
78 | object_.reverse_list()
79 | object_.print_list()
80 |
81 |
82 |
83 | #object_.print_list()
84 | #object_.print_list()
85 |
86 |
87 | # length = object_.find_length()
88 | # print(length)
89 |
90 | #median = object_.find_median()
91 | #print("median ",median)
--------------------------------------------------------------------------------
/coding-problems/13-10-23/single_linked_list.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | # def __new__(self,data):
3 | # print("inside new")
4 | def __init__(self,data):
5 | self.data = data
6 | self.next = None
7 |
8 | class LinkedList:
9 | def __init__(self):
10 | self.start = None
11 | self.merged_list = None
12 | def append_node(self,data):
13 | new_node = Node(data)
14 | current = self.start
15 | if self.start is None:
16 | self.start = new_node
17 | else:
18 | temp = current
19 | while temp.next is not None:
20 | temp = temp.next
21 | temp.next = new_node
22 |
23 | def print_list(self):
24 | current = self.start
25 | temp = current
26 | while temp is not None:
27 | print(temp.data,end=" ")
28 | temp = temp.next
29 | print()
30 | def reverse_list(self):
31 | current = self.start
32 | initial = self.start
33 | arr = []
34 | while current is not None:
35 | arr.append(current.data)
36 | current = current.next
37 | arr = arr[::-1]
38 | i=0
39 | while initial is not None:
40 | initial.data = arr[i]
41 | initial = initial.next
42 | i+=1
43 | def get_length(self):
44 | temp = self.start
45 | count = 0
46 | while temp is not None:
47 | count+=1
48 | temp = temp.next
49 | return count
50 | def delete_middle(self):
51 | length = self.get_length()
52 | current = self.start
53 | counter = (length//2 - 1)
54 | while counter !=0:
55 | current = current.next
56 | counter-=1
57 | if length%2 == 0:
58 | current.next = current.next.next.next
59 | else:
60 | current.next = current.next.next
61 | def find_median(self):
62 | length = self.get_length()
63 | current = self.start
64 | counter = (length//2 - 1)
65 | while counter !=0:
66 | current = current.next
67 | counter-=1
68 | if length%2 == 0:
69 | return (current.data+current.next.data)/2
70 | else:
71 | return current.next.data
72 |
73 | def delete_after_and_before(self,n):
74 | current = self.start
75 | if current.data == n:
76 | print("before does not exist")
77 | current.next = current.next.next
78 | else:
79 | while current.next.next.data != n:
80 | current = current.next
81 | current.next = current.next.next
82 | current = current.next
83 | current.next = current.next.next
84 |
85 | def insert_after(self,after_value,value_to_be_inserted):
86 | current = self.start
87 | while current.data != after_value:
88 | current = current.next
89 | if current is None:
90 | print("after value does not exists")
91 | else:
92 | new_node = Node(value_to_be_inserted)
93 | new_node.next = current.next
94 | current.next = new_node
95 | def generate_number(self):
96 |
97 |
98 | # def merge_sorted_list(self,list1,list2,ans):
99 | # current = self.merged_list
100 | # while list1 is not None or list2 is not None:
101 | # if list1 is None:
102 | # while list2 is not None:
103 | # ans.append_node(list2.data)
104 | # list2 = list2.next
105 | # elif list2 is None:
106 | # while list1 is not None:
107 | # ans.append_node(list1.data)
108 | # list1 = list1.next
109 | # elif list1.data > list2.data:
110 | # ans.append_node(list1.data)
111 | # list1 = list1.next
112 | # else:
113 | # ans.append_node(list2.data)
114 | # list2 = list2.next
115 | # return ans
116 |
117 | def rotate_list(self,k):
118 | current = self.start
119 | length = self.get_length()
120 | counter = length-k-1
121 | while counter !=0:
122 | current = current.next
123 | counter-=1
124 | temp_current = current
125 | current = current.next
126 | temp_current.next = None
127 | while current is not None:
128 | temp_current = current.next
129 | current.next = self.start
130 | self.start = current
131 | current = temp_current
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 | my_list = LinkedList()
159 | for i in range(12):
160 | my_list.append_node(i)
161 | #my_list.print_list()
162 | # #my_list.reverse_list()
163 | # #my_list.print_list()
164 | # #print(my_list.get_length())
165 | # #my_list.delete_middle()
166 | # my_list.print_list()
167 | # #print(my_list.find_median())
168 | # my_list.delete_after_and_before(0)
169 | # my_list.print_list()
170 | # my_list.insert_after(6,100)
171 | # my_list.print_list()
172 |
173 | # list1 = LinkedList()
174 | # for i in range(11,25):
175 | # list1.append_node(i)
176 |
177 | # list2 = LinkedList()
178 | # for i in range(7,28):
179 | # list2.append_node(i)
180 |
181 | # list1.print_list()
182 | # list2.print_list()
183 |
184 |
185 |
186 | # ans.print_list()
187 |
188 | my_list.rotate_list(3)
189 | my_list.print_list()
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
--------------------------------------------------------------------------------
/coding-problems/14-10-23/pattern.py:
--------------------------------------------------------------------------------
1 | def pyramid(n):
2 | row = n
3 | col = 2*n-1
4 | start , end = n-1 , n-1
5 | for i in range(row):
6 | for j in range(col):
7 | if j>=start and j<=end:
8 | print(" ",end="")
9 | else:
10 | print("*",end="")
11 | print()
12 | start-=1
13 | end+=1
14 |
15 | def circle(n):
16 | row = n
17 | col = n
18 | for i in range(row):
19 | for j in range(col):
20 | if i==j or (i+j) == n-1:
21 | print(" ",end=" ")
22 | elif i==0 or i==n-1 or j==0 or j==n-1:
23 | print("*",end=" ")
24 | else:
25 | print(" ",end=" ")
26 | print()
27 |
28 | def upper_trangular(n):
29 | char = 'a'
30 | for i in range(1,n+1):
31 | for j in range(i):
32 | print(char,end=" ")
33 | char = chr(ord(char)+1)
34 | if char > 'z':
35 | char = 'a'
36 | print()
37 |
38 | def hollow_pyramid(n):
39 | row = n
40 | col = 2*n-1
41 | start , end = n-1 , n-1
42 | var = 2
43 | var2 = 1
44 | for i in range(row):
45 | for j in range(col):
46 | if (j==start or j==end) and i!=n-1:
47 | if start == end:
48 | print(1,end=" ")
49 | elif j==start:
50 | print(1,end=" ")
51 | else:
52 | print(var,end=" ")
53 | var+=1
54 | elif i==n-1 and (j>=start and j<=n-1):
55 | print(var2,end=" ")
56 | var2+=1
57 | else:
58 | print(" ",end="")
59 |
60 | print()
61 | start-=1
62 | end+=1
63 |
64 |
65 |
66 | hollow_pyramid(5)
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/coding-problems/16-10-23/graph.py:
--------------------------------------------------------------------------------
1 |
2 | vertices = 6
3 | graph = [[[]] for i in range(vertices)]
4 | graph[0] = [[0,1,3],[0,2,2]]
5 | graph[1] = [[1,0,3],[1,2,5]]
6 | graph[2] = [[2,0,1],[2,1,4]]
7 |
8 | graph[3] = [[3,4,3],[3,5,2]]
9 | graph[4] = [[4,3,3],[4,5,5]]
10 | graph[5] = [[5,4,1],[5,3,4]]
11 |
12 | visited = [False for i in range(vertices)]
13 |
14 | def has_path(graph, src , des , visited):
15 | if src == des:
16 | return True
17 | for neighbour in graph[src]:
18 | next_neighbour = neighbour[1]
19 | if visited[next_neighbour] == False:
20 | visited[next_neighbour] = True
21 | result = has_path(graph,neighbour[1],des,visited)
22 | if result == True:
23 | return True
24 | return False
25 |
26 | print(has_path(graph,1,3,visited))
27 |
28 |
29 |
--------------------------------------------------------------------------------
/coding-problems/16-10-23/hash_map.py:
--------------------------------------------------------------------------------
1 | my_map = {}
2 | # putting a key value pair
3 | my_map["key"] = "This is a value"
4 | my_map[0] = "ZERO"
5 | my_map[1.3] = "ONE.THREE"
6 | my_map[0] = "UPDATED ZERO"
7 |
8 | for key in my_map:
9 | print(my_map[key],end=" ")
10 |
11 |
12 |
13 | #Printing and defaulting if a key does not exist
14 | # print(my_map)
15 | # try:
16 | # print(my_map[10])
17 | # except:
18 | # print("key does not exists")
19 | # print(my_map[1.3])
20 |
21 |
22 | #del my_map[0]
23 | # print(my_map)
24 |
25 |
26 | # if "key" in my_map:
27 | # print("key key is present")
28 | # else:
29 | # print("key 0 is not present")
--------------------------------------------------------------------------------
/coding-problems/16-10-23/heap_impl.py:
--------------------------------------------------------------------------------
1 | from heapq import heappop, heappush, _heapify_max
2 |
3 | max_heap = [1,4,2,6]
4 |
5 | _heapify_max(max_heap)
6 |
7 | print(heappop(max_heap))
8 | _heapify_max(max_heap)
9 | print(heappop(max_heap))
10 | _heapify_max(max_heap)
11 | print(heappop(max_heap))
12 |
13 |
14 | print(max_heap)
15 |
--------------------------------------------------------------------------------
/coding-problems/16-10-23/test.txt:
--------------------------------------------------------------------------------
1 | [[[0, 7], [7, 0], [0, 8], [8, 0], [0, 4], [4, 0]], [[1, 3], [3, 1]], [[2, 0], [0, 2]], [[3, 5], [5, 3]], [[4, 7], [7, 4]], [[5, 8], [8, 5]], [[6, 1], [1, 6], [6, 5], [5, 6]], [], [], []] 0 2 [False, False, False, False, False, False, False, False, False, False]
2 | [[[0, 7], [7, 0], [0, 8], [8, 0], [0, 4], [4, 0]], [[1, 3], [3, 1]], [[2, 0], [0, 2]], [[3, 5], [5, 3]], [[4, 7], [7, 4]], [[5, 8], [8, 5]], [[6, 1], [1, 6], [6, 5], [5, 6]], [], [], []] 7 2 [True, False, False, False, False, False, False, False, False, False]
3 | [[[0, 7], [7, 0], [0, 8], [8, 0], [0, 4], [4, 0]], [[1, 3], [3, 1]], [[2, 0], [0, 2]], [[3, 5], [5, 3]], [[4, 7], [7, 4]], [[5, 8], [8, 5]], [[6, 1], [1, 6], [6, 5], [5, 6]], [], [], []] 8 2 [True, False, False, False, False, False, False, True, False, False]
4 | [[[0, 7], [7, 0], [0, 8], [8, 0], [0, 4], [4, 0]], [[1, 3], [3, 1]], [[2, 0], [0, 2]], [[3, 5], [5, 3]], [[4, 7], [7, 4]], [[5, 8], [8, 5]], [[6, 1], [1, 6], [6, 5], [5, 6]], [], [], []] 4 2 [True, False, False, False, False, False, False, True, True, False]
--------------------------------------------------------------------------------
/coding-problems/17-10-23/graph.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | min_weight = float('+inf')
4 | min_weight_path = ""
5 | max_weight = float('-inf')
6 | max_weight_path = ""
7 |
8 | threshold_ceil = float('-inf')
9 | threshold_ceil_path = ""
10 | threshold_floor = float('+inf')
11 | threshold_floor_path = ""
12 |
13 | components = []
14 |
15 |
16 |
17 | def build_graph(number_of_vertices):
18 |
19 | graph = [[] for i in range(number_of_vertices)]
20 |
21 | graph[0].append([0,1,10])
22 | graph[0].append([0,2,8])
23 | graph[0].append([0,3,8])
24 | graph[0].append([0,4,8])
25 |
26 | graph[1].append([1,0,5])
27 | # graph[1].append([1,3,5])
28 | # graph[1].append([1,4,10])
29 |
30 | #graph[2].append([2,3,7])
31 | graph[2].append([2,0,8])
32 |
33 | graph[3].append([3,0,7])
34 | #graph[3].append([3,1,10])
35 |
36 | graph[4].append([4,0,10])
37 | # graph[4].append([4,5,8])
38 | # graph[4].append([4,1,8])
39 |
40 | # graph[5].append([5,4,8])
41 | # graph[5].append([5,6,3])
42 |
43 | # graph[6].append([6,5,2])
44 | # graph[6].append([6,7,3])
45 |
46 | # graph[7].append([7,6,2])
47 | # graph[7].append([7,4,10])
48 |
49 | return graph
50 |
51 |
52 | def print_graph(graph):
53 | for vertices in graph:
54 | for edge in vertices:
55 | print(edge,end=" ")
56 | print()
57 |
58 | def has_path(graph, src , des , visited):
59 | if src == des:
60 | return True
61 | visited[src] = True
62 | for edge in graph[src]:
63 | if visited[edge[1]] == False:
64 | value = has_path(graph,edge[1],des,visited)
65 | if value == True:
66 | return True
67 | return False
68 |
69 |
70 | def print_all_path(graph,src,des,psf,visited):
71 | if src == des:
72 | psf += str(src)
73 | print(psf)
74 | return
75 | psf+=str(src)
76 | visited[src] = True
77 | for edge in graph[src]:
78 | if visited[edge[1]] == False:
79 | print_all_path(graph,edge[1],des,psf,visited)
80 | visited[src] = False
81 |
82 | def multi_solver(graph,src,des,psf,wsf,visited,threshold):
83 | global min_weight
84 | global min_weight_path
85 | global max_weight
86 | global max_weight_path
87 | global threshold_ceil
88 | global threshold_floor
89 | global threshold_ceil_path
90 | global threshold_floor_path
91 | # k --> kth largest path according to weight
92 | # threshold -> path with floor and ceil of threshold
93 | # largest path from src to des acc to weight
94 | # smallest path from src to des acc to weight
95 | if src == des:
96 | psf += str(src)
97 | if wsf < min_weight:
98 | min_weight = wsf
99 | min_weight_path = psf
100 | if wsf > max_weight:
101 | max_weight = wsf
102 | max_weight_path = psf
103 | if wsf > threshold and threshold_ceil < wsf:
104 | threshold_ceil = wsf
105 | threshold_ceil_path = psf
106 | if wsf < threshold and threshold_floor > wsf:
107 | threshold_floor = wsf
108 | threshold_floor_path = psf
109 | psf+=str(src)
110 | visited[src] = True
111 | for edge in graph[src]:
112 | if visited[edge[1]] == False:
113 | multi_solver(graph,edge[1],des,psf,wsf+edge[2],visited,threshold)
114 | visited[src] = False
115 |
116 |
117 | def get_center(graph,n):
118 | for i in range(n):
119 | queue = deque()
120 | visited = set()
121 | start = i
122 | psf = ""
123 | center_arr = []
124 | queue.append([start,""])
125 | v = bfs(graph,queue,visited,psf,n,center_arr)
126 | if v == -1:
127 | break
128 |
129 |
130 |
131 | # def get_connected_components(graph, number_of_vertices):
132 | # global components
133 | # visited = [False for i in range(number_of_vertices)]
134 | # for i in range(number_of_vertices):
135 | # component = ""
136 | # if visited[i] == False:
137 |
138 | # def draw_tree(graph,vertex,visied,csf):
139 | # visited[vertex] = True
140 | # for edge in graph[vertex]:
141 |
142 | def bfs(graph,queue,visited,psf,n,center_arr):
143 | #my_map = {}
144 | #flag = True
145 | while queue:
146 | removed_node = queue.popleft()
147 | #print("level of ",removed_node," is",removed_node[2])
148 | #print(removed_node,"removed node",end=" ")
149 | visited.add(removed_node[0])
150 | psf = (removed_node[1]+str(removed_node[0]))
151 | #level = removed_node[2]
152 | #src = removed_node[0]
153 | #if flag == True:
154 | #my_map[origin] = [src+1]
155 | #flag = False
156 | #if level not in my_map:
157 | #if src != origin:
158 | #my_map[level] = [src]
159 | #else:
160 | #if src != origin:
161 | #updated_value = my_map[level]+[src]
162 | #my_map[level] = updated_value
163 | print(psf)
164 | if len(psf) != 1 or len(psf) != 0:
165 | center_arr.append(psf[-1])
166 | if len(center_arr) == n-1:
167 | print(center_arr)
168 | return -1
169 | #next_level = level+1
170 | for nbr in graph[removed_node[0]]:
171 | if nbr[1] not in visited:
172 | queue.append([nbr[1],psf])
173 | visited.add(nbr[1])
174 | #print(my_map)
175 |
176 |
177 |
178 |
179 |
180 | def main():
181 | #global min_weight
182 | #global min_weight_path
183 | #global max_weight
184 | #global max_weight_path
185 | number_of_vertices = 5
186 | graph = build_graph(number_of_vertices)
187 | #print(graph)
188 | #print_graph(graph)
189 | #visited = [False for i in range(number_of_vertices)]
190 | #print(has_path(graph,0,3,visited))
191 | #print_all_path(graph,0,6,"",visited)
192 | #multi_solver(graph,0,6,"",0,visited,45)
193 | #print(min_weight,min_weight_path)
194 | #print(max_weight,max_weight_path)
195 |
196 | #print("threshold ceil path",threshold_ceil_path)
197 | #print("threshold ceil weight",threshold_ceil)
198 | #print("threshold floor path",threshold_floor_path)
199 | #print("threshold floor weight",threshold_floor)
200 |
201 | # for vertex in range(number_of_vertices):
202 | # global components
203 | # if visited[vertex] == False:
204 | # csf = ""
205 | # visited[vertex] = True
206 | # draw_tree(graph,vertex,visited,csf)
207 | # components.append(csf)
208 |
209 | queue = deque()
210 | visited = set()
211 | start = 0
212 | psf = ""
213 | queue.append([start,""])
214 | #bfs(graph,queue,visited,psf)
215 | get_center(graph,number_of_vertices)
216 |
217 |
218 |
219 | main()
220 |
221 |
222 |
223 |
224 |
225 |
--------------------------------------------------------------------------------
/coding-problems/17-10-23/leetcode_1967.py:
--------------------------------------------------------------------------------
1 | minimum_weight = float('+inf')
2 | ans = 0
3 | modulo = (10**9 + 7)
4 |
5 | def main():
6 | n = 7
7 | roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
8 | #roads = [[1,0,10]]
9 | ans = countPaths(n,roads)
10 | print(ans)
11 |
12 |
13 | def countPaths(n,roads):
14 | global ans
15 | graph = [[] for i in range(n)]
16 | visited = [False for i in range(n)]
17 | for road in roads:
18 | src1 = road[0]
19 | des1 = road
20 | src2 = road[1]
21 | pair = road[0:2]
22 | pair = pair[::-1]
23 | des2 = pair + [road[2]]
24 | graph[src1].append(des1)
25 | graph[src2].append(des2)
26 | get_number_of_ways(graph,0,n-1,0,visited)
27 | return ans % modulo
28 |
29 | def get_number_of_ways(graph,src,des,wsf,visited):
30 | global ans
31 | global minimum_weight
32 | global modulo
33 | if src == des:
34 | print(wsf)
35 | if wsf < minimum_weight:
36 | ans = 1
37 | minimum_weight = wsf
38 | elif wsf == minimum_weight:
39 | ans = (ans+1)
40 | visited[src] = True
41 | for road in graph[src]:
42 | if visited[road[1]] == False:
43 | get_number_of_ways(graph,road[1],des,wsf+road[2],visited)
44 | visited[src] = False
45 |
46 | main()
--------------------------------------------------------------------------------
/coding-problems/17-10-23/stack.py:
--------------------------------------------------------------------------------
1 | stack = []
2 |
3 | stack.append(10)
4 | stack.append(23)
5 | stack.append(45)
6 |
7 | print(stack.pop())
8 | print(stack.pop())
9 |
10 | if len(stack) >=1:
11 | print(stack[-1])
12 | else:
13 | print("stack is empty")
14 |
--------------------------------------------------------------------------------
/coding-problems/17-10-23/test.txt:
--------------------------------------------------------------------------------
1 | [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
--------------------------------------------------------------------------------
/coding-problems/18-10-23/chaining.py:
--------------------------------------------------------------------------------
1 |
2 | def hash_function(value):
3 | return value%10
4 | def main():
5 | search_keys = [12,23,45,43,42,54,53,65,75,67,87]
6 | n = 11
7 | hash_table = [[] for i in range(n)]
8 | for value in search_keys:
9 | hash_value = hash_function(value)
10 | hash_table[hash_value].append(value)
11 | print(hash_table)
12 | main()
13 |
--------------------------------------------------------------------------------
/coding-problems/18-10-23/linear_probing.py:
--------------------------------------------------------------------------------
1 | def get_hashed_value(value):
2 | return value%10
3 |
4 | def get_next_available_index(hash_table,current_index):
5 | for i in range(current_index,len(hash_table)):
6 | if hash_table[i] == 0:
7 | return i
8 | elif i == len(hash_table)-1:
9 | i = 0
10 |
11 |
12 |
13 |
14 | def main():
15 | search_key = [12,32,45,34,65,78,90,112]
16 | n = 10
17 | hash_table = [0 for i in range(n)]
18 |
19 | for key in search_key:
20 | current_index = get_hashed_value(key)
21 | if hash_table[current_index] == 0:
22 | hash_table[current_index] = key
23 | else:
24 | next_index = get_next_available_index(hash_table,current_index)
25 | hash_table[next_index] = key
26 |
27 | print(hash_table)
28 |
29 | main()
--------------------------------------------------------------------------------
/coding-problems/19-10-23/Encapsulation.py:
--------------------------------------------------------------------------------
1 | class Encapsulation:
2 | def __init__(self):
3 | self.name = "Sudhanshu Kumar"
4 | self.age = "25"
5 | def get_name(self):
6 | print(self.name)
7 | def set_name(self,value):
8 | self.name = value
9 |
10 | obj = Encapsulation()
11 | obj.get_name()
--------------------------------------------------------------------------------
/coding-problems/19-10-23/Father.py:
--------------------------------------------------------------------------------
1 | class Father:
2 | def
3 | (self):
4 | print("gettinng a lot of money")
--------------------------------------------------------------------------------
/coding-problems/19-10-23/Son.py:
--------------------------------------------------------------------------------
1 | from Father import Father
2 |
3 | def get_money_from_father():
4 | father = Father()
5 | father.get_money()
6 |
7 | get_money_from_father()
--------------------------------------------------------------------------------
/coding-problems/19-10-23/__pycache__/Father.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meh-sudhanshu/python_practice_codes/7c751376d56a841aa8a4baafee54e13c709518a5/coding-problems/19-10-23/__pycache__/Father.cpython-312.pyc
--------------------------------------------------------------------------------
/coding-problems/19-10-23/inheritance.py:
--------------------------------------------------------------------------------
1 | class Animal:
2 | def number_of_legs(self):
3 | print("defualt number of legs")
4 | class FourLegAnimals:
5 | def number_of_legs(self):
6 | print(4)
7 | class Cat(FourLegAnimals,Animal):
8 | def number_of_ear(self):
9 | print("2 ears")
10 | cat = Cat()
11 | cat.number_of_legs()
12 | cat.number_of_ear()
13 |
--------------------------------------------------------------------------------
/coding-problems/19-10-23/polymorphism.py:
--------------------------------------------------------------------------------
1 |
2 | class CookWork:
3 | def do_the_work(self):
4 | print("cooking food")
5 | class RooberyWork:
6 | def do_the_work(self):
7 | print("It time for the robbery")
8 | def do_the_work(work):
9 | work.do_the_work()
10 |
11 | cook_work = CookWork()
12 | robbery_work = RooberyWork()
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/coding-problems/19-10-23/quadratic_probing.py:
--------------------------------------------------------------------------------
1 | def hash_fn(value):
2 | return value%10
3 |
4 | def probe(hash_table,ci):
5 | probe_number = 1
6 | while hash_table[ci] != -1:
7 | ci = ci + probe_number**2
8 | if ci >= len(hash_table):
9 | ci = ci%10
10 | if hash_table[ci] == -1:
11 | return ci
12 | else:
13 | probe_number+=1
14 | def quadratic_probing(search_keys,n):
15 | hash_table = [-1 for i in range(n)]
16 | for key in search_keys:
17 | ci = hash_fn(key)
18 | if hash_table[ci] == -1:
19 | hash_table[ci] = key
20 | else:
21 | ni = probe(hash_table,ci)
22 | hash_table[ni] = key
23 | return hash_table
24 |
25 |
26 | def main():
27 | search_keys = [34,54,65,78,32,98]
28 | n = 10
29 | hash_table = quadratic_probing(search_keys,n)
30 | print(hash_table)
31 |
32 |
33 | main()
--------------------------------------------------------------------------------
/coding-problems/19-10-23/set_bits.py:
--------------------------------------------------------------------------------
1 | def get_number_of_set_bits(n):
2 | count = 0
3 | while n > 0:
4 | if n%2 == 1:
5 | count+=1
6 | n = n>>1
7 | else:
8 | n = n>>1
9 | return count
10 |
11 | def main():
12 | print(get_number_of_set_bits(15))
13 | main()
--------------------------------------------------------------------------------
/cseab/28-05-2024/MissingNumber.py:
--------------------------------------------------------------------------------
1 | def getMissingNumber(n,arr):
2 | ans = 0
3 | for i in range(1,n+1):
4 | ans = ans^i
5 | for i in range(len(arr)):
6 | ans = ans^arr[i]
7 | return ans
--------------------------------------------------------------------------------
/ece/01-05-2024/ClimbStairs.py:
--------------------------------------------------------------------------------
1 | def getCount(n):
2 | if dp[n] != -1:
3 | return dp[n]
4 | if n == 1 or n==2:
5 | dp[n] = n
6 | return n
7 | ans1 = getCount(n-1)
8 | ans2 = getCount(n-2)
9 | dp[n-1] = ans1
10 | dp[n-2] = ans2
11 | return ans1+ans2
12 |
13 | n = 10
14 | dp = [-1 for i in range(n+1)]
15 | ans = getCount(n,dp)
--------------------------------------------------------------------------------
/ece/01-05-2024/TraceDiagonally.py:
--------------------------------------------------------------------------------
1 | def trace(arr):
2 | n = len(arr)
3 | i,j = 0,0
4 | while j < n:
5 | i = 0
6 | jFlag = j
7 | while jFlag",des)
6 | toh(n-1,aux,des,src)
7 | toh(3,"A","C","B")
--------------------------------------------------------------------------------
/ece/03-04-2024/TwoPointer.py:
--------------------------------------------------------------------------------
1 | def isPairExist(a,t):
2 | a.sort()
3 | i,j = 0, len(a)-1
4 | while i t: j-=1
8 | return False
9 |
10 | def main():
11 | arr = [-2,4,1,5,7,-89,56,87]
12 | target = 600
13 | print(isPairExist(arr,target))
14 | main()
--------------------------------------------------------------------------------
/ece/04-04-2024/KadanesAlgo.py:
--------------------------------------------------------------------------------
1 | def kadanesAlgo(arr):
2 | ans = float("-inf")
3 | cts = 0
4 | for i in range(len(arr)):
5 | cts+=arr[i]
6 | if cts > ans: ans = cts
7 | if cts < 0: cts = 0
8 | return ans
9 |
10 | def main():
11 | arr = [-3,-4,-1,-6,-4,-5,-7,-9,-3,-4,-6]
12 | print(kadanesAlgo(arr))
13 | main()
14 |
15 |
--------------------------------------------------------------------------------
/ece/04-04-2024/SlidingWindow.py:
--------------------------------------------------------------------------------
1 | def getMaximumWindowSum(arr,ws):
2 | i,j = 0, ws-1
3 | ans = float("-inf")
4 | ps = 0
5 | si, ei = -1, -1
6 | while j ans :
16 | ans = cs
17 | si = i
18 | ei = j
19 | i+=1
20 | j+=1
21 | return ans,i,j
22 | def main():
23 | arr = [2,-9,8,-1,-3,5,16,-3]
24 | ws = 3
25 | print(getMaximumWindowSum(arr,ws))
26 | main()
--------------------------------------------------------------------------------
/ece/18-04-2024/PrefixSum.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [3,-1,2,0,5,9,6,7]
3 | queries = [[0,2],[1,4],[3,5],[4,7]]
4 | ps = [0 for i in range(len(arr))]
5 | for i in range(len(arr)):
6 | if i == 0:
7 | ps[i] = arr[i]
8 | else:
9 | ps[i] = arr[i]+ps[i-1]
10 | for q in queries:
11 | si,ei = q[0],q[1]
12 | if si == 0: print(ps[ei])
13 | else: print(ps[ei]-ps[si-1])
14 | main()
--------------------------------------------------------------------------------
/ece/24-04-2024/Palindrome.py:
--------------------------------------------------------------------------------
1 | def isPalindromeIteratively(_str):
2 | i,j = 0, len(_str)-1
3 | while i < j:
4 | if _str[i] != _str[j]:
5 | return False
6 | i+=1
7 | j-=1
8 | return True
9 |
10 | def isPalindrome(_str):
11 | if len(_str) == 0 or len(_str) == 1:
12 | return True
13 | if _str[0] != _str[-1]:
14 | return False
15 | subStr = _str[1:len(_str)-1]
16 | return isPalindrome(subStr)
--------------------------------------------------------------------------------
/mlr-online-batch/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.REPL.enableREPLSmartSend": false
3 | }
--------------------------------------------------------------------------------
/mlr-online-batch/BinarySearch.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def binarySearch(arr,searchValue):
5 | i,j = 0, len(arr)-1
6 | while i<=j:
7 | mid = (i+j)//2
8 | if arr[mid] == searchValue:
9 | return True
10 | if arr[mid] > searchValue:
11 | j = mid-1
12 | if arr[mid] < searchValue:
13 | i = mid+1
14 | return False
15 |
16 |
17 |
18 | def main():
19 | # sorted array
20 | arr = [-12,-3,4,5,12,32,42,56,67,87,98]
21 | searchValue = 3200
22 | ans = binarySearch(arr,searchValue)
23 | print(ans)
24 |
25 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/IsPowerOf2.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def isPowerOf2(num):
5 | ans = num & (num-1)
6 | if ans == 0:
7 | return True
8 | return False
9 |
10 |
11 |
12 | def main():
13 | num = 9
14 | ans = isPowerOf2(num)
15 | print(ans)
16 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/Kadanes.py:
--------------------------------------------------------------------------------
1 |
2 | def getMaximumSubarraySum(arr):
3 | ans = float("-inf")
4 | sum = 0
5 | for i in range(len(arr)):
6 | ele = arr[i]
7 | sum += ele
8 | if sum > ans:
9 | ans = sum
10 | if sum < 0:
11 | sum = 0
12 | return ans
13 |
14 |
15 |
16 | def main():
17 | arr = [-3,8,2,1,-3,-9,-19,2,3,8,3,-9,2,1]
18 | ans = getMaximumSubarraySum(arr)
19 | print(ans)
20 |
21 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/MissingNumber.py:
--------------------------------------------------------------------------------
1 | def getMissingNumberByMath(n,arr):
2 | ans = (n*(n+1)//2) - sum(arr)
3 | return int(ans)
4 |
5 | def getMissingNumberByDictionary(n,arr):
6 | _dict = {}
7 | for e in arr:
8 | _dict[e] = 1
9 | for i in range(1,n+1):
10 | if i not in _dict:
11 | return i
12 |
13 | def getMissingNumberByXor(n,arr):
14 | ans = 0
15 | for i in range(1,n+1): ans = ans^i
16 | for e in arr: ans = ans^e
17 | return ans
18 |
19 |
20 |
21 |
22 | def main():
23 | n = 6
24 | arr = [1,6,5,3,2]
25 | ans1 = getMissingNumberByMath(n,arr)
26 | ans2 = getMissingNumberByDictionary(n,arr)
27 | ans3 = getMissingNumberByXor(n,arr)
28 | print(ans1,ans2,ans3)
29 |
30 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/Queries.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getQueiresAns(arr,queries):
4 | ans = []
5 | n = len(arr)
6 | prefixSum = [0 for i in range(n)]
7 | for i in range(n):
8 | if i == 0:
9 | prefixSum[i] = arr[i]
10 | else:
11 | prefixSum[i] = prefixSum[i-1]+arr[i]
12 | for query in queries:
13 | si = query[0]
14 | ei = query[1]
15 | if si == 0:
16 | ans.append(prefixSum[ei])
17 | else:
18 | ans.append(prefixSum[ei]-prefixSum[si-1])
19 | return ans
20 |
21 |
22 | def main():
23 | arr = [3,8,0,-3,2,3,7]
24 | queries = [[1,4],[2,5],[0,6]]
25 | ans = getQueiresAns(arr,queries)
26 | print(ans)
27 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/SubarraySum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def getMaximumSubarraySumOfSizeK(arr,k):
5 | i = 0
6 | j = k-1
7 | ans = float("-inf")
8 | sum = 0
9 | while j < len(arr):
10 | if i == 0:
11 | for l in range(i,j+1):
12 | sum = sum + arr[l]
13 | else:
14 | sum = sum - arr[i-1] + arr[j]
15 | i+=1
16 | j+=1
17 | if sum > ans:
18 | ans = sum
19 | return ans
20 |
21 |
22 |
23 |
24 |
25 |
26 | def main():
27 | arr = [-11,2,6,-2,6,8,-4,32,-56,-32]
28 | k = 3
29 | ans = getMaximumSubarraySumOfSizeK(arr,k)
30 | print(ans)
31 |
32 | main()
33 |
--------------------------------------------------------------------------------
/mlr-online-batch/TargetSum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def isPairExist(arr,target):
4 | arr.sort() #nlogn
5 | i,j = 0,len(arr)-1
6 | while i < j: #n
7 | _sum = arr[i]+arr[j]
8 | if _sum == target:
9 | return True
10 | if _sum > target:
11 | j = j -1
12 | if _sum < target:
13 | i = i+1
14 | return False
15 |
16 |
17 |
18 |
19 |
20 | def main():
21 | arr = [3,4,25,-3,-6,34,76,12,-12]
22 | target = 90
23 | ans = isPairExist(arr,target)
24 | print(ans)
25 | main()
--------------------------------------------------------------------------------
/mlr-online-batch/TwoUnique.py:
--------------------------------------------------------------------------------
1 |
2 | def getFirstSetBitPos(num):
3 | ans = 1
4 | while num%2 != 1:
5 | num = num >> 1
6 | ans+=1
7 | return ans
8 | def getIthBit(n,i):
9 | n = n>>(i-1)
10 | if n%2 == 0:
11 | return 0
12 | else:
13 | return 1
14 |
15 |
16 | def getAnsByXor(arr):
17 | wholeXor = 0
18 | for e in arr: wholeXor = wholeXor ^ e
19 | pos = getFirstSetBitPos(wholeXor)
20 | ans1, ans2 = 0, 0
21 | for e in arr:
22 | if getIthBit(e,pos) == 1:
23 | ans1 = ans1 ^ e
24 | else:
25 | ans2 = ans2 ^ e
26 | return ans1,ans2
27 |
28 |
29 |
30 |
31 |
32 |
33 | def main():
34 | arr = {2,7,2,17,3,3,6,6}
35 | ans = getAnsByXor(arr)
36 | print(ans)
37 |
38 | main()
--------------------------------------------------------------------------------
/noNotebookNoPen/02-01-24/BinarySearch.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def binarySearch(arr,ele):
4 | low, high = 0, len(arr)-1
5 | while low < high:
6 | mid = (low+high) // 2
7 | if arr[mid] == ele:
8 | return True
9 | if arr[mid] > ele:
10 | high = mid-1
11 | else:
12 | low = mid+1
13 | return False
14 |
15 |
16 |
17 | arr = [89,23,-23,-45,98,3,6,78,98,-22,-54,76]
18 | arr.sort()
19 | print(binarySearch(arr,78))
20 | # for i in range(100):
21 | # print(binarySearch(arr,i+1))
--------------------------------------------------------------------------------
/noNotebookNoPen/02-01-24/PrioritySum.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def prioritySum(arr,priorityArray):
4 | arr.sort()
5 | priority = 1
6 | ans = 0
7 | for i in range(len(arr)-1,0,-1):
8 | if priority in priorityArray:
9 | ans+=arr[i]
10 | if arr[i] != arr[i-1]:
11 | priority+=1
12 | return ans
--------------------------------------------------------------------------------
/noNotebookNoPen/02-01-24/SmallestMissingNumber.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def fingSmallestMissingNumber(arr):
4 | arr.sort()
5 | if arr[0] != 0:
6 | return 0
7 | for i in range(len(arr)):
8 | if i == len(arr)-1:
9 | return arr[i]
10 | if arr[i+1] != arr[i]+1:
11 | return arr[i]+1
12 |
--------------------------------------------------------------------------------
/noNotebookNoPen/02-04-24/TwoPointer.py:
--------------------------------------------------------------------------------
1 | def isPairExist(arr,target):
2 | arr.sort()
3 | i = 0
4 | j = len(arr)-1
5 | while i target: j-=1
8 | if arr[i]+arr[j] < target: i+=1
9 | return False
10 |
11 | def main():
12 | arr = [-3,5,2,1,0,-6,9,5]
13 | target = 7
14 | ans = isPairExist(arr,target)
15 | print(ans)
16 | main()
--------------------------------------------------------------------------------
/noNotebookNoPen/08-01-24/IsPalindromeUsingStack.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def isPalindrome(string):
4 | stack = []
5 | for i in range(len(string)):
6 | stack.append(string[i])
7 | for i in range(len(string)):
8 | if string[i] != stack.pop():
9 | return False
10 | return True
11 |
12 | print(isPalindrome("MadaMhvhv"))
13 |
--------------------------------------------------------------------------------
/noNotebookNoPen/08-01-24/Stack.py:
--------------------------------------------------------------------------------
1 | stack = []
2 |
3 | for i in range(10):
4 | stack.append(i)
5 |
6 | print(len(stack))
7 | print(stack.pop())
8 | print(stack.top())
9 | print(len(stack ))
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/noNotebookNoPen/08-01-24/ValidParanthesis.py:
--------------------------------------------------------------------------------
1 | # "(((())))"
2 | # "(()"
3 | # ")(()))(("
4 | # ")("
5 |
6 | def isValid(string):
7 | stack = []
8 | for i in range(len(string)):
9 | if string[i] == "(":
10 | stack.append("(")
11 | elif string[i] == ")" and len(stack) == 0:
12 | return False
13 | else:
14 | stack.pop()
15 | return len(stack) == 0
16 | print(isValid("((())"))
--------------------------------------------------------------------------------
/noNotebookNoPen/09-01-24/AllPermutation.py:
--------------------------------------------------------------------------------
1 |
2 | # arr = [1,2,3]
3 | # [1] [[1]]
4 |
5 | # [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]
6 | def permute(arr):
7 | if len(arr) == 1:
8 |
9 | ans = []
10 | for i in range(len(arr)):
11 | fixedEle = arr[i]
12 | subArr = arr[0:i]+arr[i+1:]
13 | allPermutation = permute(subArr) #[[2,3],[3,2]]
14 | for p in allPermutation:
15 | currAns = [fixedEle]+p
16 | ans.append(currAns)
17 | return ans
18 |
19 | arr = [1,2,3]
20 | ans = permute(arr)
21 | print(ans)
--------------------------------------------------------------------------------
/noNotebookNoPen/09-01-24/IsValid.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def isValid(str):
4 | st = []
5 | for ch in str:
6 | if ch == '(' or ch=="{" or ch == "[":
7 | st.append(ch)
8 | elif ch == '}' and st[-1]!="{":
9 | return False
10 | elif ch == ']' and st[-1]!="[":
11 | return False
12 | elif ch == ')' and st[-1]!="(":
13 | return False
14 | elif ch == ")" and st[-1] =="(":
15 | st.pop()
16 | elif ch == "]" and st[-1] =="[":
17 | st.pop()
18 | elif ch == "}" and st[-1] =="{":
19 | st.pop()
20 | return len(st) == 0
21 |
22 | print(isValid("[[{{(()}]]"))
23 |
24 |
--------------------------------------------------------------------------------
/noNotebookNoPen/09-01-24/Queue.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | queue = []
4 | for i in range(10):
5 | queue.append(i)
6 |
7 | print(queue.pop(0),queue[0])
--------------------------------------------------------------------------------
/noNotebookNoPen/09-01-24/RotateStack.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | stack = []
4 | stack.append(2)
5 | stack.append(8)
6 | stack.append(9)
7 | stack.append(-3)
8 | stack.append(5)
9 | stack.append(12)
10 | pointer = 3
11 | st1 = []
12 | st2 = []
13 | top = len(stack)-pointer
14 | while top!=0:
15 | st1.append(stack.pop())
16 | top-=1
17 | while len(stack)!=0:
18 | st2.append(stack.pop())
19 | while len(st1)!=0:
20 | stack.append(st1.pop())
21 | while len(st2)!=0:
22 | stack.append(st2.pop())
23 |
24 | print(stack)
25 |
26 | # ((()))
27 |
28 | # } { ] [ ) {
--------------------------------------------------------------------------------
/noNotebookNoPen/11-12-23/BitManipulation.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def flipIthBit(num,i):
4 | mask = 1<<(i-1)
5 | num = num ^ mask
6 | return num
7 |
--------------------------------------------------------------------------------
/noNotebookNoPen/11-12-23/MinOperation.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getMinimumOperation(arr):
4 | wholeXor = 0
5 | isAnsPossible = -1
6 | ans = float('+inf')
7 | for e in arr:
8 | wholeXor = wholeXor ^ e
9 | for e in arr:
10 | exceptThisElementXor = wholeXor ^ e
11 | if exceptThisElementXor > e:
12 | isAnsPossible = 1
13 | currAns = exceptThisElementXor - e
14 | if currAns < ans:
15 | ans = currAns
16 | if isAnsPossible == -1:
17 | return -1
18 | return ans
19 |
--------------------------------------------------------------------------------
/noNotebookNoPen/11-12-23/MissingNumber.py:
--------------------------------------------------------------------------------
1 |
2 | def getMissingNumber(n,arr):
3 | ans = 0
4 | for i in range(1,n+1):
5 | ans = ans^i
6 | for e in arr:
7 | ans = ans^e
8 | return ans
9 |
10 |
11 |
12 | n = 10
13 | arr = [1,4,3,2,6,7,8,9,10]
14 |
15 | print(getMissingNumber(n,arr))
--------------------------------------------------------------------------------
/noNotebookNoPen/11-12-23/TwoUniqueNumber.py:
--------------------------------------------------------------------------------
1 | def getFirstSetBitPosition(num):
2 | ans = 1
3 | while num%2 == 0:
4 | ans+=1
5 | num = num>>1
6 | return ans
7 |
8 | def isIthBitSet(num,i):
9 | num = num>>(i-1)
10 | return num%2 == 1
11 |
12 |
13 | def getBothUniqueNumber(arr):
14 | ans = 0
15 | ans1, ans2 = 0, 0
16 | for e in arr:
17 | ans = ans^e
18 | pos = getFirstSetBitPosition(ans)
19 |
20 | for e in arr:
21 | if isIthBitSet(e,pos) == True:
22 | ans1 = ans1^e
23 | else:
24 | ans2 = ans2^e
25 | print(ans1)
26 | print(ans2)
27 |
28 |
29 |
30 |
31 |
32 | arr = [1,2,3,6,5,1,2,3,5,7]
33 | getBothUniqueNumber(arr)
--------------------------------------------------------------------------------
/noNotebookNoPen/11-12-23/UniqueNumber.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getUniqueNumber(arr):
4 | ans = 0
5 | for e in arr:
6 | ans = ans^e
7 | return ans
8 |
9 | arr = [2,2,3,4,3]
10 | print(getUniqueNumber(arr))
--------------------------------------------------------------------------------
/noNotebookNoPen/12-12-23/SlidingWindow.py:
--------------------------------------------------------------------------------
1 | def getMaximumSubarraySumOfSizek(arr,k):
2 | i,j = 0,k-1
3 | ps = 0
4 | ans = float("-inf")
5 | while j < len(arr):
6 | if i==0:
7 | currSum = 0
8 | for l in range(i,j+1):
9 | currSum= currSum + arr[l]
10 | ps = currSum
11 | else:
12 | currSum = ps - arr[i-1]+arr[j]
13 | ps = currSum
14 | i+=1
15 | j+=1
16 | ans = max(ans,currSum)
17 | return ans
18 |
19 |
20 |
21 | arr = [-3,4,-12,34,-67-54]
22 | k = 3
23 | print(getMaximumSubarraySumOfSizek(arr,k))
--------------------------------------------------------------------------------
/noNotebookNoPen/12-12-23/TargetSum.py:
--------------------------------------------------------------------------------
1 | def isPairExist(arr,target):
2 | arr.sort()
3 | i,j = 0,len(arr)-1
4 | while i target: j-=1
8 | return False
9 |
10 | arr = [-3,6,7,12,13,-89,34,54,76,58]
11 | target = 1100
12 | print(isPairExist(arr,target))
13 |
--------------------------------------------------------------------------------
/noNotebookNoPen/18-12-23/Kadanes.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getMaximumSubarraySum(arr):
4 | ans = float("-inf")
5 | cs = 0
6 | for i in range(len(arr)):
7 | if cs < 0:
8 | cs = 0
9 | else:
10 | if arr[i] >=0:
11 | cs += arr[i]
12 | if arr[i] < 0:
13 | ans = max(ans,cs)
14 | cs+=arr[i]
15 | if max(cs,ans) == 0:
16 | arr.sort()
17 | return arr[-1]
18 | return max(cs,ans)
19 |
20 | arr = [-3,-9,-2,-11,-8,-7,-6,-5,-13]
21 | print(getMaximumSubarraySum(arr))
--------------------------------------------------------------------------------
/noNotebookNoPen/18-12-23/MergeSortedArray.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def mergeTwoSortedArray(arr1,arr2):
4 | n1,n2 = len(arr1), len(arr2)
5 | n = n1+n2
6 | ans = [0 for i in range(n)]
7 | i,j,k = 0,0,0
8 | while i 0:
10 | arr[j] = stack.pop()
11 | j+=1
12 | while len(queue) > 0:
13 | arr[j] = queue.pop(0)
14 | j+=1
15 | return arr
16 |
17 |
18 | arr = [3,2,4,5,6,7,8,9]
19 | i = 5
20 | print(rotateArray(arr,i))
--------------------------------------------------------------------------------
/noNotebookNoPen/19-12-23/IsPalindrome.py:
--------------------------------------------------------------------------------
1 | def isPalindrome(str):
2 | if len(str) == 0 or len(str)==1:
3 | return True
4 | if str[0] != str[-1]:
5 | return False
6 | subStr = str[1:len(str)-1]
7 | return isPalindrome(subStr)
8 |
9 | print(isPalindrome("MadaMcsc"))
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/04-03-2024/Count.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | def count(n):
5 | ans = 0
6 | for i in range(1,n+1):
7 | i = str(i)
8 | c1 = i.count('1')
9 | c7 = i.count('7')
10 | ans+=(c1+c7)
11 | return ans
12 |
13 | print(count(11))
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/04-03-2024/Pattern.py:
--------------------------------------------------------------------------------
1 | def pattern1(n):
2 | for i in range(1,n+1):
3 | j = 1
4 | ch = 'A'
5 | while j<=i:
6 | j+=1
7 | print(ch,end=" ")
8 | ch = chr(ord(ch)+1)
9 | if ch == 'Z':
10 | ch = 'A'
11 | print()
12 |
13 | def pattern2(n):
14 | countOfChar = 0
15 | for i in range(1,n+1):
16 | j = 1
17 | ch = 'A'
18 | for k in range(countOfChar):
19 | print(" ",end=" ")
20 | while j<=i:
21 | j+=1
22 | print(ch,end=" ")
23 | countOfChar+=1
24 | ch = chr(ord(ch)+1)
25 | if ch == 'Z':
26 | ch = 'A'
27 | print()
28 | def pattern3(n):
29 | space = n-1
30 | char = 1
31 | for i in range(n):
32 | ch = 'A'
33 | for j in range(space):
34 | print(" ",end=" ")
35 | for j in range(char):
36 | print(ch,end=" ")
37 | ch = chr(ord(ch)+1)
38 | print()
39 | char+=2
40 | space-=1
41 |
42 |
43 | pattern3(4)
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/05-03-2024/Array.py:
--------------------------------------------------------------------------------
1 | # arr = [0]*10
2 | # print(arr)
3 |
4 |
5 | # # len --- used to find the length of array
6 | # print(len(arr),"length of array")
7 |
8 | # # append --> use to insert a value at the end of the array
9 | # arr.append(10)
10 | # print(arr," 10 appended to the array")
11 |
12 | # removedValue = arr.pop()
13 | # print(removedValue, "gets popped")
14 | # print(arr)
15 | # removedValue = arr.pop(5)
16 | # print(removedValue, " gets popped")
17 | # print(arr)
18 |
19 | # arr = [100]+arr
20 | # print(arr , '100 got appended')
21 |
22 | # def printArray(arr):
23 | # for row in arr:
24 | # for ele in row:
25 | # print(ele,end = " ")
26 | # print()
27 |
28 |
29 | # arr1 = [[0 for i in range(4)] for j in range(5)]
30 | # #printArray(arr1)
31 | # arr1[1][2] = 100
32 | #printArray(arr1)
33 |
34 |
35 | # arr2 = [[0]*5]*4
36 | # printArray(arr2)
37 | # arr2[2][1] = 100
38 | # print()
39 | # print()
40 | # print()
41 | # print("-------------updated array------------------")
42 | # printArray(arr2)
43 |
44 |
45 | arr = [[i for i in range(5)] for j in range(4)]
46 |
47 | for i in range(5):
48 | for j in range(4):
49 | print(arr[j][i],end=" ")
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/08-04-2024/Kadanes.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-3,1,2,-1,-5,2,6,9,-1]
3 | ans = float("-inf")
4 | cts = 0
5 | for i in range(len(arr)):
6 | cts = cts+arr[i]
7 | if cts > ans:
8 | ans = cts
9 | if cts < 0:
10 | cts = 0
11 | print(max(ans,cts))
12 | main()
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/08-04-2024/SlidingWindow.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [-2,4,1,2,-5,-3,-5,60,4,-1,4,2,-5]
3 | ws = 4
4 | i,j = 0, ws-1
5 | ans = float("-inf")
6 | ps = 0
7 | while j < len(arr):
8 | if i == 0:
9 | cs = sum(arr[i:j+1])
10 | ps = cs
11 | else:
12 | cs = ps-arr[i-1]+arr[j]
13 | ps = cs
14 | i+=1
15 | j+=1
16 | ans = max(ans,cs)
17 | print(ans)
18 |
19 | main()
20 |
21 |
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/11-03-2024/CountFrequency.py:
--------------------------------------------------------------------------------
1 | arr = [1,1,1,2,2,3,1,0,0,4,2,3,2]
2 | low = 0
3 | high = 5
4 | f_arr = [0 for i in range(high+1)]
5 | for i in range(len(arr)):
6 | ele = arr[i]
7 | f_arr[ele]+=1
8 | for i in range(len(f_arr)):
9 | if f_arr[i] != 0:
10 | print(str(i)+" has occured"+str(f_arr[i])+" times")
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/11-03-2024/Remove.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | arr = list(map(int,input().split()))
4 | num = int(input())
5 | for i in range(len(arr)):
6 | if arr[i] == num:
7 | arr.remove(arr[i])
8 | print(arr)
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/11-03-2024/ReverseArray.py:
--------------------------------------------------------------------------------
1 |
2 | arr = list(map(int,input().split()))
3 | i, j = 0, len(arr)-1
4 | while i < j:
5 | temp = arr[i]
6 | arr[i] = arr[j]
7 | arr[j] = temp
8 | i+=1
9 | j-=1
10 | print(arr)
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/12-03-2024/Fib.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def getSumTillN(n):
4 | if n<=0:return "Invalid input"
5 | if n==1: return 0
6 | if n==2: return 1
7 | a,b = 0,1
8 | _sum = a+b
9 | for i in range(3,n+1):
10 | _next = a+b
11 | _sum+=_next
12 | a = b
13 | b = _next
14 | return _sum
15 |
16 | print(getSumTillN(10))
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/12-03-2024/Function.py:
--------------------------------------------------------------------------------
1 | # def getSum(a,b):
2 | # return a+b
3 |
4 | def greaterOfThree(a,b,c):
5 | return a if a>b and a>c else b if b>a and b>c else c
6 | # print(greaterOfThree(1,2,3))
7 | # addTwoNumbers = lambda(a,b):a+b
8 |
9 |
10 | # def main():
11 | # ans = getSum(20,30)
12 | # print(ans)
13 |
14 | # main()
15 |
16 | def addNumbers(*args):
17 | sum_ = 0
18 | for num in args:
19 | sum_+=num
20 | print(sum_)
21 |
22 | def printObject(**kargs):
23 | print(kargs)
24 |
25 | printObject(name="sudhanshu",height="5ft7inch")
26 |
27 | addNumbers(1,2,3)
--------------------------------------------------------------------------------
/noNotebookNoPen/Next/15-04-2024/Matrix.py:
--------------------------------------------------------------------------------
1 | def main():
2 | arr = [[1,5,8,10],[0,2,6,9],[0,0,3,7],[0,0,0,4]]
3 | n = 4
4 | globalJ = 0
5 | while globalJ1:
26 | return True
27 | info = graph[src]
28 | for i in range(len(info)):
29 | if info[i] != 0:
30 | if i not in visited:
31 | visited.append(i)
32 | flag = isPathExist(i,des,graph,visited)
33 | if flag == True:
34 | return True
35 | return False
36 |
37 | def printAllPaths(src,des,graph,visited,psf,wsf):
38 | global minWeight, maxWeight, longestPath, shortestPath
39 | if src == des:
40 | print(psf,"psfff")
41 | if len(psf)>len(longestPath) or len(longestPath) == 0:
42 | longestPath = psf
43 | if len(shortestPath) == 0 or len(psf) < len(shortestPath):
44 | shortestPath = psf
45 | if wsf > maxWeight: maxWeight = wsf
46 | if wsf < minWeight : minWeight = wsf
47 | info = graph[src]
48 | for i in range(len(info)):
49 | if info[i] != 0:
50 | if i not in visited:
51 | visited.append(i)
52 | printAllPaths(i,des,graph,visited,psf+str(i),wsf+info[i])
53 | visited.remove(i)
54 | # if flag == True:
55 | # return True
56 |
57 | def isCyclic(graph,n,visited):
58 | for i in range(n):
59 | flag = isPathExist(i,i,graph,visited )
60 | if flag == True:
61 | return True
62 | return False
63 |
64 | edges = [[0,2,8],[0,1,-9],[1,3,7],[4,5,56],[5,6,1],
65 | [6,7,69],[7,4,67],[3,2,65],[3,4,8]]
66 |
67 | #nbr = [[1,2],[3],[],[4,2],[5],[6],[7],[4]]
68 |
69 | nodes = 8
70 | graph = buildGraph(nodes,edges)
71 | #printGraph(graph)
72 | visited = []
73 | src = 0
74 | des = 2
75 | visited.append(src)
76 | # #print(isPathExist(src,des,graph,visited))
77 | # printAllPaths(src,des,graph,visited,str(src),0)
78 |
79 | # print(longestPath,"longest")
80 | # print(shortestPath,"shortest")
81 | # print(minWeight,"min-weight")
82 | # print(maxWeight ,"max-weight")
83 |
84 | print(isCyclic(graph,nodes,visited))
85 |
86 |
--------------------------------------------------------------------------------
/pyramid-3-2/01-03-2024/ListGraph.py:
--------------------------------------------------------------------------------
1 |
2 | def buildGraph(edges,n):
3 | graph = [[] for i in range(n)]
4 | for edge in edges:
5 | src = edge[0]
6 | des = edge[1]
7 | graph[src].append(des)
8 | return graph
9 |
10 | edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[4,5],[4,7],[7,6],[5,6]]
11 | n = 8
12 | graph = buildGraph(edges)
13 |
--------------------------------------------------------------------------------
/saturday/AllPermutation.py:
--------------------------------------------------------------------------------
1 |
2 | # [1] --> [[1]]
3 | def permute(arr):
4 | if len(arr) == 1:
5 | return [arr]
6 | ans = []
7 | for i in range(len(arr)):
8 | fixedElement = [arr[i]]
9 | subArray = arr[0:i]+arr[i+1:]
10 | allPermutation = permute(subArray)
11 | for permutation in allPermutation:
12 | ans.append(fixedElement+permutation)
13 |
14 | return ans
15 |
16 |
17 |
18 |
19 | def main():
20 | arr = [1,2,3]
21 | ans = permute(arr)
22 | print(ans)
23 |
24 | main()
25 |
26 |
27 |
--------------------------------------------------------------------------------
/saturday/MergeSortedList.py:
--------------------------------------------------------------------------------
1 | def mergeList(arr1, arr2):
2 | n = len(arr1)+len(arr2)
3 | ans = [0 for i in range(n)]
4 | i,j,k = 0,0,0
5 | while i