Essential Python Programming Snippets and Algorithms

Classified in Computers

Written on in English with a size of 3.17 KB

Jabber JID to Email Conversion

def jid2email(jid):
    email = jid[:jid.find('/')]
    return email

if __name__ == '__main__':
    jabber = '[email protected]/quertyy'
    print(jid2email(jabber))

Lists vs. Tuples

Lists are mutable and can be changed by internal operations, whereas tuples are immutable.

Remove Duplicates from String

def remove_dup(string):
    result = []
    for char in string:
        if char not in result:
            result.append(char)
    return ''.join(result)

Identical Character Count

def count_max(in_string):
    d = dict()
    for c in in_string:
        d[c] = d.get(c, 0) + 1
    return max(d.items(), key=lambda x: x[1])

# Using collections
from collections import Counter
def counter_max(in_string):
    return Counter(in_string).most_common(1)[0]

Longest Palindrome

def longest_pal(instr):
    max_palin = ''
    for i in range(len(instr)):
        for width in range(1, len(instr) + 1):
            if i + width <= len(instr):
                sub_str = instr[i:i + width]
                if sub_str == sub_str[::-1]:
                    if len(sub_str) >= len(max_palin):
                        max_palin = sub_str
    return max_palin

File Line Lengths

def get_length(fname):
    return ((i, len(l.strip())) for i, l in enumerate(open(fname)))

# Usage
fname = input()
for i, length in get_length(fname):
    print(i, length)

Ticker Symbol Fetcher

import requests
base_url = 'http://www.google.com'
ticker = input()
url_text = requests.get(base_url + ticker).text
print(url_text)

Anagram Checker

def get_counter_dic(in_str, ignore):
    d = dict()
    for c in in_str.lower():
        if c not in ignore:
            d[c] = d.get(c, 0) + 1
    return d

def anagram(s1, s2):
    ignore = [',', ' ', '_', '-', '!']
    d1 = get_counter_dic(s1, ignore)
    d2 = get_counter_dic(s2, ignore)
    return d1 == d2

File Tail Implementation

from collections import deque
def tail(filename, n):
    return deque(open(filename), n)

log_file = 'tmp/pybook'
print(' '.join(tail(log_file, 4)))

Hashtable List Class

class HList(list):
    def __hash__(self):
        return hash(str(self))

h = HList()
h.append(2)
d = {h: 'a'}
print(d)

Floating Point Precision

1.1 * 3.0 == 3.3 returns False due to precision.

(1.1 * 3.0).hex() # '0x1.a6666667p+1'
(3.3).hex()       # '0x1.a666666p+1'

List Comprehension and Zipping

squares = [i**2 for i in range(10)]
a_list = list(zip(*[iter(squares)]*2))
b_list = list(zip(squares[::2], squares[1::2]))
# Output: [(0, 1), (4, 9), (16, 25), (36, 49), (64, 81)]

Quick Sort Algorithm

def q_sort(L):
    if len(L) <= 1:
        return L
    pivot = L.pop()
    left = [i for i in L if i < pivot]
    right = [i for i in L if i >= pivot]
    return q_sort(left) + [pivot] + q_sort(right)

Related entries: