mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-28 11:03:57 +08:00
Added Dequeue in Python
This commit is contained in:
45333
other/Dictionary.txt
Normal file
45333
other/Dictionary.txt
Normal file
File diff suppressed because it is too large
Load Diff
18
other/FindingPrimes.py
Normal file
18
other/FindingPrimes.py
Normal file
@ -0,0 +1,18 @@
|
||||
'''
|
||||
-The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value.
|
||||
-Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
|
||||
'''
|
||||
from math import sqrt
|
||||
def SOE(n):
|
||||
check = round(sqrt(n)) #Need not check for multiples past the square root of n
|
||||
|
||||
sieve = [False if i <2 else True for i in range(n+1)] #Set every index to False except for index 0 and 1
|
||||
|
||||
for i in range(2, check):
|
||||
if(sieve[i] == True): #If i is a prime
|
||||
for j in range(i+i, n+1, i): #Step through the list in increments of i(the multiples of the prime)
|
||||
sieve[j] = False #Sets every multiple of i to False
|
||||
|
||||
for i in range(n+1):
|
||||
if(sieve[i] == True):
|
||||
print(i, end=" ")
|
34
other/LinearCongruentialGenerator.py
Normal file
34
other/LinearCongruentialGenerator.py
Normal file
@ -0,0 +1,34 @@
|
||||
__author__ = "Tobias Carryer"
|
||||
|
||||
from time import time
|
||||
|
||||
class LinearCongruentialGenerator(object):
|
||||
"""
|
||||
A pseudorandom number generator.
|
||||
"""
|
||||
|
||||
def __init__( self, multiplier, increment, modulo, seed=int(time()) ):
|
||||
"""
|
||||
These parameters are saved and used when nextNumber() is called.
|
||||
|
||||
modulo is the largest number that can be generated (exclusive). The most
|
||||
efficent values are powers of 2. 2^32 is a common value.
|
||||
"""
|
||||
self.multiplier = multiplier
|
||||
self.increment = increment
|
||||
self.modulo = modulo
|
||||
self.seed = seed
|
||||
|
||||
def next_number( self ):
|
||||
"""
|
||||
The smallest number that can be generated is zero.
|
||||
The largest number that can be generated is modulo-1. modulo is set in the constructor.
|
||||
"""
|
||||
self.seed = (self.multiplier * self.seed + self.increment) % self.modulo
|
||||
return self.seed
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Show the LCG in action.
|
||||
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
|
||||
while True :
|
||||
print lcg.next_number()
|
28
other/anagrams.py
Normal file
28
other/anagrams.py
Normal file
@ -0,0 +1,28 @@
|
||||
import collections, pprint, time, os
|
||||
|
||||
start_time = time.time()
|
||||
print('creating word list...')
|
||||
path = os.path.split(os.path.realpath(__file__))
|
||||
word_list = sorted(list(set([word.strip().lower() for word in open(path[0] + '/words')])))
|
||||
|
||||
def signature(word):
|
||||
return ''.join(sorted(word))
|
||||
|
||||
word_bysig = collections.defaultdict(list)
|
||||
for word in word_list:
|
||||
word_bysig[signature(word)].append(word)
|
||||
|
||||
def anagram(myword):
|
||||
return word_bysig[signature(myword)]
|
||||
|
||||
print('finding anagrams...')
|
||||
all_anagrams = {word: anagram(word)
|
||||
for word in word_list if len(anagram(word)) > 1}
|
||||
|
||||
print('writing anagrams to file...')
|
||||
with open('anagrams.txt', 'w') as file:
|
||||
file.write('all_anagrams = ')
|
||||
file.write(pprint.pformat(all_anagrams))
|
||||
|
||||
total_time = round(time.time() - start_time, 2)
|
||||
print('Done [', total_time, 'seconds ]')
|
49
other/binary_exponentiation.py
Normal file
49
other/binary_exponentiation.py
Normal file
@ -0,0 +1,49 @@
|
||||
"""
|
||||
* Binary Exponentiation for Powers
|
||||
* This is a method to find a^b in a time complexity of O(log b)
|
||||
* This is one of the most commonly used methods of finding powers.
|
||||
* Also useful in cases where solution to (a^b)%c is required,
|
||||
* where a,b,c can be numbers over the computers calculation limits.
|
||||
* Done using iteration, can also be done using recursion
|
||||
|
||||
* @author chinmoy159
|
||||
* @version 1.0 dated 10/08/2017
|
||||
"""
|
||||
|
||||
|
||||
def b_expo(a, b):
|
||||
res = 1
|
||||
while b > 0:
|
||||
if b&1:
|
||||
res *= a
|
||||
|
||||
a *= a
|
||||
b >>= 1
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def b_expo_mod(a, b, c):
|
||||
res = 1
|
||||
while b > 0:
|
||||
if b&1:
|
||||
res = ((res%c) * (a%c)) % c
|
||||
|
||||
a *= a
|
||||
b >>= 1
|
||||
|
||||
return res
|
||||
|
||||
"""
|
||||
* Wondering how this method works !
|
||||
* It's pretty simple.
|
||||
* Let's say you need to calculate a ^ b
|
||||
* RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2
|
||||
* RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even.
|
||||
* Once b is even, repeat the process to get a ^ b
|
||||
* Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1
|
||||
*
|
||||
* As far as the modulo is concerned,
|
||||
* the fact : (a*b) % c = ((a%c) * (b%c)) % c
|
||||
* Now apply RULE 1 OR 2 whichever is required.
|
||||
"""
|
50
other/binary_exponentiation_2.py
Normal file
50
other/binary_exponentiation_2.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""
|
||||
* Binary Exponentiation with Multiplication
|
||||
* This is a method to find a*b in a time complexity of O(log b)
|
||||
* This is one of the most commonly used methods of finding result of multiplication.
|
||||
* Also useful in cases where solution to (a*b)%c is required,
|
||||
* where a,b,c can be numbers over the computers calculation limits.
|
||||
* Done using iteration, can also be done using recursion
|
||||
|
||||
* @author chinmoy159
|
||||
* @version 1.0 dated 10/08/2017
|
||||
"""
|
||||
|
||||
|
||||
def b_expo(a, b):
|
||||
res = 0
|
||||
while b > 0:
|
||||
if b&1:
|
||||
res += a
|
||||
|
||||
a += a
|
||||
b >>= 1
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def b_expo_mod(a, b, c):
|
||||
res = 0
|
||||
while b > 0:
|
||||
if b&1:
|
||||
res = ((res%c) + (a%c)) % c
|
||||
|
||||
a += a
|
||||
b >>= 1
|
||||
|
||||
return res
|
||||
|
||||
|
||||
"""
|
||||
* Wondering how this method works !
|
||||
* It's pretty simple.
|
||||
* Let's say you need to calculate a ^ b
|
||||
* RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2
|
||||
* RULE 2 : IF b is ODD, then ---- a * b = a + (a * (b - 1)) :: where (b - 1) is even.
|
||||
* Once b is even, repeat the process to get a * b
|
||||
* Repeat the process till b = 1 OR b = 0, because a*1 = a AND a*0 = 0
|
||||
*
|
||||
* As far as the modulo is concerned,
|
||||
* the fact : (a+b) % c = ((a%c) + (b%c)) % c
|
||||
* Now apply RULE 1 OR 2, whichever is required.
|
||||
"""
|
55
other/detecting_english_programmatically.py
Normal file
55
other/detecting_english_programmatically.py
Normal file
@ -0,0 +1,55 @@
|
||||
import os
|
||||
|
||||
UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
|
||||
|
||||
def loadDictionary():
|
||||
path = os.path.split(os.path.realpath(__file__))
|
||||
dictionaryFile = open(path[0] + '/Dictionary.txt')
|
||||
englishWords = {}
|
||||
for word in dictionaryFile.read().split('\n'):
|
||||
englishWords[word] = None
|
||||
dictionaryFile.close()
|
||||
return englishWords
|
||||
|
||||
ENGLISH_WORDS = loadDictionary()
|
||||
|
||||
def getEnglishCount(message):
|
||||
message = message.upper()
|
||||
message = removeNonLetters(message)
|
||||
possibleWords = message.split()
|
||||
|
||||
if possibleWords == []:
|
||||
return 0.0
|
||||
|
||||
matches = 0
|
||||
for word in possibleWords:
|
||||
if word in ENGLISH_WORDS:
|
||||
matches += 1
|
||||
|
||||
return float(matches) / len(possibleWords)
|
||||
|
||||
def removeNonLetters(message):
|
||||
lettersOnly = []
|
||||
for symbol in message:
|
||||
if symbol in LETTERS_AND_SPACE:
|
||||
lettersOnly.append(symbol)
|
||||
return ''.join(lettersOnly)
|
||||
|
||||
def isEnglish(message, wordPercentage = 20, letterPercentage = 85):
|
||||
"""
|
||||
>>> isEnglish('Hello World')
|
||||
True
|
||||
|
||||
>>> isEnglish('llold HorWd')
|
||||
False
|
||||
"""
|
||||
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
|
||||
numLetters = len(removeNonLetters(message))
|
||||
messageLettersPercentage = (float(numLetters) / len(message)) * 100
|
||||
lettersMatch = messageLettersPercentage >= letterPercentage
|
||||
return wordsMatch and lettersMatch
|
||||
|
||||
|
||||
import doctest
|
||||
doctest.testmod()
|
18
other/euclidean_gcd.py
Normal file
18
other/euclidean_gcd.py
Normal file
@ -0,0 +1,18 @@
|
||||
# https://en.wikipedia.org/wiki/Euclidean_algorithm
|
||||
|
||||
def euclidean_gcd(a, b):
|
||||
while b:
|
||||
t = b
|
||||
b = a % b
|
||||
a = t
|
||||
return a
|
||||
|
||||
def main():
|
||||
print("GCD(3, 5) = " + str(euclidean_gcd(3, 5)))
|
||||
print("GCD(5, 3) = " + str(euclidean_gcd(5, 3)))
|
||||
print("GCD(1, 3) = " + str(euclidean_gcd(1, 3)))
|
||||
print("GCD(3, 6) = " + str(euclidean_gcd(3, 6)))
|
||||
print("GCD(6, 3) = " + str(euclidean_gcd(6, 3)))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
68
other/frequency_finder.py
Normal file
68
other/frequency_finder.py
Normal file
@ -0,0 +1,68 @@
|
||||
# Frequency Finder
|
||||
|
||||
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
|
||||
englishLetterFreq = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97,
|
||||
'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25,
|
||||
'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36,
|
||||
'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29,
|
||||
'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10,
|
||||
'Z': 0.07}
|
||||
ETAOIN = 'ETAOINSHRDLCUMWFGYPBVKJXQZ'
|
||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||
|
||||
def getLetterCount(message):
|
||||
letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0,
|
||||
'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0,
|
||||
'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0,
|
||||
'Y': 0, 'Z': 0}
|
||||
for letter in message.upper():
|
||||
if letter in LETTERS:
|
||||
letterCount[letter] += 1
|
||||
|
||||
return letterCount
|
||||
|
||||
def getItemAtIndexZero(x):
|
||||
return x[0]
|
||||
|
||||
def getFrequencyOrder(message):
|
||||
letterToFreq = getLetterCount(message)
|
||||
freqToLetter = {}
|
||||
for letter in LETTERS:
|
||||
if letterToFreq[letter] not in freqToLetter:
|
||||
freqToLetter[letterToFreq[letter]] = [letter]
|
||||
else:
|
||||
freqToLetter[letterToFreq[letter]].append(letter)
|
||||
|
||||
for freq in freqToLetter:
|
||||
freqToLetter[freq].sort(key = ETAOIN.find, reverse = True)
|
||||
freqToLetter[freq] = ''.join(freqToLetter[freq])
|
||||
|
||||
freqPairs = list(freqToLetter.items())
|
||||
freqPairs.sort(key = getItemAtIndexZero, reverse = True)
|
||||
|
||||
freqOrder = []
|
||||
for freqPair in freqPairs:
|
||||
freqOrder.append(freqPair[1])
|
||||
|
||||
return ''.join(freqOrder)
|
||||
|
||||
def englishFreqMatchScore(message):
|
||||
'''
|
||||
>>> englishFreqMatchScore('Hello World')
|
||||
1
|
||||
'''
|
||||
freqOrder = getFrequencyOrder(message)
|
||||
matchScore = 0
|
||||
for commonLetter in ETAOIN[:6]:
|
||||
if commonLetter in freqOrder[:6]:
|
||||
matchScore += 1
|
||||
|
||||
for uncommonLetter in ETAOIN[-6:]:
|
||||
if uncommonLetter in freqOrder[-6:]:
|
||||
matchScore += 1
|
||||
|
||||
return matchScore
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
49
other/nested_brackets.py
Normal file
49
other/nested_brackets.py
Normal file
@ -0,0 +1,49 @@
|
||||
'''
|
||||
The nested brackets problem is a problem that determines if a sequence of
|
||||
brackets are properly nested. A sequence of brackets s is considered properly nested
|
||||
if any of the following conditions are true:
|
||||
|
||||
- s is empty
|
||||
- s has the form (U) or [U] or {U} where U is a properly nested string
|
||||
- s has the form VW where V and W are properly nested strings
|
||||
|
||||
For example, the string "()()[()]" is properly nested but "[(()]" is not.
|
||||
|
||||
The function called is_balanced takes as input a string S which is a sequence of brackets and
|
||||
returns true if S is nested and false otherwise.
|
||||
|
||||
'''
|
||||
|
||||
|
||||
def is_balanced(S):
|
||||
|
||||
stack = []
|
||||
open_brackets = set({'(', '[', '{'})
|
||||
closed_brackets = set({')', ']', '}'})
|
||||
open_to_closed = dict({'{':'}', '[':']', '(':')'})
|
||||
|
||||
for i in range(len(S)):
|
||||
|
||||
if S[i] in open_brackets:
|
||||
stack.append(S[i])
|
||||
|
||||
elif S[i] in closed_brackets:
|
||||
if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]):
|
||||
return False
|
||||
|
||||
return len(stack) == 0
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
S = input("Enter sequence of brackets: ")
|
||||
|
||||
if is_balanced(S):
|
||||
print(S, "is balanced")
|
||||
|
||||
else:
|
||||
print(S, "is not balanced")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
14
other/password_generator.py
Normal file
14
other/password_generator.py
Normal file
@ -0,0 +1,14 @@
|
||||
import string
|
||||
import random
|
||||
|
||||
letters = [letter for letter in string.ascii_letters]
|
||||
digits = [digit for digit in string.digits]
|
||||
symbols = [symbol for symbol in string.punctuation]
|
||||
chars = letters + digits + symbols
|
||||
random.shuffle(chars)
|
||||
|
||||
min_length = 8
|
||||
max_length = 16
|
||||
password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
|
||||
print('Password: ' + password)
|
||||
print('[ If you are thinking of using this passsword, You better save it. ]')
|
25
other/tower_of_hanoi.py
Normal file
25
other/tower_of_hanoi.py
Normal file
@ -0,0 +1,25 @@
|
||||
def moveTower(height, fromPole, toPole, withPole):
|
||||
'''
|
||||
>>> moveTower(3, 'A', 'B', 'C')
|
||||
moving disk from A to B
|
||||
moving disk from A to C
|
||||
moving disk from B to C
|
||||
moving disk from A to B
|
||||
moving disk from C to A
|
||||
moving disk from C to B
|
||||
moving disk from A to B
|
||||
'''
|
||||
if height >= 1:
|
||||
moveTower(height-1, fromPole, withPole, toPole)
|
||||
moveDisk(fromPole, toPole)
|
||||
moveTower(height-1, withPole, toPole, fromPole)
|
||||
|
||||
def moveDisk(fp,tp):
|
||||
print('moving disk from', fp, 'to', tp)
|
||||
|
||||
def main():
|
||||
height = int(input('Height of hanoi: '))
|
||||
moveTower(height, 'A', 'B', 'C')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
38
other/word_patterns.py
Normal file
38
other/word_patterns.py
Normal file
@ -0,0 +1,38 @@
|
||||
import pprint, time
|
||||
|
||||
def getWordPattern(word):
|
||||
word = word.upper()
|
||||
nextNum = 0
|
||||
letterNums = {}
|
||||
wordPattern = []
|
||||
|
||||
for letter in word:
|
||||
if letter not in letterNums:
|
||||
letterNums[letter] = str(nextNum)
|
||||
nextNum += 1
|
||||
wordPattern.append(letterNums[letter])
|
||||
return '.'.join(wordPattern)
|
||||
|
||||
def main():
|
||||
startTime = time.time()
|
||||
allPatterns = {}
|
||||
|
||||
with open('Dictionary.txt') as fo:
|
||||
wordList = fo.read().split('\n')
|
||||
|
||||
for word in wordList:
|
||||
pattern = getWordPattern(word)
|
||||
|
||||
if pattern not in allPatterns:
|
||||
allPatterns[pattern] = [word]
|
||||
else:
|
||||
allPatterns[pattern].append(word)
|
||||
|
||||
with open('Word Patterns.txt', 'w') as fo:
|
||||
fo.write(pprint.pformat(allPatterns))
|
||||
|
||||
totalTime = round(time.time() - startTime, 2)
|
||||
print('Done! [', totalTime, 'seconds ]')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
235886
other/words
Normal file
235886
other/words
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user