BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Coding Questions V - 2024

python_logo




Bookmark and Share





bogotobogo.com site search:

What is Hashable? Immutable?

What is Hashable?

Let's start with the key in dictionary. The key of a dictionary should be unique. Internally, the key is transformed by a hash function and become an index to a memory where the value is stored. Suppose, if the key is changed, then it will be pointing somewhere else and we lose the original value the the old key was pointing.

In Python, we can say that the key should be hashable. That's why we always use hashable objects as keys. Hashable objects are integers, floats, strings, tuples, and frozensets.

Immutable object will not change after it has been created, especially in any way that changes the hash value of that object. Objects used as hash keys must be immutable so their hash values remain unchanged. Note that all hashable objects are also immutable objects.


Mutable objects are lists, dictoroaries, and sets.

Don't be surprised at the following code using tuple as a key for a dictionary:

d={}

t1 = (1,2)
t2 = (3,4,5)

d[t1] = 2
d[t2] = 3

print d[t1], d[t2]

Output:

2 3

We rarely use a tuple as a key, but there is no problem because tuple is hashable.

If we use a list as a key, we get the following error:

print d[list(range(2))]

TypeError: unhashable type: 'list'

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python's immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

-from Python glossary




Convert a list to a tuple
t = tuple([0,1,2,3])
print(t)

Output:

(0, 1, 2, 3)




Convert a list to a string
# list of strings
L = ["Imagination", "is", "more", "important", "than", "knowledge"]
print(' '.join(L))

# list of integers
N = [0,1,2,3]
print(''.join(str(n) for n in N))

Output:

Imagination is more important than knowledge
0123




Convert a list to a dictionary
number = ['eins','zwei','drei',1,2,3]
print(dict(zip(number[:3], number[3:])))  

Output:

{'drei': 3, 'eins': 1, 'zwei': 2}

To get the same output from this list, ['eins',1,'zwei',2,'drei',3]:

number = ['eins',1,'zwei',2,'drei',3]
print(dict(zip(number[0::2], number[1::2]))) 

Specially, for this zigzag (on-and-off) type, we can use iter() method, and create list iterator object:

number = ['eins',1,'zwei',2,'drei',3]
i = iter(number)
print(type(i))
print(dict(zip(i,i)))  

We'll get the same output:

<type 'listiterator'>
{'drei': 3, 'eins': 1, 'zwei': 2}




List - append vs extend vs concatenate

While the append() and extend() methods modify the original list, the concatenate ('+') creates a new list:

a = [1,2]
b = [3,4,5]
c = a.append(b) # modifying a
print(a, c)

a = [1,2]
b = [3,4,5]
c = a.extend(b) # modifying a
print(a, c)

a = [1,2]
b = [3,4,5]
c = a + b  # creating a new list
print(a, c)

Output:

[1, 2, [3, 4, 5]] None
[1, 2, 3, 4, 5] None
[1, 2] [1, 2, 3, 4, 5]




Use sorted(list) to keep the original list

The sorted() function returns a new sorted list.

We can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if we don't need the original list, list.sort() is slightly more efficient.

a = [3, 2, 1]

a2 = sorted(a)
print(a, a2)  

a3 = a.sort()
print(a, a3)

Output:

[3, 2, 1] [1, 2, 3]
[1, 2, 3] None

The list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.

Note that both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons:

from operator import itemgetter, attrgetter

guest = [
    ('john', 'A', 15, 170),
    ('clair', 'B', 44, 240),
    ('bell', 'D', 74, 111),
    ('dave', 'C', 10, 164) ]

print(sorted(guest, key = lambda x:x[0]))
print(sorted(guest, key = itemgetter(1)))

class Guest:
  def __init__(self, name, grade, age, weight):
    self.name = name
    self.grade = grade
    self.age = age
    self.weight = weight
  def __repr__(self):
    return repr( (self.name, self.grade, self.age, self.weight) )

g_object = [
    Guest('john', 'A', 15, 170),
    Guest('clair', 'B', 44, 240),
    Guest('bell', 'D', 74, 111),
    Guest('dave', 'C', 10, 164),
 ]

print(sorted(g_object, key = lambda g: g.age))
print(sorted(g_object, key = attrgetter('weight')))

Output:

[('bell', 'D', 74, 111), ('clair', 'B', 44, 240), ('dave', 'C', 10, 164), ('john', 'A', 15, 170)]
[('john', 'A', 15, 170), ('clair', 'B', 44, 240), ('dave', 'C', 10, 164), ('bell', 'D', 74, 111)]
[('dave', 'C', 10, 164), ('john', 'A', 15, 170), ('clair', 'B', 44, 240), ('bell', 'D', 74, 111)]
[('bell', 'D', 74, 111), ('dave', 'C', 10, 164), ('john', 'A', 15, 170), ('clair', 'B', 44, 240)]   




list.count() and Counter()

We have a list : [1,1,2,3,4,5,6,6,6]. Print how many 6s in the list in one-liner:

print([1,1,2,3,4,5,6,6,6].count(6))

There is a Counter() method which is faster:

from collections import Counter
L = [1,1,2,3,4,5,6,6,6]
print(Counter(L))

Output:

Counter({6: 3, 1: 2, 2: 1, 3: 1, 4: 1, 5: 1})

So, we can pass the number as a key to the dictionary to get its count. For example, pass 6 as a key:

print Counter([1,1,2,3,4,5,6,6,6])[6]  # we get 3

We can write a simple version of the Counter() like this:

def myCounter(L):
  import operator
  # initialize dict with 0
  d = dict.fromkeys(L,0)
  # or 
  # d = {x:0 for x in L}
  for l in L:
    d[l] += 1
  # return sorted (by vaule) dict descending order
  return sorted(d.items(), key=operator.itemgetter(1), reverse=True)
  # or using labmda
  # return sorted(d.items(), key = lambda x:x[1], reverse=True)

L = [1,1,2,3,4,5,6,6,6]
print(myCounter(L))    






zip(list,list) - join elements of two lists

Given two lists, a = ['l','m','n'] and b = ['p','q','r']. Write a code to crete a list, ['lp', 'mq', 'nr'].

As a preview, the following code shows how the zip(list,list) works:

#!/usr/local/bin/python

a = ['l','m','n']
b = ['p','q','r']
c = [(x,y) for x,y in zip(a,b)]
print(c)    # ==> [('l', 'p'), ('m', 'q'), ('n', 'r')]
d = [[x,y] for x,y in zip(a,b)]
print(d)    # ==> [['l', 'p'], ['m', 'q'], ['n', 'r']]

Our code should look like this:

#!/usr/local/bin/python

j = [''.join([x,y]) for x,y in zip(a,b)]
# or
# j = [x+y for x,y in zip(a,b)]
print(j)

Output:

['lp', 'mq', 'nr']    

Note that join() takes a list!



zip(list,list) - weighted average with two lists

We have two lists: [values] and [weights]. This sample shows how to use zip to calculate weighted average:

weights = [0.5, 0.8, 0.7, 0.8, 1.0]
values = [10, 20, 10, 10, 30]
average = sum([weight[i] * values[i] for i in range(len(weight))])/sum(values)
zip_average = sum ([x * y for x,y in zip(weights,values)]) / sum(values)
print average, zip_average  # 0.825 0.825

Note that the sum(list) takes a list, and the zip(list,list) takes two lists.





Intersection of two lists

Here we can use two approach: filter() and list comprehension:

a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]
print filter(lambda x: x in a, b)  # prints out [2, 3, 5, 7]

