Coding Questions X - 2024
import collections name = "aabbbccde" def get_top(d, n): print(f"input dictionary d = {d}") # sorted list of tuples st = sorted(d.items(), key=lambda x:x[1], reverse=True) print(f"sorted tuples = {st}") return st[0:n] # method 1 dict_1 = dict(collections.Counter(name)) top3_1 = get_top(dict_1, 3) print(f"top3_1 = {top3_1}") # method 2 dict_2 = collections.defaultdict(int) for c in name: dict_2[c] += 1 top3_2 = get_top(dict(dict_2), 3) print(f"top3_2 = {top3_2}") # method 3 dict_3 = dict.fromkeys(name,0) for c in name: dict_3[c] += 1 top3_3 = get_top(dict_3, 3) print(f"top3_3 = {top3_3}")
Output:
input dictionary d = {'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1} sorted tuples = [('b', 3), ('a', 2), ('c', 2), ('d', 1), ('e', 1)] top3_1 = [('b', 3), ('a', 2), ('c', 2)] input dictionary d = {'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1} sorted tuples = [('b', 3), ('a', 2), ('c', 2), ('d', 1), ('e', 1)] top3_2 = [('b', 3), ('a', 2), ('c', 2)] input dictionary d = {'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1} sorted tuples = [('b', 3), ('a', 2), ('c', 2), ('d', 1), ('e', 1)] top3_3 = [('b', 3), ('a', 2), ('c', 2)]
ss = 'AAAABBBCCDAABBBCCC' # → A B C D A B C justseen = [ss[0]] for s in ss: if s != justseen[-1]: justseen.append(s) print(f"justseen = {justseen}") # → A B C D everseen = [] for s in ss: if s not in everseen: everseen.append(s) print(f"everseen = {everseen}")
Output:
justseen = ['A', 'B', 'C', 'D', 'A', 'B', 'C'] everseen = ['A', 'B', 'C', 'D']
string.capitalize()
capitalizes the first character while string.upper()
capitalizes all characters of a string!
fullname = 'albert einstein' print(f"fullname = {fullname}") fist_last = fullname.split() for i in range(len(fist_last)): fist_last[i] = fist_last[i].capitalize() fullname_capitalized = ' '.join(fist_last) print(f"fullname_capitalized = {fullname_capitalized}")
Output:
fullname = albert einstein fullname_capitalized = Albert Einstein
'abbbcaa' -> (1,'a') (3,'b') (1,'c') (2,'a'): 'a' appears once, 'b' three times, 'c' once, and then 'a' 2 times.
# 'abbbcaa' -> (1,'a') (3,'b') (1,'c') (2,'a') s = 'abbbcaa' c = s[0] count = 1 output = [] for i in range(1,len(s)): if c != s[i] or i == len(s)-1: # new char or end_of_string output.append(str((count,c))) count = 1 c = s[i] else: count += 1 print(f"output = {output}") final_output = ' '.join(output) print(f"final_output = {final_output}")
Output:
output = ["(1, 'a')", "(3, 'b')", "(1, 'c')", "(1, 'a')"] final_output = (1, 'a') (3, 'b') (1, 'c') (1, 'a')
# A = [1, 2], B = [3, 4] # input: # 1 2 # 3 4 # Output: # AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] # reading input string of numbers and convert it into a list of integers number_str_a = input('Enter two numbers separated by a space: ').split() number_str_b = input('Enter two numbers separated by a space: ').split() A = [int(x) for x in number_str_a] B = [int(x) for x in number_str_b] print(f"A = {A}, B = {B}") # construct a product using list comprehension AB = [(x,y) for x in A for y in B] print(f"AxB = {AB}")
Output:
A = [1, 2], B = [3, 4] AxB = [(1, 3), (1, 4), (2, 3), (2, 4)]
For example, for a given string, 'ABCDCDC', we want to find the number of times that a substring, 'CDC' occurs in the string. In this case, 'ABCDCDC' and ABCDCDC', so the answer is 2.
Now, find the same substring 'CDC' in a string of 'ABCDCDCCACDCB'
s = 'ABCDCDCCACDCB' sub = 'CDC' count = 0 for i in range(len(s)-2): if s[i:i+len(sub)] == sub: count += 1 print(f"count = {count}")
Output:
count = 3
Use the following str.isalnum()
, str.isalpha()
, str.isdigit()
, str.islower()
, and str.isupper()
string validators,
read an input string, and then print out True/False per line. Note that the validators return True if all characters of a string satisfy the condition.
True if string has any alphanumeric characters. Otherwise, False. True if string has any alphabetical characters. Otherwise, False. True if string has any digits. Otherwise, False. True if string has any lowercase characters. Otherwise, False. True if string has any uppercase characters. Otherwise, False.
Note the word any
!
def str_validation(s): if any([c.isalnum() for c in s]): print(f"True") else: print(f"False") if any([c.isalpha() for c in s]): print(f"True") else: print(f"False") if any([c.isdigit() for c in s]): print(f"True") else: print(f"False") if any([c.islower() for c in s]): print(f"True") else: print(f"False") if any([c.isupper() for c in s]): print(f"True") else: print(f"False") if __name__ == '__main__': s = input("Enter a string (alphanumeric, etc...): ") str_validation(s)
Output #1:
Enter a string (alphanumeric, etc...): A1a True True True True True
Output #2:
Enter a string (alphanumeric, etc...): 123 True False True False False
Output #3:
Enter a string (alphanumeric, etc...): Abc True True False True True
We have two lists: A = ['a', 'a', 'b', 'a', 'b', 'a', 'b'] and B = ['a', 'b', 'c']. Find the positions where each character in B appears in A. For example, the character 'a' from B appears in A at index positions 0, 1, 3, and 5. If a character in B, like 'c', is not found in A, the index should be -1.
from collections import defaultdict A = ['a', 'a', 'b', 'a', 'b', 'a', 'b'] B = ['a', 'b', 'c'] d = defaultdict(list) for y in B: d[y] = [i for i,v in enumerate(A) if v == y] if y not in A: d[y] = -1 for i in d.items(): print(i)
Output:
('a', [0, 1, 3, 5]) ('b', [2, 4, 6]) ('c', -1)
Print all possible combinations of the input string characters, up to size n.
from itertools import combinations inp = input('Enter a string and an integer k: ').split() print(f"inp = {inp}") s = inp[0]; n = int(inp[1]) print(f"s = {s}, n = {n}") # Print all possible combinations of chars of the input string, # up to size n. a = [] for i in range(n): a.extend(list(combinations(s,i+1))) print(f"a = {a}") aa = [] for x in a: aa.append(''.join(x)) print(f"aa = {aa}")
Output:
Enter a string and an integer k: abc 2 inp = ['abc', '2'] s = abc, n = 2 a = [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c')] aa = ['a', 'b', 'c', 'ab', 'ac', 'bc']
- 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
List of codes Q & A
- Merging two sorted list
- Get word frequency - initializing dictionary
- Initializing dictionary with list
- map, filter, and reduce
- Write a function f() - yield
- What is __init__.py?
- Build a string with the numbers from 0 to 100, "0123456789101112..."
- Basic file processing: Printing contents of a file - "with open"
- How can we get home directory using '~' in Python?
- The usage of os.path.dirname() & os.path.basename() - os.path
- Default Libraries
- range vs xrange
- Iterators
- Generators
- Manipulating functions as first-class objects
- docstrings vs comments
- using lambdda
- classmethod vs staticmethod
- Making a list with unique element from a list with duplicate elements
- What is map?
- What is filter and reduce?
- *args and **kwargs
- mutable vs immutable
- Difference between remove, del and pop on lists
- Join with new line
- Hamming distance
- Floor operation on integers
- Fetching every other item in the list
- Python type() - function
- Dictionary Comprehension
- Sum
- Truncating division
- Python 2 vs Python 3
- len(set)
- Print a list of file in a directory
- Count occurrence of a character in a Python string
- Make a prime number list from (1,100)
- Reversing a string - Recursive
- Reversing a string - Iterative
- Reverse a number
- Output?
- Merging overlapped range
- Conditional expressions (ternary operator)
- Packing Unpacking
- Function args
- Unpacking args
- Finding the 1st revision with a bug
- Which one has higher precedence in Python? - NOT, AND , OR
- Decorator(@) - with dollar sign($)
- Multi-line coding
- Recursive binary search
- Iterative binary search
- Pass by reference
- Simple calculator
- iterator class that returns network interfaces
- Converting domain to ip
- How to count the number of instances
- Python profilers - cProfile
- Calling a base class method from a child class that overrides it
- How do we find the current module name?
- Why did changing list 'newL' also change list 'L'?
- Constructing dictionary - {key:[]}
- Colon separated sequence
- Converting binary to integer
- 9+99+999+9999+...
- Calculating balance
- Regular expression - findall
- Chickens and pigs
- Highest possible product
- Implement a queue with a limited size
- Copy an object
- Filter
- Products
- Pickle
- Overlapped Rectangles
- __dict__
- Fibonacci I - iterative, recursive, and via generator
- Fibonacci II - which method?
- Fibonacci III - find last two digits of Nth Fibonacci number
- Write a Stack class returning Max item at const time A
- Write a Stack class returning Max item at const time B
- Finding duplicate integers from a list - 1
- Finding duplicate integers from a list - 2
- Finding duplicate integers from a list - 3
- Reversing words 1
- Parenthesis, a lot of them
- Palindrome / Permutations
- Constructing new string after removing white spaces
- Removing duplicate list items
- Dictionary exercise
- printing numbers in Z-shape
- Factorial
- lambda
- lambda with map/filter/reduce
- Number of integer pairs whose difference is K
- iterator vs generator
- Recursive printing files in a given directory
- Bubble sort
- What is GIL (Global Interpreter Lock)?
- Word count using collections
- Pig Latin
- List of anagrams from a list of words
- lamda with map, filer and reduce functions
- Write a code sending an email using gmail
- histogram 1 : the frequency of characters
- histogram 2 : the frequency of ip-address
- Creating a dictionary using tuples
- Getting the index from a list
- Looping through two lists side by side
- Dictionary sort with two keys : primary / secondary keys
- Writing a file downloaded from the web
- Sorting csv data
- Reading json file
- Sorting class objects
- Parsing Brackets
- Printing full path
- str() vs repr()
- Missing integer from a sequence
- Polymorphism
- Product of every integer except the integer at that index
- What are accessors, mutators, and @property?
- N-th to last element in a linked list
- Implementing linked list
- Removing duplicate element from a list
- List comprehension
- .py vs .pyc
- Binary Tree
- Print 'c' N-times without a loop
- Quicksort
- Dictionary of list
- Creating r x c matrix
- Transpose of a matrix
- str.isalpha() & str.isdigit()
- Regular expression
- What is Hashable? Immutable?
- Convert a list to a string
- Convert a list to a dictionary
- List - append vs extend vs concatenate
- Use sorted(list) to keep the original list
- list.count()
- zip(list,list) - join elements of two lists
- zip(list,list) - weighted average with two lists
- Intersection of two lists
- Dictionary sort by value
- Counting the number of characters of a file as One-Liner
- Find Armstrong numbers from 100-999
- Find GCF (Greatest common divisor)
- Find LCM (Least common multiple)
- Draws 5 cards from a shuffled deck
- Dictionary order by value or by key
- Regular expression - re.split()
- Regular expression : re.match() vs. re.search()
- Regular expression : re.match() - password check
- Regular expression : re.search() - group capturing
- Regular expression : re.findall() - group capturin
- Prime factors : n = products of prime numbers
- Valid IPv4 address
- Sum of strings
- List rotation - left/right
- shallow/deep copy
- Converting integer to binary number
- Creating a directory and a file
- Creating a file if not exists
- Invoking a python file from another
- Sorting IP addresses
- Word Frequency
- Printing spiral pattern from a 2D array - I. Clock-wise
- Printing spiral pattern from a 2D array - II. Counter-Clock-wise
- Find a minimum integer not in the input list
- I. Find longest sequence of zeros in binary representation of an integer
- II. Find longest sequence of zeros in binary representation of an integer - should be surrounded with 1
- Find a missing element from a list of integers
- Find an unpaired element from a list of integers
- Prefix sum : Passing cars
- Prefix sum : count the number of integers divisible by k in range [A,B]
- Can make a triangle?
- Dominant element of a list
- Minimum perimeter
- MinAbsSumOfTwo
- Ceiling - Jump Frog
- Brackets - Nested parentheses
- Brackets - Nested parentheses of multiple types
- Left rotation - list shift
- MaxProfit
- Stack - Fish
- Stack - Stonewall
- Factors or Divisors
- String replace in files 1
- String replace in files 2
- Using list as the default_factory for defaultdict
- Leap year
- Capitalize
- Log Parsing
- Getting status_code for a site
- 2D-Array - Max hourglass sum
- New Year Chaos - list
- List (array) manipulation - list
- Hash Tables: Ransom Note
- Count Triplets with geometric progression
- Strings: Check if two strings are anagrams
- Strings: Making Anagrams
- Strings: Alternating Characters
- Special (substring) Palindrome
- String with the same frequency of characters
- Common Child
- Fraudulent Activity Notifications
- Maximum number of toys
- Min Max Riddle
- Poisonous Plants with Pesticides
- Common elements of 2 lists - Complexity
- Get execution time using decorator(@)
- Conver a string to lower case and split using decorator(@)
- Python assignment and memory location
- shallow copy vs deep copy for compound objects (such as a list)
- Generator with Fibonacci
- Iterator with list
- Second smallest element of a list
- *args, **kargs, and positional args
- Write a function, fn('x','y',3) that returns ['x1', 'y1', 'x2', 'y2', 'x3', 'y3']
- sublist or not
- any(), all()
- Flattening a list
- Select an element from a list
- Circularly identical lists
- Difference between two lists
- Reverse a list
- Split a list with a step
- Break a list and make chunks of size n
- Remove duplicate consecutive elements from a list
- Combination of elements from two lists
- Adding a sublist
- Replace the first occurence of a value
- Sort the values of the first list using the second list
- Transpose of a matrix (nested list)
- Binary Gap
- Powerset
- Round Robin
- Fixed-length chunks or blocks
- Accumulate
- Dropwhile
- Groupby
- Simple product
- Simple permutation
- starmap(fn, iterable)
- zip_longest(*iterables, fillvalue=None)
- What is the correct way to write a doctest?
- enumerate(iterable, start=0)
- collections.defaultdict - grouping a sequence of key-value pairs into a dictionary of lists
- What is the purpose of the 'self' keyword when defining or calling instance methods?
- collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
- zipped
- What is key difference between a set and a list?
- What does a class's init() method do?
- Class methods
- Permutations and combinations of ['A','B','C']
- Sort list of dictionaries by values
- Return a list of unique words
- hashlib
- encode('utf-8')
- Reading in CSV file
- Count capital letters in a file
- is vs ==
- Create a matrix : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Binary to integer and check if it's the power of 2
- urllib.request.urlopen() and requests
- Game statistics
- Chess - pawn race
- Decoding a string
- Determinant of a matrix - using numpy.linalg.det()
- Revenue from shoe sales - using collections.Counter()
- Rangoli
- Unique characters
- Valid UID
- Permutations of a string in lexicographic sorted order
- Nested list
- Consecutive digit count
- Find a number that occurs only once
- Sorting a two-dimensional array
- Reverse a string
- Generate random odd numbers in a range
- Shallow vs Deep copy
- Transpose matrix
- Are Arguments in Python Passed by Value or by Reference?
- re: Is a string alphanumeric?
- reversed()
- Caesar's cipher, or shift cipher, Caesar's code, or Caesar shift
- Every other words
- re: How can we check if an email address is valid or not?
- re: How to capture temperatures of a text
- re.split(): How to split a text.
- How can we merge two dictionaries?
- How can we combine two dictionaries?
- What is the difference between a generator and a list?
- Pairs of a given array A whose sum value is equal to a target value N
- Adding two integers without plus
- isinstance() vs type()
- What is a decorator?
- In Python slicing, what does my_list[-3:2:-2] slice do?
- Revisit sorting dict - counting chars in a text file
- re: Transforming a date format using re.sub
- How to replace the newlines in csv file with tabs?
- pandas.merge
- How to remove duplicate charaters from a string?
- Implement a class called ComplexNumber
- Find a word frequency
- Get the top 3 most frequent characters of a string
- Just seen and ever seen
- Capitalizing the full name
- Counting Consequitive Characters
- Calculate Product of a List of Integers Provided using input()
- How many times a substring appears in a string
- Hello, first_name last_name
- String validators
- Finding indices that a char occurs in a list
- 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