Python
/
Applications
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Binary Search
➟
➟
Last update: 09-12-2021
Binary search (A)
Make a bisection search (or binary search)
# Binary search
#
# You start in the middle of the list, ...
# then you search the second half.
import os
words = []
file = os.path.dirname(__file__) + "/words.txt"
for line in open(file):
word = line.strip()
words.append(word)
def full_search(words, keyword):
i = 0
for word in words:
i = i + 1
if (word == keyword):
return i
return i
def binary_search(words, keyword, i=0):
i = i + 1
key = len(words) // 2
if words[key] == keyword:
return i
if keyword < words[key]:
words = words[:key]
else:
words = words[key+1:]
i = binary_search(words, keyword, i)
return i
print(len(words)) # 113783
print(full_search(words, "mother")) # 62889
print(binary_search(words, "mother")) # 16
Caesar cypher
Caesar cypher rotates each letter by a number.
# A Caesar cypher is a weak form on encryption:
# It involves "rotating" each letter by a number (shift it through the alphabet)
#
# Example:
# A rotated by 3 is D; Z rotated by 1 is A
# In a SF movie the computer is called HAL, which is IBM rotated by -1
#
# Our function rotate_word() uses:
# ord (char to code_number)
# chr (code to char)
def encrypt(word, no):
rotated = ""
for i in range(len(word)):
j = ord(word[i]) + no
rotated = rotated + chr(j)
return rotated
def decrypt(word, no):
return encrypt(word, -no)
assert encrypt("abc", 3) == "def" # pass
assert encrypt("IBM", -1) == "HAL" # pass
assert decrypt("def", 3) == "abc" # pass
assert decrypt("HAL", -1) == "IBM" # pass
Double letters
Get the words with three consecutive double letters
# Get the words with three consecutive double letters
import os
def has_three_doubles(word):
i = 0
jj = 0
while i < len(word) -1:
if word[i] == word[i+1]:
jj = jj + 1
if jj == 3:
return True
i = i + 2
else:
jj = 0
i = i + 1
return False
assert has_three_doubles("aabbcc") == True
assert has_three_doubles("Mississippi") == False
file = os.path.dirname(__file__) + "/words.txt"
for line in open(file):
word = line.strip()
if has_three_doubles(word):
print(word)
# bookkeeper
# bookkeepers
# bookkeeping
# bookkeepings
➥ Questions github Applications