Note that we can do the same with list comprehension:

a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]
print [x for x in a if x in b] # prints out [2, 3, 5, 7]

With set():

a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]

j = list(set(a) & set(b))
print(j)  # ==> [2, 3, 5, 7]  




Dictionary sort by value

In this section, initially a list of character is given. From the list, we make a dictionary {char, count}, and print out the dictionary sorted by the value (count).

a = ['a','a','c','c','b','c']
# d = dict.fromkeys(a,0)
# or
d = {x:0 for x in a}
print(d)

for ch in a:
	d[ch] += 1
print(d)

sorted_d = sorted(d.items(), key=lambda x:x[1], reverse=True)
print(sorted_d)

Output:

{'a': 0, 'c': 0, 'b': 0}
{'a': 2, 'c': 3, 'b': 1}
[('c', 3), ('a', 2), ('b', 1)]

We can also use operator.itemgetter() to sort dictionary:

inventory = {'apple': 3, 'banana': 2, 'pear': 5, 'orange': 1}
s = sorted(inventory.items(), key=operator.itemgetter(0))
print(s)

Output:

[('apple', 3), ('banana', 2), ('orange', 1), ('pear', 5)]




Counting the number of characters of a file as One-Liner

The file given: "input.txt" is "abcdefgHIJKLMOPQrstuvwxyz". We need to count the Capitals only. One line of code:

print(len([s for s in open("input.txt","r").read() if s.isupper()]))

Output:

9

Actually, more readable code looks something like this:

with open("input.txt","r") as f:
    print(len([s for s in f.read() if s.isupper()]))




Find Armstrong numbers from 0-999

Write a program that computes all Armstrong numbers in the range of 0 and 999. An Armstrong number is a number such that the sum of its digits raised to the third power is equal to the number itself. For example, 371 is an Armstrong number, since 3**3 + 7**3 + 1**3 = 371.

