diff --git a/All_prime.py b/All_prime.py deleted file mode 100644 index b9ef7a6..0000000 --- a/All_prime.py +++ /dev/null @@ -1,19 +0,0 @@ -# Sieve Theorem -# all prime numbers upto n -# (not first n prime numbers) -from math import * - -def all_primes(n): - pr = [True] * (n+1) - pr[0] = False - pr[1] = False - for x in range(2, int(sqrt(n))+1): - if pr[x] == True: - for i in range(x*x,n+1,x): - pr[i] = False - for i in range(n+1): #changed range value from len(pr) to n+1, confirm if it works properly - if pr[i] == True: - print(i, end=" ") - -n = int(input()) -print(all_primes(n)) diff --git a/BubbleSort.py b/BubbleSort.py deleted file mode 100644 index 473dc33..0000000 --- a/BubbleSort.py +++ /dev/null @@ -1,26 +0,0 @@ -# Python program for implementation of Bubble Sort - -def bubbleSort(arr): - n = len(arr) - - # Traverse through all array elements - for i in range(n-1): - # range(n) also work but outer loop will repeat one time more than needed. - - # Last i elements are already in place - for j in range(0, n-i-1): - - # traverse the array from 0 to n-i-1 - # Swap if the element found is greater - # than the next element - if arr[j] > arr[j+1] : - arr[j], arr[j+1] = arr[j+1], arr[j] - -# Driver code to test above -arr = [64, 34, 25, 12, 22, 11, 90] - -bubbleSort(arr) - -print ("Sorted array is:") -for i in range(len(arr)): - print ("%d" %arr[i]), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index e451ceb..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,36 +0,0 @@ -# Contributing - -When contributing to this repository, please make sure that the changes you wish to make consists of an algorithm/concept/adanced DSA implementation -and not a mere program which almost everyone beginning with python knows(like even/odd check). - -However Basic programs are welcomed in another repository of ours to get your journey of Open source contribution -started without the need of in-depth knowledge of programming. if someone is at the beginning to learn programming, you can contribute in -our [Basic programs](https://github.com/Dude-901/basic-programs) repository. -If you want to send in C/Cpp programs, go to [Cpp-Algorithms](https://github.com/Dude-901/Cpp-Algorithms) repository. - -## Pull Request Process - -* Ensure any install or build dependencies are removed before the end of the layer when doing a - build. - -## Code of Conduct -Please make sure that the approach/algorithm/concept whose implementation you are adding is completely your work, not -copy-pasted from somewhere, or adding someone else's work. -**We are strictly against PLAGIARISM** - - -### Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -### Scope - -We aim to develop a repository with a vast set of python algorithmic approaches/implementations. diff --git a/Josephus_problem.py b/Josephus_problem.py deleted file mode 100644 index cc2b074..0000000 --- a/Josephus_problem.py +++ /dev/null @@ -1,20 +0,0 @@ -#Josephus Problem - -# The Josephus problem, where 100 people standing in a circle, 1 kills 2 passes the sword to 3….who survives in the end? - -#Python Solution - -from sys import stdin,stdout - -def Josephus_Prblm(n, k): - if (n == 1): - return 1 - else: - return ((Josephus_Prblm(n - 1, k) + k-1) % n + 1) - -for _ in range(int(stdin.readline())): - N = int(stdin.readline()) - K = int(stdin.readline()) - print(Josephus_Prblm(N,K) - - diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 13697a5..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Tanmay Khandelwal - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Questions/missing_number_in_linear_sequence.py b/Questions/missing_number_in_linear_sequence.py deleted file mode 100644 index b2ddb3e..0000000 --- a/Questions/missing_number_in_linear_sequence.py +++ /dev/null @@ -1,11 +0,0 @@ -mylist = [1, 2, 3, 4, 5, 7, 8, 9, 10] - - -def findmissing(ls, n): - sum1 = (n+1)*n/2 - sum2 = sum(ls) - print(sum1-sum2) - - -findmissing(mylist, 10) - diff --git a/Questions/sum_of_pair_equal_to_given_number.py b/Questions/sum_of_pair_equal_to_given_number.py deleted file mode 100644 index e72857b..0000000 --- a/Questions/sum_of_pair_equal_to_given_number.py +++ /dev/null @@ -1,22 +0,0 @@ -# write a program to find all the pairs of integers whose sum is equal to a given number - -# Things to ask the interviewer before solving -# does array contains only positive ints? -# what if same pair is repeated twice, should we print it again? -# if the reverse pair is acceptable for ex- (4,1) and (1,4) for given sum 5? -# Do we need to print only distinct pairs? is (3,3) is a valid pair for given sum 6? -# How big is the array? - - -def findpairs(nums, target): - for i in range(len(nums)): - for j in range(i+1, len(nums)): - if nums[i] == nums[j]: # don't print for same values - continue - if nums[i] + nums[j] == target: - print(i, j) - - -# arr = [2, 6, 3, 9, 11] -arr = [1, 2, 3, 2, 3, 4, 5, 6] -findpairs(arr, 6) diff --git a/README.md b/README.md deleted file mode 100644 index b11e29a..0000000 --- a/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# **Python-algorithms** -## efficient algorithms for general tasks with good time complexity. - -## To send a Pull-request: -* Check our contribution guidelines in [CONTRIBUTING.md](https://github.com/Dude-901/python-algorithms/blob/master/CONTRIBUTING.md) -* Star and Fork this repo. -* Clone the repo on your local machine using `git clone https://github.com/{your-username}/python-algorithms.git`. -* Create a branch `git checkout -b your_new_branch_name` -* Make required changes then add and commit - `git add.` - `git commit -m "your commit message"` -* Push your changes `git push origin your_new_branch_name` -* Merge and send a Pull-request. - ------------------------------------------------------------------------------------- - - **Referance:** Competetive programming with python - ------------------------------------------------------------------------------------- -#### bitwise operator not {~} : (a = 10 => 1010 (Binary) => ~a = ~1010 = -(1010 + 1) = -(1011) = -11) -#### bitwise operator xor {^} : (n^n = 0), (n^0 = n) -#### bitwise operator rightshift {>>} : (100 >> 2 = 25) -#### bitwise operator leftshift {<<} : (100 << 2 = 400) - -------------------------------------------------------------------------------------- -### sum of first n numbers:O(1) -```python -def sum_total(n): - return int(n*(n+1)/2) -``` -### LCM/GCD:(Euclid's algorithm) -```python -def gcd(a,b): - if a == 0: - return b - return gcd(b%a,a) - -def lcm(a,b): - prod = a*b - hcf = gcd(a,b) - return prod//hcf -``` -### Odd-Even:O(1) -```python -if n&1 == 1: - print('odd') -else: - print('even') -``` -### Leftshift(multiply) / Rightshift(divide) by 2n:O(1) -```python -def multpow(x,y): - return x<>y # x/(2^y) -``` -### Check if a number is power of 2:O(1) -```python -def ispow(n): - if n <= 0: - return False - x = n - y = not(n & (n-1)) - return x and y -``` -### count 1's in binary representation:O(log(n)) -```python -def cntbits(n): - cnt = 0 - while n: - cnt += 1 - n = n & (n-1) - return cnt -``` -### convert int to binary / binary to int:O(1) -```python -def inttobin(n): - return str(bin(n))[2:] - -def bintoint(m): - return int(m,2) -``` -### check which number occurs once(or odd number of times/doesn't has it's unique identical element) in an array:O(n) -```python -def checkpair(arr): # n -> aray - temp = arr[0] - for i in range(1,len(arr)): - temp = temp ^ arr[i] - return temp -``` diff --git a/ShellSort.py b/ShellSort.py deleted file mode 100644 index 4210d27..0000000 --- a/ShellSort.py +++ /dev/null @@ -1,30 +0,0 @@ -def shellSort(arr): - n = len(arr) - gap = n/2 - - while gap > 0: - - for i in range(gap,n): - temp = arr[i] - j = i - while j >= gap and arr[j-gap] >temp: - arr[j] = arr[j-gap] - j -= gap - - arr[j] = temp - gap /= 2 - - -# Driver code to test above -arr = [ 12, 34, 54, 2, 3] - -n = len(arr) -print ("Array before sorting:") -for i in range(n): - print(arr[i]), - -shellSort(arr) - -print ("\nArray after sorting:") -for i in range(n): - print(arr[i]), \ No newline at end of file diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..9da9a02 --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-dinky \ No newline at end of file diff --git a/all_primes_part-2.py b/all_primes_part-2.py deleted file mode 100644 index 3ccc927..0000000 --- a/all_primes_part-2.py +++ /dev/null @@ -1,9 +0,0 @@ -# Eratosthenes application of sieve algorithm -def eratosthenes2(n): - multiples = set() - for i in range(2, n+1): - if i not in multiples: - yield i - multiples.update(range(i*i, n+1, i)) - -primes = list(eratosthenes2(4000000)) diff --git a/binary_search_d3xt3r0.py b/binary_search_d3xt3r0.py deleted file mode 100644 index 0a3d0b9..0000000 --- a/binary_search_d3xt3r0.py +++ /dev/null @@ -1,17 +0,0 @@ -def binary_search(item_list,item): - first = 0 - last = len(item_list)-1 - flag = False - while( first<=last and not flag): - temp = (first + last)//2 - if item_list[temp] == item : - flag = True - else: - if item < item_list[temp]: - last = temp - 1 - else: - first = temp + 1 - return flag - -message = binary_search([4,5,6,8,9], 6) -print(message) \ No newline at end of file diff --git a/combSort.py b/combSort.py deleted file mode 100644 index 36d102a..0000000 --- a/combSort.py +++ /dev/null @@ -1,77 +0,0 @@ -'''Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares -adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble -Sort by using gap of size more than 1. The gap starts with a large value and shrinks by -a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes -more than one inversion counts with one swap and performs better than Bubble Sort.''' - - -# Python program for implementation of CombSort - - -def comb_sort(alist): - def swap(i, j): - alist[i], alist[j] = alist[j], alist[i] - - gap = len(alist) - shrink = 1.3 - - no_swap = False - while not no_swap: - gap = int(gap/shrink) - - if gap < 1: - gap = 1 - no_swap = True - else: - no_swap = False - - i = 0 - while i + gap < len(alist): - if alist[i] > alist[i + gap]: - swap(i, i + gap) - no_swap = False - i = i + 1 - -#TEST CODE -alist = input('Enter the list of numbers separated by space: ').split() -alist = [int(x) for x in alist] -comb_sort(alist) -print('Sorted list: ', end='') -print(alist) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/divisors.py b/divisors.py deleted file mode 100644 index 8f8e8b1..0000000 --- a/divisors.py +++ /dev/null @@ -1,15 +0,0 @@ -from math import * - - -def divisors(n): - div = set() - for i in range(1,int(sqrt(n))+1): - if n%i == 0: - div.add(i) - div.add(n//i) - return list(div) - - -for _ in range(int(input())): - n = int(input()) - print(*divisors(n)) diff --git a/emailchecker_regex.py b/emailchecker_regex.py deleted file mode 100644 index aa1ef07..0000000 --- a/emailchecker_regex.py +++ /dev/null @@ -1,40 +0,0 @@ -# Python program to validate an Email - -# import re module - -# re module provides support -# for regular expressions -import re - -# Make a regular expression -# for validating an Email -regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' -# for custom mails use: '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w+$' - -# Define a function for -# for validating an Email -def check(email): - - # pass the regular expression - # and the string in search() method - if(re.search(regex,email)): - print("Valid Email") - - else: - print("Invalid Email") - - -# Driver Code -if __name__ == '__main__' : - - # Enter the email - email = "dude_tanmay326@gmail.com" - - # calling run function - check(email) - - email = "my.ownsite@ourearth.org" - check(email) - - email = "ankitrai326.com" - check(email) diff --git a/exponentiation.py b/exponentiation.py deleted file mode 100644 index acf2bcf..0000000 --- a/exponentiation.py +++ /dev/null @@ -1,13 +0,0 @@ -'''Efficient approach''' - -def bin_pow(a,n): - res = 1 - while(n>0): - if n&1: - res = res * a - a = a * a - n >>= 1 - return res -print(bin_pow(2101010,32)) #20782597351780148360705447543438026166282198412508937706220746225693908693563681788663888827908012942663696008670876015403914749631306435949260373147394419808970340368320100000000000000000000000000000000 - -''' Time complexity : O(log n) ''' diff --git a/fibonacci/fibonacci_iterative.py b/fibonacci/fibonacci_iterative.py deleted file mode 100644 index 98e97aa..0000000 --- a/fibonacci/fibonacci_iterative.py +++ /dev/null @@ -1,15 +0,0 @@ -from math import * -# Calculates fibonacci sequence -def fibonacci(n): - fibs = [0, 1] - if n <=0: - return [] - elif n == 1: - return fibs[1] - else: - for i in range(2, n): - fibs.append(fibs[-1] + fibs[-2]) - return fibs - -n = int(input("How many terms?")) -print(fibonacci(n)) diff --git a/fibonacci/fibonacci_recursive.py b/fibonacci/fibonacci_recursive.py deleted file mode 100644 index a322f58..0000000 --- a/fibonacci/fibonacci_recursive.py +++ /dev/null @@ -1,11 +0,0 @@ -def fibonacci(n): - assert n >= 0 and n == int(n), 'n should be positive integer' - if n in [0, 1]: - return n - else: - return fibonacci(n-1) + fibonacci(n-2) - - -print("Enter number:", end=" ") -x = int(input()) -print(fibonacci(x)) diff --git a/graph-nodes.py b/graph-nodes.py deleted file mode 100644 index 66b0cb3..0000000 --- a/graph-nodes.py +++ /dev/null @@ -1,25 +0,0 @@ -# return list of all nodes in the graph -from collections import defaultdict - - -def dfs(graph, start, visited, path): - path.append(start) - visited[start] = True - for neighbour in graph[start]: - if not visited[neighbour]: - dfs(graph, neighbour, visited, path) - return path - - -v, e = map(int, input().split()) -graph = defaultdict(list) -for i in range(e): - u, x = input().split() - graph[u].append(x) - graph[x].append(u) - -path = [] -start = 'A' -visited = defaultdict(bool) -traverse = dfs(graph, start, visited, path) -print(traverse) diff --git a/index.md b/index.md new file mode 100644 index 0000000..a3a5a4c --- /dev/null +++ b/index.md @@ -0,0 +1,37 @@ +## Welcome to GitHub Pages + +You can use the [editor on GitHub](https://github.com/Tanmay-901/python-algorithms/edit/gh-pages/index.md) to maintain and preview the content for your website in Markdown files. + +Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files. + +### Markdown + +Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for + +```markdown +Syntax highlighted code block + +# Header 1 +## Header 2 +### Header 3 + +- Bulleted +- List + +1. Numbered +2. List + +**Bold** and _Italic_ and `Code` text + +[Link](url) and ![Image](src) +``` + +For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/). + +### Jekyll Themes + +Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/Tanmay-901/python-algorithms/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file. + +### Support or Contact + +Having trouble with Pages? Check out our [documentation](https://docs.github.com/categories/github-pages-basics/) or [contact support](https://support.github.com/contact) and we’ll help you sort it out. diff --git a/lcm.py b/lcm.py deleted file mode 100644 index a013ed5..0000000 --- a/lcm.py +++ /dev/null @@ -1,22 +0,0 @@ -from math import * - -#Calculates Lowest Common Multiple -def compute_lcm(x, y): - - # Select larger number - if x > y: - larger = x - else: - larger = y - - # Checks if the larger value is divisible by both numbers - while((larger % x != 0) or (larger % y != 0)): - # If not divisible by either number, the larger value is incremented by 1 - larger += 1 - - return larger - -in1 = int(input("Insert 1st number: ")) -in2 = int(input("Insert 2nd number: ")) - -print("LCM of %d and %d is"%(in1, in2), compute_lcm(in1, in2)) \ No newline at end of file diff --git a/prime_check.py b/prime_check.py deleted file mode 100644 index f1c52ee..0000000 --- a/prime_check.py +++ /dev/null @@ -1,19 +0,0 @@ -from math import * - - -def prime(a): - if a==0 or a==1: - return False - if a==2 or a==3: - return True - if a%2==0 or a%3==0: - return False - for i in range(5,int(sqrt(a))+1,4): - if a%i==0 or a%(i+2)==0: - return False - return True - - -for _ in range(int(input())): - n = int(input()) - print(prime(n)) diff --git a/second-largest-num.py b/second-largest-num.py deleted file mode 100644 index 53cef82..0000000 --- a/second-largest-num.py +++ /dev/null @@ -1,18 +0,0 @@ -# Program to find second largest element in list -# Time Complexity : O(N) -# run cmd: python3 second-largest-num.py - -class Solution: - def secondLargest(self, l): - mx=max(l[0],l[1]) - secondmx=min(l[0],l[1]) - n =len(l) - for i in range(2,n): - if l[i]>mx: - secondmx=mx - mx=l[i] - elif l[i]>secondmx and mx != l[i]: - secondmx=l[i] - return secondmx - -print("Second Largest number is :", Solution().secondLargest([12,412,11,42,10,1])) \ No newline at end of file diff --git a/stack/stack_using_linkedlist.py b/stack/stack_using_linkedlist.py deleted file mode 100644 index a23fba9..0000000 --- a/stack/stack_using_linkedlist.py +++ /dev/null @@ -1,66 +0,0 @@ -class Node: - def __int__(self, value=None): - self.value = value - self.next = next - - -class LinkedList: - def __init__(self): - self.head = None - - def __iter__(self): - currnode = self.head - while currnode: - yield currnode - currnode = currnode.next - - -class Stack: - def __init__(self): - self.LinkedList = LinkedList() - - def __str__(self): - values = [str(x.value) for x in self.LinkedList] - return '\n'.join(values) - - def isEmpty(self): - if self.LinkedList.head is None: - return True - else: - return False - - def push(self, value): - node = Node() - node.value = value - node.next = self.LinkedList.head - self.LinkedList.head = node - - def pop(self): - if self.isEmpty(): - print("Stack underflow") - else: - node = self.LinkedList.head.value - self.LinkedList.head = self.LinkedList.head.next - return node - - def peak(self): - if self.isEmpty(): - print("Stack underflow") - else: - node = self.LinkedList.head.value - return node - - def delete(self): - self.LinkedList.head = None - - -customStack = Stack() -print(customStack.isEmpty()) -customStack.push(1) -customStack.push(2) -customStack.push(3) -print(customStack) -print("_________") -print(customStack.pop()) -print("_________") -print(customStack.peak()) diff --git "a/sum_total (\342\210\221n)" "b/sum_total (\342\210\221n)" deleted file mode 100644 index 76f10db..0000000 --- "a/sum_total (\342\210\221n)" +++ /dev/null @@ -1,5 +0,0 @@ -def sum_total(n): - return int(n*(n+1)/2) - - -print(sum_total(10)) diff --git a/tree/BFS_preorder_traversal.py b/tree/BFS_preorder_traversal.py deleted file mode 100644 index eda1184..0000000 --- a/tree/BFS_preorder_traversal.py +++ /dev/null @@ -1,25 +0,0 @@ -class TreeNode: - def __init__(self, data): - self.data = data - self.lnode = None - self.rnode = None - - -def preOrderTraversal(rootNode): - if not rootNode: - return - print(rootNode.data) - preOrderTraversal(rootNode.lnode) - preOrderTraversal(rootNode.rnode) - - -bt = TreeNode("Drinks") -leftchild = TreeNode("hot") -rightchild = TreeNode("cold") -hotchild = TreeNode("Tea") -coldchild = TreeNode("Cola") -leftchild.lnode = hotchild -rightchild.rnode = coldchild -bt.lnode = leftchild -bt.rnode = rightchild -preOrderTraversal(bt) diff --git a/tree/create_tree.py b/tree/create_tree.py deleted file mode 100644 index 0288a83..0000000 --- a/tree/create_tree.py +++ /dev/null @@ -1,30 +0,0 @@ -class TreeNode: - def __init__(self, data, children=[]): - self.data = data - self.children = children - - def __str__(self, level=0): - ret = " " * level + str(self.data) + "\n" - for child in self.children: - ret += child.__str__(level+1) - return ret - - def addchild(self, TreeNode): - self.children.append(TreeNode) - - -tree = TreeNode('Drinks', []) -cold = TreeNode('Cold', []) -hot = TreeNode('Hot', []) -tree.addchild(hot) -tree.addchild(cold) -coffee = TreeNode('Coffee', []) -tea = TreeNode('Tea', []) -cola = TreeNode('Cola', []) -fanta = TreeNode('Fanta', []) -cold.addchild(cola) -cold.addchild(fanta) -hot.addchild(tea) -hot.addchild(coffee) - -print(tree) diff --git a/unweighted-graph.py b/unweighted-graph.py deleted file mode 100644 index a5f2bf0..0000000 --- a/unweighted-graph.py +++ /dev/null @@ -1,14 +0,0 @@ -# part 1- graph theory -# make a dictionaries of all the nodes(vertices) and their linked nodes in the unordered graph -from collections import defaultdict - -graph = defaultdict(list) -v,e = map(int,input().split()) -# v -> no. of vertices -# e -> no. of edges -for i in range(e): - u, v = input().split() - graph[u].append(v) - graph[v].append(u) -for i in graph: - print(i,graph[i])