Hint: use floor (//)

def isArmstrong(n):
    temp = n
    sum = 0
    while temp > 0:
        sum += (temp % 10)**3
        temp //= 10
    if n == sum:
        return True
    return False

n = 1000
print([i for i in range(0,n) if isArmstrong(i)])

Output:

[0, 1, 153, 370, 371, 407]





Find GCF (Greatest Common Factor)

def GCF(n1,n2):
    n = min(n1,n2)
    while True:
        if n1 % n == 0 and n2 % n == 0:
            return n
        n -= 1

n1 = 80; n2 = 240
print(GCF(n1,n2))

Output:

80




Find LCM (Least Common Multiple)

def LCM(n1,n2):
    n = max(n1,n2)
    while True:
        if n % n1 == 0 and n % n2 == 0:
            return n
        n += 1

n1 = 24; n2 = 36
print(LCM(n1,n2))

Output:

72




Draws 5 cards from a shuffled deck

Write a code to shuffle a deck of card and draw 5 cards.

import itertools, random

deck = list(itertools.product(range(1,14),['Space','Diamond','Club','Heart']))
random.shuffle(deck)
hands = list(deck[i] for i in range(5))
print(hands)

Output:

[(2, 'Club'), (11, 'Diamond'), (8, 'Diamond'), (13, 'Heart'), (2, 'Diamond')]




Ever seen & Just seen

Example:
# 'AAAABBBCCDAABBB' --> [A, B, C, D] (Ever seen)
# 'AAAABBBCCDAABBB' --> [A, B, C, D, A, B] (Just seen)

s1 = 'AAAABBBCCDAABBB'
s2 = 'AAAABBBCCDAABBB'

ever_seen = [s1[0]]
for v in s1[1:]:
    if v != ever_seen[-1] and v not in ever_seen:
        ever_seen.append(v)
print(ever_seen)


just_seen = [s2[0]]
for v in s2[1:]:
    if v != just_seen[-1]:
        just_seen.append(v)
print(just_seen)

Output:

['A', 'B', 'C', 'D']
['A', 'B', 'C', 'D', 'A', 'B']




Dictionary order by value or by key

Given a list, list items as the most frequent at top:

mylist = ['a','b','b','d','b','c','d','a','d','d']
    
d = {}.fromkeys(mylist,0) 
# or
d = {k:0 for k in mylist}
for m in mylist:
    d[m] += 1
print('initial d = %s' %d)

import operator

# descending : reverse=True
d2 = sorted(d.items(), key=operator.itemgetter(1), reverse=True)
print('order by value: %s' %d2)

d2 = sorted(d.items(), key=operator.itemgetter(0), reverse=True)
print('order by key: %s' %d2)

Output:

initial d = {'a': 2, 'b': 3, 'd': 4, 'c': 1}
order by value: [('d', 4), ('b', 3), ('a', 2), ('c', 1)]
order by key: [('d', 4), ('c', 1), ('b', 3), ('a', 2)]


Note: the itemgetter() can be used like this (specifying the sort order):

import operator

st = [('Tom',19,80), ('John',20,90), ('Jony',17,91), ('Jony',17,93), ('Json',21,85)]
print(sorted(st, key = operator.itemgetter(0,1,2)))

Output:

[('John', 20, 90), ('Jony', 17, 91), ('Jony', 17, 93), ('Json', 21, 85), ('Tom', 19, 80)]






Strings with "???"

Take an input string parameter and determine if exactly 3 question marks exist between every pair of numbers that add up to 10. If so, return true, otherwise return false.

'''
"arrb6???4xxbl5???eee5" => true
"4???1??bc9" => false
"acc?7??sss?3rr4??????5" => true
"5??aaaaaaaaaaaaaaaaaaa?5?5" => false
"9b???1???9??k?1???9" => true
"3?6???4?j?1???9" => true
"aa6?9" => false
'''

sslist = ["arrb6???4xxbl5???eee5", "4???1??bc9", "acc?7??sss?3rr4??????5",
         "5??aaaaaaaaaaaaaaaaaaa?5?5", "9b???1???9??k?1???9", "3?6???4?j?1???9", "aa6?9"]

def qmark(ss):
    print(ss)
    
    # index : the location of digits
    index = [i for i, s in enumerate(ss) if s.isdigit()]
    print('index=%s' %index)
    
    # index_tuple : [(start1, end1), ... ]
    index_tuple = [(index[i], index[i+1]) for i in range(len(index)-1)]
    print('index_tuple=%s' %index_tuple)

    # truth : list of 'True' or 'False'. 
    # To pass, all items should be 'True', Empty list means failure
    truth = []
    for t in index_tuple:
        sum = int(ss[t[0]]) + int(ss[t[1]])
        if sum == 10:
            if ss[t[0]:t[1]].count("?") != 3:
                truth.append('F')
            else:
                truth.append('T')
    if len(truth) == 0:
        return False
    elif 'F' in truth:
        return False
    else:
        return True
                    
for ss in sslist:
    print(qmark(ss))
    print()

The output:

arrb6???4xxbl5???eee5
index=[4, 8, 13, 20]
index_tuple=[(4, 8), (8, 13), (13, 20)]
True

4???1??bc9
index=[0, 4, 9]
index_tuple=[(0, 4), (4, 9)]
False

acc?7??sss?3rr4??????5
index=[4, 11, 14, 21]
index_tuple=[(4, 11), (11, 14), (14, 21)]
True

5??aaaaaaaaaaaaaaaaaaa?5?5
index=[0, 23, 25]
index_tuple=[(0, 23), (23, 25)]
False

9b???1???9??k?1???9
index=[0, 5, 9, 14, 18]
index_tuple=[(0, 5), (5, 9), (9, 14), (14, 18)]
True

3?6???4?j?1???9
index=[0, 2, 6, 10, 14]
index_tuple=[(0, 2), (2, 6), (6, 10), (10, 14)]
True

aa6?9
index=[2, 4]
index_tuple=[(2, 4)]
False




Regular expression - re.split()

We can split a string with string.split(). But when we need to split a string with multiple delimiters, we may want to use regular expression, re.split().

For example with the following string:

"Is life a joke?
Does it not make you cry?
Life is not a joke!
Those who live know.
It is sometimes a yoke!"

We want to split the string with three delimiters: '?', '!', and '.'

The string now has multiple sentences.

We should write a code the maximum number of words for those sentences.

Here is the code:

def solution(S):
    import re

    sentences = re.split(r'[.!?]', S)
    print(sentences)

    mx = 0 
    for sn in sentences:
        mx = max (mx, len(sn.split()))
    return mx
       
S = '''Is life a joke? Does it not make you cry? Life is not a joke! My be or may be not at all.'''
print(solution(S))

Output:

['Is life a joke', ' Does it not make you cry', ' Life is not a joke', ' My be or may be not at all', '']
8

Note that in the re.split() we used r (raw) which signals Python not to interpret backslashes and special meta-characters in the string (literally, ignore if there are any special character, for example, dot(.), meta character). Also, we used square bracket, '[]', to tell Python to match any characters in the bracket.


Another example for a given string: '1. First part 2. Second part 3. Third part'. How to split the string to ['First part', 'Second part', 'Third part']?

input_string = '1. First part 2. Second part 3. Third part'
strings = re.split('\d\. ', input_string)
print(strings)

Output:

['', 'First part ', 'Second part ', 'Third part']




Regular expression : re.match() vs. re.search()

Both method accept pattern and string and returns a match object on success or None if no match is found.

The following code prints out the 'count' for a given pattern, 'back':

import re
filename = ['backup.txt','text.back','backup2.txt', 'file.back']
pattern = r'back'
count = 0
for file in filename:
    if re.match(pattern, file):
        print('matched: %s' %file)
        count += 1
print('count=%d' %count)

Output:

matched: backup.txt
matched: backup2.txt
count=2

Note that re.match() is very similar to re.search(), and the difference is that re.match() will start looking for matches at the beginning of the string.

So, we can get the same result from re.search() if we use ^ before the pattern:

import re
filename = ['backup.txt','text.back','backup2.txt', 'file.back']
pattern = r'back'
count = 0
print('pattern=%s' %pattern)
for file in filename:
    if re.match(pattern, file):
        print('re.match() - matched: %s' %file)
        count += 1
print('count=%d' %count)

pattern = r'back'
count = 0
print('pattern=%s' %pattern)
for file in filename:
    if re.search(pattern, file):
        print('re.search() - matched: %s' %file)
        count += 1
print('count=%d' %count)

pattern = r'^back'
count = 0
print('pattern=%s' %pattern)
for file in filename:
    result = re.search(pattern, file)
    if result:
        print('re.search() - matched: %s' %result.group())
        count += 1
print('count=%d' %count)

Output:

pattern=back
re.match() - matched: backup.txt
re.match() - matched: backup2.txt
count=2
pattern=back
re.search() - matched: backup.txt
re.search() - matched: text.back
re.search() - matched: backup2.txt
re.search() - matched: file.back
count=4
pattern=^back
re.search() - matched: back
re.search() - matched: back
count=2

The match object has group() method which contains the matching text in the string.





Regular expression : re.match() - password check
'''
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [@#$%^&+=]
4. Minimum length of transaction password: 6
'''

import re

def pass_check(password):
    if re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$])[\w\d@#$]{6,}$", password):
        return password
    else:
        return None

password = ['ABd1234@1','abcdef', '3Fa1#', '2w3E*', '2We3345']
pass_ok = []
for p in password:
    pass_ok.append(pass_check(p))
print(pass_ok)

Output:

['ABd1234@1', None, None, None, None]

Note:

  1. (?=...)

    Matches if ... matches next, but doesn't consume any of the string. This is called a positive lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it's followed by 'Asimov'.

    Note that if we use '!' instead of '=', we call it negative lookahead. For example, Isaac (?!Asimov) will match 'Isaac ' if it's not followed by 'Asimov'.

    import re
    result = re.match(r'Issac (?=Asimov)', 'Issac Asimov 1920-1992')
    if result:
        print(result.group(0))
    else:
        print('no match')
        
    result = re.match(r'Issac (?!Asimov)', 'Issac Asimov 1920-1992')
    if result:
        print(result.group(0))
    else:
        print('no match')
    

    Output:

    Issac 
    no match
    

  2. \d
    Matches any decimal digit





Regular expression : re.search() - group capturing
import re

# . (dot) : matches any character except newline
# \w      : matches any word character i.e letters, alphanumeric, digits and underscore ('_')
# +       : matches one or more of the preceding character (greedy match)

patterns = [r'\w@\w', r'\w+@\w+', r'[\w.-]+@[\w.]+']

for p in patterns:
    match = re.search(p, 'ki.hong-777@yahoo.com')
    if match:
        print('pattern = %s, match.group() = %s' %(p, match.group()))
    else:
        print('No match')

Output:

pattern = \w@\w, match.group() = 7@y
pattern = \w+@\w+, match.group() = 777@yahoo
pattern = [\w.-]+@[\w.]+, match.group() = ki.hong-777@yahoo.com

Group capturing allows us to extract parts from the matching string. We can create groups using parentheses ().

Using the capturing capability, we can extract username and host name from the email address in the above example. To do this we need to add () around username and host name like this:

r'([\w.-]+)@([\w.]+)'

The code:

import re

# . (dot) : matches any character except newline
# \w      : matches any word character i.e letters, alphanumeric, digits and underscore ('_')
# +       : matches one or more of the preceding character (greedy match)

patterns = [r'([\w.-]+)@([\w.]+)']

for p in patterns:
    match = re.search(p, 'ki.hong-777@yahoo.com')
    if match:
        print('pattern = %s, match.group() = %s' %(p, match.group()))
        print('group(1) = %s, group(2) = %s' %(match.group(1),match.group(2)))
    else:
        print('No match')




Regular expression : re.findall() - group capturing

We can also use group capturing with findall(). When group capturing is applied, findall() returns a list of tuples where tuples will contain the matching groups:

import re

# +     : matches one or more of the preceding character (greedy match)
# \d    : matches a single digit

pattern = r'(\d{3})-(\d+)-(\d\d\d\d)'
numbers = ['123-456-7890', '3210-6540-09870']

print('pattern = %s' %pattern)
for n in numbers:
    match = re.findall(pattern, n)
    if match:       
        for m in match:
            print('number = %s, m = %s' %(n,m))
    else:
        print('No match')

Output:

pattern = (\d{3})-(\d+)-(\d\d\d\d)
number = 123-456-7890, m = ('123', '456', '7890')
number = 3210-6540-09870, m = ('210', '6540', '0987')

We used three patterns to illustrate the difference. The \d{3} picks up 3 digits preceding '-', \d+ gets any umber of digits before '-', and \d\d\d\d takes 4 digits as specified.





Prime factors : n = products of prime numbers

Write a function to find all the prime factors of a given integer. The function must return a list containing all the prime factors, sorted in ascending order.

import math
def prime_factors(n):
    pf = []
    while n % 2 == 0:
        pf.append(2)
        n = int(n/2)
    for i in range(3, int(n/2), 2):
        while n % i == 0:
            pf.append(i)
            n = n/i                   
    return pf

numbers = [2,5,12,34,135,741,5068,40356,362925,3628855,39916866,479001678]

for n in numbers:
    print('%s: %s' %(n, prime_factors(n)))

Output:

2: [2]
5: []
12: [2, 2]
34: [2]
135: [3, 3, 3, 5]
741: [3, 13, 19]
5068: [2, 2, 7, 181]
40356: [2, 2, 3, 3, 19, 59]
362925: [3, 3, 5, 5, 1613]
3628855: [5, 557, 1303]
39916866: [2, 3, 11, 604801]
479001678: [2, 3, 79833613]




Valid IPv4 address

Create a function that takes a string (IPv4 address in standard dot-decimal format) and returns True if the IP is valid or False if it's not.

# "1.2.3.4" => True
# "1.2.3" => False
# "1.2.3.4.5" => False
# "123.45.67.89" => True
# "123.456.78.90" => False
# "123.045.067.089" => False

def valid(ip):
  n4 = ip.split('.')
  if len(n4) != 4:
     return False
  for n in n4:
     if n[0] == '0' or int(n) > 255:
       return False

  return True

ips = ["1.2.3.4", "1.2.3", "1.2.3.4.5", "123.45.67.89", "123.456.78.90", "123.045.067.089"]

for ip in ips:
  print('%s => %s' %(ip,valid(ip))) 

Output:

1.2.3.4 => True
1.2.3 => False
1.2.3.4.5 => False
123.45.67.89 => True
123.456.78.90 => False
123.045.067.089 => False




Sum of strings - ord() and sum()

Write a program to replace each string with an integer value in a given list of strings. The replacement integer value should be a sum of Ascii values of each character of the corresponding string.

countries  =['Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy']
ord_sum = []
for country in countries:
  ord_sum.append(sum([ord(c) for c in country]))
print(ord_sum)

Output:

[706, 723, 700, 591, 723, 587, 734, 703, 515]




List rotation - left/right shift

Write a left and right rotations of a list. For example, rotation(l, 2) should convert a = [1,2,3,4,5] should print out [3,4,5,1,2], which is a left rotation. For right rotation, the 2nd parameter can be given as -2 instead of +2.

def rotation(a,n):
	return a[n:] + a[:n]
	
a = [1,2,3,4,5]

# left 
print(rotation(a,1))
print(rotation(a,2))

# right
print(rotation(a,-1))
print(rotation(a,-2))

Output:

[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[5, 1, 2, 3, 4]
[4, 5, 1, 2, 3]


For more complete (general) solution, please check Left rotation - list shift





shallow/deep copy

The keyword here is reference!

We copy to make a duplicate data. But this copy function only makes the copy of reference that means if we change the new object then this will change the original as well.

So, we may want to use deep copy so that we can create a new object with original one and can modify the newly created object separately.

Note that the deep copy makes execution of the program slower due to making certain copies for each object that is been called.

deep_copy_vs_shallow_copy_python.png

Picture credit: trying to do a shallow copy on list in python



When a child element of a list changes, the element of the copied list also changes. To make the original and copied ones remain independent, we can use copy.deepcopy().

import copy

x = [1,2,[1,2]]
y = x
print('x=%s, y=%s' %(x,y))
x[2][0] = '?'
print('x=%s, y=%s' %(x,y))

x2 = [1,2,[1,2]]
y2 = copy.copy(x2)
print('x2=%s, y2=%s' %(x2,y2))
x2[2][0] = '?'
print('x2=%s, y2=%s' %(x2,y2))
                  
x3 = [1,2,[1,2]]
y3 = copy.deepcopy(x3)
print('x3=%s, y3=%s' %(x3,y3))
x3[2][0] = '?'
print('x3=%s, y3=%s' %(x3,y3))

Output:

x=[1, 2, [1, 2]], y=[1, 2, [1, 2]]
x=[1, 2, ['?', 2]], y=[1, 2, ['?', 2]]
x2=[1, 2, [1, 2]], y2=[1, 2, [1, 2]]
x2=[1, 2, ['?', 2]], y2=[1, 2, ['?', 2]]
x3=[1, 2, [1, 2]], y3=[1, 2, [1, 2]]
x3=[1, 2, ['?', 2]], y3=[1, 2, [1, 2]]

Note that for the deepcopied y3[2][0]=1, not affected from the x3[2][0]='?'
Note also that y = x is the same as y = copy.copy(x).


Another example: shallow copy vs deep copy.





Converting integer to binary number
def binary(n):
    b = []
    while n > 0:
        b.append(str(n % 2))
        n = n // 2
    return b[::-1]    

n = 21
bb = binary(n)
print(bb)
print(''.join(bb))

Output:

['1', '0', '1', '0', '1']
10101

Or we can just use bin():

n = 21
print(bin(n))
print(bin(n)[2:])

Output:

0b10101
10101

Binary => int:

int(0b1111) # =>  15
int(0B1111) # =>  15




Creating a directory and a file

Write a code to create a directory with name "Temporary" and create a file "myfile.txt" in the new directory "Temporary".

import os
filename = os.path.expanduser('~/Documents/TEST/Temporary/myfile.txt')
dirname = os.path.dirname(filename)

if not os.path.exists(dirname):
    os.makedirs(dirname)
with open(filename,'w') as f:
    f.write("test")




Creating a file if not exists

List all the files from a given path and verify the file "myfile.txt" file exists or not? If the file does not exist create it.

import os
path = os.path.expanduser('~/Documents/TEST/Temporary')
fname = "myfile.txt"
print(path)
for root, dirnames, filenames in os.walk(path):
    files = [f for f in filenames]
if not fname in files:
    with open(os.path.join(path, fname), 'w') as f:
        f.write("test...")




Invoking a python file from another

Create a hello.py file and run this program by invoking it in another python file.

# hello.py
print("hello, python!")
  
def hello_1():
   print('hello-1')

def hello_2():
   print('hello-2')

# call_hello.py
import hello
  
hello.hello_1()
hello.hello_2()

We can run it "python call_hello.py", and the output:

hello, python!
hello-1
hello-2




Sorting IP addresses

import operator

ips = ['5.4.3.2', '1.2.3.4', '5.4.1.2', '1.2.4.5']

# [['5', '4', '3', '2'], [], ...]
splitted = [(ip.split('.')) for ip in ips]

# [[['1', '2', '3', '4'], [], ...]]
sorted_splitted = sorted(splitted, key=operator.itemgetter(0,1,2,3), reverse=False)

# inserting dot('.')s
sorted_ips = ['.'.join(s) for s in sorted_splitted]
    
print('%s => %s' %(ips,sorted_ips))


Output:

['5.4.3.2', '1.2.3.4', '5.4.1.2', '1.2.4.5'] => ['1.2.3.4', '1.2.4.5', '5.4.1.2', '5.4.3.2']





Word Frequency

For a given text, we want to get the frequency of the words. The most frequent one at the top.

text="""
bands which have connected them with another, 
and to assume among the powers of the earth, 
the separate and equal station to which the Laws of Nature 
and of Nature's God entitle them, 
a decent respect to the opinions of mankind requires 
that they should declare the causes which impel them to the separation.
"""

First, we need to process the text excluding some characters:

words = text.replace('-',' ').replace(',',' ').replace('.',' ').replace('\n',' ').lower().split()
print(words)

The modified input text should look like this:

['bands', 'which', 'have', 'connected', 'them', 'with', 'another', 'and', 'to', 'assume', 'among', 'the', 'powers', 'of', 'the', 'earth', 'the', 'separate', 'and', 'equal', 'station', 'to', 'which', 'the', 'laws', 'of', 'nature', 'and', 'of', "nature's", 'god', 'entitle', 'them', 'a', 'decent', 'respect', 'to', 'the', 'opinions', 'of', 'mankind', 'requires', 'that', 'they', 'should', 'declare', 'the', 'causes', 'which', 'impel', 'them', 'to', 'the', 'separation']

Here are some of the implementations:

d = {}.fromkeys(words,0)
for w in words:
    d[w] += 1
s = sorted(d.items(), key=lambda x:x[1], reverse=True)
print(s)

import operator
d = {}
for w in words:
    d[w] = d.get(w,0)+1
s = sorted(d.items(), key=operator.itemgetter(1), reverse=True)
print(s)

import collections
d = collections.Counter(words) # descending
#d = sorted(collections.Counter(words), reverse=True) # ascending
print(d)

d = {}
for w in words:
    if w not in d:
        d[w] = 0
    d[w] += 1
mylist = [(k, d[k]) for k in sorted(d, key=d.get, reverse=True)]
print(mylist)



The outputs should look like this:

[('the', 7), ('to', 4), ('of', 4), ('which', 3), ('them', 3), ('and', 3), ('bands', 1), ('have', 1), ('connected', 1), ('with', 1), ('another', 1), ('assume', 1), ('among', 1), ('powers', 1), ('earth', 1), ('separate', 1), ('equal', 1), ('station', 1), ('laws', 1), ('nature', 1), ("nature's", 1), ('god', 1), ('entitle', 1), ('a', 1), ('decent', 1), ('respect', 1), ('opinions', 1), ('mankind', 1), ('requires', 1), ('that', 1), ('they', 1), ('should', 1), ('declare', 1), ('causes', 1), ('impel', 1), ('separation', 1)]




URL query string - making parameter dictionary

With a given query string, we want to make a dictionary for the parameters. Note that the url has two identical key, "userEmail", and we want to keep both of the emails.

url = "https://bogotobogo.com/?userId=1&userName=Bob&userEmail=foo@gmail.com&userEmail=bar@yahoo.com"

from collections import defaultdict
parm_dict = defaultdict(list)
par_list = url.split('?')[1].split('&')
print(par_list)
for p in par_list:
    k,v = p.split('=')
    parm_dict[k].append(v)
    
print(parm_dict)

Output:

['userId=1', 'userName=Bob', 'userEmail=foo@gmail.com', 'userEmail=bar@yahoo.com']
defaultdict(<class 'list'>, {'userId': ['1'], 'userName': ['Bob'], 'userEmail': ['foo@gmail.com', 'bar@yahoo.com']})




Printing spiral pattern from a 2D array - I. Clock-wise

Print numbers in spiral pattern (clock-wise) for a given 2D array.


spiral-cw.png
# clock-wise spiral

def spiral(re, ce, a):
    
    rs = 0; cs = 0
    
    # rs : starting row index
    # rd : ending row index
    # cs : starting column index
    # ce : ending column index
    
    while (rs < re and cs < ce):
        
        # printing the 1st row of the remaining rows
        for c in range(cs, ce):
            print(a[rs][c],end=" ")
        rs += 1
        
        # printing the last column of the remaining columns
        for r in range(rs, re):
            print(a[r][ce-1],end=" ")
        ce -= 1
        
        # printing the last row of the remaining rows
        if rs < re:
            for c in range(ce-1, cs-1, -1):
                print(a[re-1][c],end=" ")
            re -= 1        

        # printing the first column of the remaining columns
        if cs < ce:
            for r in range(re-1, rs-1, -1):
                print(a[r][c],end=" ")
            cs += 1   

if __name__ == '__main__':
   
    # Case 1 : 4 x 6 grid
    row = 4
    column = 6
    arr = [ [ 1,  2,  3,  4,  5, 6],
            [16, 17, 18, 19, 20, 7],
            [15, 24, 23, 22, 21, 8],
            [14, 13, 12, 11, 10, 9]]
    spiral(4, 6, arr)

    print()
    
    # Case 2 - 5 x 5 grid
    row = 5
    column = 5
    arr = [ [ 1,  2,  3,  4, 5],
            [16, 17, 18, 19, 6],
            [15, 24, 25, 20, 7],
            [14, 23, 22, 21, 8],
            [13, 12, 11, 10, 9]]
    spiral(5, 5, arr)

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 

Printing spiral pattern from a 2D array - II. Counter-Clock-wise

Print numbers in spiral pattern (coundter-clock-wise) for a given 2D array.


spiral-ccw.png
# counter-clock-wise spiral

def spiral(re, ce, a):
    
    rs = 0; cs = 0
    
    # rs : starting row index
    # rd : ending row index
    # cs : starting column index
    # ce : ending column index
    
    while (rs < re and cs < ce):
        
        # printing the 1st column of the remaining columns
        for r in range(rs, re):
            print(a[r][cs],end=" ")
        cs += 1
        
        # printing the last row of the remaining rows
        for c in range(cs, ce):
            print(a[re-1][c],end=" ")
        re -= 1
        
        # printing the last column of the remaining columns
        if cs < ce:
            for r in range(re-1, rs-1, -1):
                print(a[r][ce-1],end=" ")
            ce -= 1        

        # printing the first row of the remaining rows
        if rs < re:
            for c in range(ce-1, cs-1, -1):
                print(a[r][c],end=" ")
            rs += 1   

if __name__ == '__main__':
   
    # Case 1 : 4 x 6 grid
    row = 4
    column = 6
    arr = [ [1, 15, 13, 14, 13, 12],
            [2, 16, 23, 22, 21, 11],
            [3, 17, 18, 19, 20, 10],
            [4,  5,  6,  7,  8,  9]]
    spiral(4, 6, arr)

    print()
    
    # Case 2 - 5 x 5 grid
    row = 5
    column = 5
    arr = [ [1, 16, 15, 14, 13],
            [2, 17, 24, 23, 12],
            [3, 18, 25, 22, 11],
            [4, 19, 20, 21, 10],
            [5,  6,  7,  8, 9]]
    spiral(5, 5, arr)

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 13 15 16 17 18 19 20 21 22 23 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 





Find a minimum integer not in the input list

Print out a minimum integer (should be greater than 0) not in the input list of integers. The size of the list could be up to N = 100000.

N = 100000
def my_integer(a):   
    a = set(a)
    i = 1
    while (i <= N):
        if i not in a and i >= 1:
            return i
        i += 1

a = [1, 2, 7, 5, 4, 1, 3]
print(my_integer(a))

a = [1, 2, 3] 
print(my_integer(a))
 
a =[2]
print(my_integer(a))

a = [x for x in range(-5,5,2)]
print(my_integer(a))

import random

a = [random.randint(-N//2, N//2) for x in range(N//2)]
print(my_integer(a))

a = [random.randint(-2, 2) for x in range(10)]
print(my_integer(a))

Output:

6
4
1
2
4
3


I. Binary Gap: find longest sequence of zeros in binary representation of an integer
def binary(n):
    b = []
    while n > 0:
        b.append(n%2)
        n = n // 2
    return b

def mxlength(a):
    count = 0
    mx = 0
    for index, e in enumerate(a):
        if e == 0:
            count += 1
            mx = max(mx, count)
        else:
            count = 0
    return mx
            
for x in range(20):
    b = binary(x)
    print('%s : b=%s, mx=%s' %(x, b, mxlength(b)))

Output:

0 : b=[], mx=0
1 : b=[1], mx=0
2 : b=[0, 1], mx=1
3 : b=[1, 1], mx=0
4 : b=[0, 0, 1], mx=2
5 : b=[1, 0, 1], mx=1
6 : b=[0, 1, 1], mx=1
7 : b=[1, 1, 1], mx=0
8 : b=[0, 0, 0, 1], mx=3
9 : b=[1, 0, 0, 1], mx=2
10 : b=[0, 1, 0, 1], mx=1
11 : b=[1, 1, 0, 1], mx=1
12 : b=[0, 0, 1, 1], mx=2
13 : b=[1, 0, 1, 1], mx=1
14 : b=[0, 1, 1, 1], mx=1
15 : b=[1, 1, 1, 1], mx=0
16 : b=[0, 0, 0, 0, 1], mx=4
17 : b=[1, 0, 0, 0, 1], mx=3
18 : b=[0, 1, 0, 0, 1], mx=2
19 : b=[1, 1, 0, 0, 1], mx=2


II. Binary Gap: fin longest sequence of zeros in binary representation of an integer - should be surrounded by 1s

The difference from the previous case is that the 0-block should be surrounded with 1s. So, the number 16 = [1,0,0,0,0] should have max = 0 not 4 because it's missing '1' at the end.

def binary(n):
    b = []
    while n > 0:
        b.append(n%2)
        n = n // 2
    return b 

def mxlength(b):
    count = 0
    mx = 0
    total = 0
    for index, bit in enumerate(b):
        if bit == 0:  
            # exclude the 0-block with starting and ending with 0
            if index == 0 or index == len(b)-1:
                count = 0
                total = 0
            # for each bit, calculate the sum of the bits before and after the index
            else:               
                count += 1
                total = total + b[index-1]+b[index+1]   
            # legitimate 0-block's total should be 2
            if total == 2:
                mx = max(mx, count)
        else:
            count = 0
            total = 0
    return mx

for x in range(100):
    b = binary(x)
    print('%s : b=%s, mx=%s' %(x, b, mxlength(b)))

Output:

0 : b=[], mx=0
1 : b=[1], mx=0
2 : b=[0, 1], mx=0
3 : b=[1, 1], mx=0
4 : b=[0, 0, 1], mx=0
5 : b=[1, 0, 1], mx=1
6 : b=[0, 1, 1], mx=0
7 : b=[1, 1, 1], mx=0
8 : b=[0, 0, 0, 1], mx=0
9 : b=[1, 0, 0, 1], mx=2
10 : b=[0, 1, 0, 1], mx=1
11 : b=[1, 1, 0, 1], mx=1
12 : b=[0, 0, 1, 1], mx=0
13 : b=[1, 0, 1, 1], mx=1
14 : b=[0, 1, 1, 1], mx=0
15 : b=[1, 1, 1, 1], mx=0
16 : b=[0, 0, 0, 0, 1], mx=0
17 : b=[1, 0, 0, 0, 1], mx=3
18 : b=[0, 1, 0, 0, 1], mx=2
19 : b=[1, 1, 0, 0, 1], mx=2
20 : b=[0, 0, 1, 0, 1], mx=1
21 : b=[1, 0, 1, 0, 1], mx=1
22 : b=[0, 1, 1, 0, 1], mx=1
23 : b=[1, 1, 1, 0, 1], mx=1
24 : b=[0, 0, 0, 1, 1], mx=0
25 : b=[1, 0, 0, 1, 1], mx=2
26 : b=[0, 1, 0, 1, 1], mx=1
27 : b=[1, 1, 0, 1, 1], mx=1
28 : b=[0, 0, 1, 1, 1], mx=0
29 : b=[1, 0, 1, 1, 1], mx=1
30 : b=[0, 1, 1, 1, 1], mx=0
31 : b=[1, 1, 1, 1, 1], mx=0
32 : b=[0, 0, 0, 0, 0, 1], mx=0
33 : b=[1, 0, 0, 0, 0, 1], mx=4
34 : b=[0, 1, 0, 0, 0, 1], mx=3
35 : b=[1, 1, 0, 0, 0, 1], mx=3
36 : b=[0, 0, 1, 0, 0, 1], mx=2
37 : b=[1, 0, 1, 0, 0, 1], mx=2
38 : b=[0, 1, 1, 0, 0, 1], mx=2
39 : b=[1, 1, 1, 0, 0, 1], mx=2
40 : b=[0, 0, 0, 1, 0, 1], mx=1
41 : b=[1, 0, 0, 1, 0, 1], mx=2
42 : b=[0, 1, 0, 1, 0, 1], mx=1
43 : b=[1, 1, 0, 1, 0, 1], mx=1
44 : b=[0, 0, 1, 1, 0, 1], mx=1
45 : b=[1, 0, 1, 1, 0, 1], mx=1
46 : b=[0, 1, 1, 1, 0, 1], mx=1
47 : b=[1, 1, 1, 1, 0, 1], mx=1
48 : b=[0, 0, 0, 0, 1, 1], mx=0
49 : b=[1, 0, 0, 0, 1, 1], mx=3
50 : b=[0, 1, 0, 0, 1, 1], mx=2
51 : b=[1, 1, 0, 0, 1, 1], mx=2
52 : b=[0, 0, 1, 0, 1, 1], mx=1
53 : b=[1, 0, 1, 0, 1, 1], mx=1
54 : b=[0, 1, 1, 0, 1, 1], mx=1
55 : b=[1, 1, 1, 0, 1, 1], mx=1
56 : b=[0, 0, 0, 1, 1, 1], mx=0
57 : b=[1, 0, 0, 1, 1, 1], mx=2
58 : b=[0, 1, 0, 1, 1, 1], mx=1
59 : b=[1, 1, 0, 1, 1, 1], mx=1
60 : b=[0, 0, 1, 1, 1, 1], mx=0
61 : b=[1, 0, 1, 1, 1, 1], mx=1
62 : b=[0, 1, 1, 1, 1, 1], mx=0
63 : b=[1, 1, 1, 1, 1, 1], mx=0
64 : b=[0, 0, 0, 0, 0, 0, 1], mx=0
65 : b=[1, 0, 0, 0, 0, 0, 1], mx=5
66 : b=[0, 1, 0, 0, 0, 0, 1], mx=4
67 : b=[1, 1, 0, 0, 0, 0, 1], mx=4
68 : b=[0, 0, 1, 0, 0, 0, 1], mx=3
69 : b=[1, 0, 1, 0, 0, 0, 1], mx=3
70 : b=[0, 1, 1, 0, 0, 0, 1], mx=3
71 : b=[1, 1, 1, 0, 0, 0, 1], mx=3
72 : b=[0, 0, 0, 1, 0, 0, 1], mx=2
73 : b=[1, 0, 0, 1, 0, 0, 1], mx=2
74 : b=[0, 1, 0, 1, 0, 0, 1], mx=2
75 : b=[1, 1, 0, 1, 0, 0, 1], mx=2
76 : b=[0, 0, 1, 1, 0, 0, 1], mx=2
77 : b=[1, 0, 1, 1, 0, 0, 1], mx=2
78 : b=[0, 1, 1, 1, 0, 0, 1], mx=2
79 : b=[1, 1, 1, 1, 0, 0, 1], mx=2
80 : b=[0, 0, 0, 0, 1, 0, 1], mx=1
81 : b=[1, 0, 0, 0, 1, 0, 1], mx=3
82 : b=[0, 1, 0, 0, 1, 0, 1], mx=2
83 : b=[1, 1, 0, 0, 1, 0, 1], mx=2
84 : b=[0, 0, 1, 0, 1, 0, 1], mx=1
85 : b=[1, 0, 1, 0, 1, 0, 1], mx=1
86 : b=[0, 1, 1, 0, 1, 0, 1], mx=1
87 : b=[1, 1, 1, 0, 1, 0, 1], mx=1
88 : b=[0, 0, 0, 1, 1, 0, 1], mx=1
89 : b=[1, 0, 0, 1, 1, 0, 1], mx=2
90 : b=[0, 1, 0, 1, 1, 0, 1], mx=1
91 : b=[1, 1, 0, 1, 1, 0, 1], mx=1
92 : b=[0, 0, 1, 1, 1, 0, 1], mx=1
93 : b=[1, 0, 1, 1, 1, 0, 1], mx=1
94 : b=[0, 1, 1, 1, 1, 0, 1], mx=1
95 : b=[1, 1, 1, 1, 1, 0, 1], mx=1
96 : b=[0, 0, 0, 0, 0, 1, 1], mx=0
97 : b=[1, 0, 0, 0, 0, 1, 1], mx=4
98 : b=[0, 1, 0, 0, 0, 1, 1], mx=3
99 : b=[1, 1, 0, 0, 0, 1, 1], mx=3

Note that the returned list from the function (binary()) should be reversed for the bits to represent the real binary value. In our case, however, it gives us the right answer.



Find a missing element from a list of integers

A list consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Let's try to find the missing element.

def missing(a):
    exists = [False]*(len(A)+1)
    for item in a:
        exists[item-1] = True
    for index, e in enumerate(exists):
        if e == False:
            return index+1

a = [1,2,3,5,6]
print(missing(a))

Output:

4




Find an unpaired element from a list of integers

A non-empty list a consisting of N integers is given. The list contains an odd number of elements, and each element of the list can be paired with another element that has the same value, except for one element that is left unpaired.

For example, given a = [1,2,3,1,2], the output should be '3'.

The following solution gives us the right answer, but it's O(n^2):

def unpaired(a):
    for e in a:
        if a.count(e) % 2 == 1:
            return e
    return None

a = [1,2,3,1,2]
unpaired(a)

Another try which looks ok - (O(N logN)) and traverse(O(N)):

def unpaired(a):
    d = dict.fromkeys(a,0)
    print(d)
    for x in a:
        d[x] += 1
    print(d)
    
    odd = []
    for k,v in d.items():
        if v % 2 == 1:
            odd.append(k)
            return k
    
    return k
            
a = [9,3,9,3,9,7,9]
print(unpaired(a))

Here we have a final solution: sort the list first ( O(N logN) ), and traverse( O(N) ) the elements with step 2:

def unpaired(a):
    if len(a) == 1:
        return a[0]
    
    a = sorted(a)
    for i in range(0,len(a),2):
        if i+1 == len(a):
            return a[i]
        if a[i] != a[i+1]:
            return a[i]

a = [1,2,3,5,6,10,1,2,6,3,5]
print(unpaired(a))

import random
N = 1000000
a = [random.randint(1,N) for x in range(N//2)]
print(unpaired(a))

Output:

10
2






  1. Python Coding Questions I
  2. Python Coding Questions II
  3. Python Coding Questions III
  4. Python Coding Questions IV
  5. Python Coding Questions V
  6. Python Coding Questions VI
  7. Python Coding Questions VII
  8. Python Coding Questions VIII
  9. Python Coding Questions IX
  10. Python Coding Questions X





List of codes Q & A

  1. Merging two sorted list
  2. Get word frequency - initializing dictionary
  3. Initializing dictionary with list
  4. map, filter, and reduce
  5. Write a function f() - yield
  6. What is __init__.py?
  7. Build a string with the numbers from 0 to 100, "0123456789101112..."
  8. Basic file processing: Printing contents of a file - "with open"
  9. How can we get home directory using '~' in Python?
  10. The usage of os.path.dirname() & os.path.basename() - os.path
  11. Default Libraries
  12. range vs xrange
  13. Iterators
  14. Generators
  15. Manipulating functions as first-class objects
  16. docstrings vs comments
  17. using lambdda
  18. classmethod vs staticmethod
  19. Making a list with unique element from a list with duplicate elements
  20. What is map?
  21. What is filter and reduce?
  22. *args and **kwargs
  23. mutable vs immutable
  24. Difference between remove, del and pop on lists
  25. Join with new line
  26. Hamming distance
  27. Floor operation on integers
  28. Fetching every other item in the list
  29. Python type() - function
  30. Dictionary Comprehension
  31. Sum
  32. Truncating division
  33. Python 2 vs Python 3
  34. len(set)
  35. Print a list of file in a directory
  36. Count occurrence of a character in a Python string
  37. Make a prime number list from (1,100)
  38. Reversing a string - Recursive
  39. Reversing a string - Iterative
  40. Reverse a number
  41. Output?
  42. Merging overlapped range
  43. Conditional expressions (ternary operator)
  44. Packing Unpacking
  45. Function args
  46. Unpacking args
  47. Finding the 1st revision with a bug
  48. Which one has higher precedence in Python? - NOT, AND , OR
  49. Decorator(@) - with dollar sign($)
  50. Multi-line coding
  51. Recursive binary search
  52. Iterative binary search
  53. Pass by reference
  54. Simple calculator
  55. iterator class that returns network interfaces
  56. Converting domain to ip
  57. How to count the number of instances
  58. Python profilers - cProfile
  59. Calling a base class method from a child class that overrides it
  60. How do we find the current module name?
  61. Why did changing list 'newL' also change list 'L'?
  62. Constructing dictionary - {key:[]}
  63. Colon separated sequence
  64. Converting binary to integer
  65. 9+99+999+9999+...
  66. Calculating balance
  67. Regular expression - findall
  68. Chickens and pigs
  69. Highest possible product
  70. Implement a queue with a limited size
  71. Copy an object
  72. Filter
  73. Products
  74. Pickle
  75. Overlapped Rectangles
  76. __dict__
  77. Fibonacci I - iterative, recursive, and via generator
  78. Fibonacci II - which method?
  79. Fibonacci III - find last two digits of Nth Fibonacci number
  80. Write a Stack class returning Max item at const time A
  81. Write a Stack class returning Max item at const time B
  82. Finding duplicate integers from a list - 1
  83. Finding duplicate integers from a list - 2
  84. Finding duplicate integers from a list - 3
  85. Reversing words 1
  86. Parenthesis, a lot of them
  87. Palindrome / Permutations
  88. Constructing new string after removing white spaces
  89. Removing duplicate list items
  90. Dictionary exercise
  91. printing numbers in Z-shape
  92. Factorial
  93. lambda
  94. lambda with map/filter/reduce
  95. Number of integer pairs whose difference is K
  96. iterator vs generator
  97. Recursive printing files in a given directory
  98. Bubble sort
  99. What is GIL (Global Interpreter Lock)?
  100. Word count using collections
  101. Pig Latin
  102. List of anagrams from a list of words
  103. lamda with map, filer and reduce functions
  104. Write a code sending an email using gmail
  105. histogram 1 : the frequency of characters
  106. histogram 2 : the frequency of ip-address
  107. Creating a dictionary using tuples
  108. Getting the index from a list
  109. Looping through two lists side by side
  110. Dictionary sort with two keys : primary / secondary keys
  111. Writing a file downloaded from the web
  112. Sorting csv data
  113. Reading json file
  114. Sorting class objects
  115. Parsing Brackets
  116. Printing full path
  117. str() vs repr()
  118. Missing integer from a sequence
  119. Polymorphism
  120. Product of every integer except the integer at that index
  121. What are accessors, mutators, and @property?
  122. N-th to last element in a linked list
  123. Implementing linked list
  124. Removing duplicate element from a list
  125. List comprehension
  126. .py vs .pyc
  127. Binary Tree
  128. Print 'c' N-times without a loop
  129. Quicksort
  130. Dictionary of list
  131. Creating r x c matrix
  132. Transpose of a matrix
  133. str.isalpha() & str.isdigit()
  134. Regular expression
  135. What is Hashable? Immutable?
  136. Convert a list to a string
  137. Convert a list to a dictionary
  138. List - append vs extend vs concatenate
  139. Use sorted(list) to keep the original list
  140. list.count()
  141. zip(list,list) - join elements of two lists
  142. zip(list,list) - weighted average with two lists
  143. Intersection of two lists
  144. Dictionary sort by value
  145. Counting the number of characters of a file as One-Liner
  146. Find Armstrong numbers from 100-999
  147. Find GCF (Greatest common divisor)
  148. Find LCM (Least common multiple)
  149. Draws 5 cards from a shuffled deck
  150. Dictionary order by value or by key
  151. Regular expression - re.split()
  152. Regular expression : re.match() vs. re.search()
  153. Regular expression : re.match() - password check
  154. Regular expression : re.search() - group capturing
  155. Regular expression : re.findall() - group capturin
  156. Prime factors : n = products of prime numbers
  157. Valid IPv4 address
  158. Sum of strings
  159. List rotation - left/right
  160. shallow/deep copy
  161. Converting integer to binary number
  162. Creating a directory and a file
  163. Creating a file if not exists
  164. Invoking a python file from another
  165. Sorting IP addresses
  166. Word Frequency
  167. Printing spiral pattern from a 2D array - I. Clock-wise
  168. Printing spiral pattern from a 2D array - II. Counter-Clock-wise
  169. Find a minimum integer not in the input list
  170. I. Find longest sequence of zeros in binary representation of an integer
  171. II. Find longest sequence of zeros in binary representation of an integer - should be surrounded with 1
  172. Find a missing element from a list of integers
  173. Find an unpaired element from a list of integers
  174. Prefix sum : Passing cars
  175. Prefix sum : count the number of integers divisible by k in range [A,B]
  176. Can make a triangle?
  177. Dominant element of a list
  178. Minimum perimeter
  179. MinAbsSumOfTwo
  180. Ceiling - Jump Frog
  181. Brackets - Nested parentheses
  182. Brackets - Nested parentheses of multiple types
  183. Left rotation - list shift
  184. MaxProfit
  185. Stack - Fish
  186. Stack - Stonewall
  187. Factors or Divisors
  188. String replace in files 1
  189. String replace in files 2
  190. Using list as the default_factory for defaultdict
  191. Leap year
  192. Capitalize
  193. Log Parsing
  194. Getting status_code for a site
  195. 2D-Array - Max hourglass sum
  196. New Year Chaos - list
  197. List (array) manipulation - list
  198. Hash Tables: Ransom Note
  199. Count Triplets with geometric progression
  200. Strings: Check if two strings are anagrams
  201. Strings: Making Anagrams
  202. Strings: Alternating Characters
  203. Special (substring) Palindrome
  204. String with the same frequency of characters
  205. Common Child
  206. Fraudulent Activity Notifications
  207. Maximum number of toys
  208. Min Max Riddle
  209. Poisonous Plants with Pesticides
  210. Common elements of 2 lists - Complexity
  211. Get execution time using decorator(@)
  212. Conver a string to lower case and split using decorator(@)
  213. Python assignment and memory location
  214. shallow copy vs deep copy for compound objects (such as a list)
  215. Generator with Fibonacci
  216. Iterator with list
  217. Second smallest element of a list
  218. *args, **kargs, and positional args
  219. Write a function, fn('x','y',3) that returns ['x1', 'y1', 'x2', 'y2', 'x3', 'y3']
  220. sublist or not
  221. any(), all()
  222. Flattening a list
  223. Select an element from a list
  224. Circularly identical lists
  225. Difference between two lists
  226. Reverse a list
  227. Split a list with a step
  228. Break a list and make chunks of size n
  229. Remove duplicate consecutive elements from a list
  230. Combination of elements from two lists
  231. Adding a sublist
  232. Replace the first occurence of a value
  233. Sort the values of the first list using the second list
  234. Transpose of a matrix (nested list)
  235. Binary Gap
  236. Powerset
  237. Round Robin
  238. Fixed-length chunks or blocks
  239. Accumulate
  240. Dropwhile
  241. Groupby
  242. Simple product
  243. Simple permutation
  244. starmap(fn, iterable)
  245. zip_longest(*iterables, fillvalue=None)
  246. What is the correct way to write a doctest?
  247. enumerate(iterable, start=0)
  248. collections.defaultdict - grouping a sequence of key-value pairs into a dictionary of lists
  249. What is the purpose of the 'self' keyword when defining or calling instance methods?
  250. collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
  251. zipped
  252. What is key difference between a set and a list?
  253. What does a class's init() method do?
  254. Class methods
  255. Permutations and combinations of ['A','B','C']
  256. Sort list of dictionaries by values
  257. Return a list of unique words
  258. hashlib
  259. encode('utf-8')
  260. Reading in CSV file
  261. Count capital letters in a file
  262. is vs ==
  263. Create a matrix : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  264. Binary to integer and check if it's the power of 2
  265. urllib.request.urlopen() and requests
  266. Game statistics
  267. Chess - pawn race
  268. Decoding a string
  269. Determinant of a matrix - using numpy.linalg.det()
  270. Revenue from shoe sales - using collections.Counter()
  271. Rangoli
  272. Unique characters
  273. Valid UID
  274. Permutations of a string in lexicographic sorted order
  275. Nested list
  276. Consecutive digit count
  277. Find a number that occurs only once
  278. Sorting a two-dimensional array
  279. Reverse a string
  280. Generate random odd numbers in a range
  281. Shallow vs Deep copy
  282. Transpose matrix
  283. Are Arguments in Python Passed by Value or by Reference?
  284. re: Is a string alphanumeric?
  285. reversed()
  286. Caesar's cipher, or shift cipher, Caesar's code, or Caesar shift
  287. Every other words
  288. re: How can we check if an email address is valid or not?
  289. re: How to capture temperatures of a text
  290. re.split(): How to split a text.
  291. How can we merge two dictionaries?
  292. How can we combine two dictionaries?
  293. What is the difference between a generator and a list?
  294. Pairs of a given array A whose sum value is equal to a target value N
  295. Adding two integers without plus
  296. isinstance() vs type()
  297. What is a decorator?
  298. In Python slicing, what does my_list[-3:2:-2] slice do?
  299. Revisit sorting dict - counting chars in a text file
  300. re: Transforming a date format using re.sub
  301. How to replace the newlines in csv file with tabs?
  302. pandas.merge
  303. How to remove duplicate charaters from a string?
  304. Implement a class called ComplexNumber
  305. Find a word frequency
  306. Get the top 3 most frequent characters of a string
  307. Just seen and ever seen
  308. Capitalizing the full name
  309. Counting Consequitive Characters
  310. Calculate Product of a List of Integers Provided using input()
  311. How many times a substring appears in a string
  312. Hello, first_name last_name
  313. String validators
  314. Finding indices that a char occurs in a list
  315. itertools combinations








Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...




Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master