The 4-part structure — Input → Process → Output → Main Function — is an excellent reusable template for solving both simple and complex problems in Python.
Let’s now refine this template into a more scalable pattern that can help you solve:
- Palindromes
- Consecutive equal strings
- Binary search
- Sorting
- Min distance problems
- Or any real-world problem
✅ Upgraded Python Problem-Solving Template
# 1. Input Function
def get_input():
"""
Take user input or read from file, API, etc.
Example: list of numbers or a string
"""
raw_data = input("Enter space-separated numbers: ") # Example
data = list(map(int, raw_data.strip().split()))
return data
# 2. Preprocessing Function (Optional)
def preprocess(data):
"""
Clean, validate, or transform the input data if needed.
Example: sorting, removing duplicates, filtering
"""
return data # Modify as needed
# 3. Core Logic Function
def solve(data):
"""
Core logic to solve the problem.
Write logic here in steps:
1. Understand pattern
2. Handle edge cases
3. Write logic (loop, conditions, recursion, etc.)
"""
# Example: Check if list is sorted
return data == sorted(data)
# 4. Output Function
def show_output(result):
"""
Print or return results in required format.
"""
print("Result:", result)
# 5. Main Controller
def main():
data = get_input()
data = preprocess(data)
result = solve(data)
show_output(result)
# 6. Run the program
if __name__ == "__main__":
main()
💡 Example 1: Palindrome String Check
def get_input():
return input("Enter a string: ").strip()
def preprocess(data):
return data.lower()
def solve(data):
return data == data[::-1]
def show_output(result):
print("Is Palindrome?", result)
def main():
data = get_input()
data = preprocess(data)
result = solve(data)
show_output(result)
if __name__ == "__main__":
main()
💡 Example 2: Binary Search
def get_input():
arr = list(map(int, input("Enter sorted list: ").split()))
target = int(input("Enter target: "))
return arr, target
def solve(data):
arr, target = data
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def show_output(result):
print("Index found at:", result)
def main():
data = get_input()
result = solve(data)
show_output(result)
if __name__ == "__main__":
main()
🧠 Step-by-Step Thinking Template (Before Coding)
You can use this logical flow or pseudo-template in your notebook:
- Understand the problem
- What are the inputs/outputs?
- Constraints (length, range, time)?
- Break it down
- Write steps or flowcharts.
- Identify operations (loop, condition, sort, etc.)
- Write pseudo-code
Example:for each char in string: check if char == last char
- Implement in code using the 5-step template
🏗️ For Math-heavy or Logic-heavy Problems (e.g., Minimum Distance)
You might add this variation:
# You can pass additional helper functions here if logic is modular.
def solve_min_distance(arr, x, y):
min_dist = float('inf')
prev = -1
for i, val in enumerate(arr):
if val == x or val == y:
if prev != -1 and arr[prev] != val:
min_dist = min(min_dist, i - prev)
prev = i
return min_dist if min_dist != float('inf') else -1
🧩 Summary: Template You Can Use For Any Python Problem
Step | Description | Optional? |
---|---|---|
get_input() | Get data from user, file, or code | No |
preprocess() | Clean, transform data before logic | Yes |
solve() | Core logic: loop, condition, math, etc. | No |
show_output() | Display or return result | No |
main() | Connects all parts, clean flow | No |
You’re absolutely right — the solve()
or process()
step is the heart of any problem-solving template, and customizing it well is what separates a beginner from an expert.
Let’s break this down into a step-by-step strategy for customizing the logic part of your code — especially for problems like palindrome, string operations, search/sort, distance, or dynamic logic.
✅ 1. Master Template: Input → Logic → Output
# 1. Input
def get_input():
return input("Enter something: ")
# 2. Process / Logic
def process(data):
# Your logic goes here
return data == data[::-1] # Example for palindrome
# 3. Output
def show_result(result):
print("Result is:", result)
# 4. Main Function
def main():
data = get_input()
result = process(data)
show_result(result)
main()
Now let’s focus on customizing the process()
step.
🧠 2. Key Questions to Design the Logic (Use This Mental Checklist)
🧩 Step-by-step logic builder:
Step | Question to Ask | Example Decision |
---|---|---|
1 | What is the input type and structure? | String? List? 2D matrix? Tree? |
2 | Do I need to loop? | Yes, for traversal or comparisons |
3 | Should I use a data structure to store/track something? | Set for uniqueness, Dict for counting |
4 | Do I need to compare, swap, sort, or calculate something? | Sort for ordering, Swap for bubble sort |
5 | Is it a pattern or state-based? | Use DP, Recursion, or Greedy |
6 | Is optimization needed (space/time)? | Use better structure, precompute, etc. |
🔧 3. Examples of Customizing the solve()
/ process()
Step
🔁 A. Palindrome with Loop Instead of Slice:
def is_palindrome(data):
left, right = 0, len(data) - 1
while left < right:
if data[left] != data[right]:
return False
left += 1
right -= 1
return True
When to use: When you want more control (case-insensitive, remove non-alphanumeric).
🎯 B. Consecutive Equal String Checker
def has_consecutive_equal(data):
for i in range(1, len(data)):
if data[i] == data[i-1]:
return True
return False
👉 Used for: Detecting repeated letters like "aabbcc"
or "helloo"
.
🔍 C. Binary Search (Sorted List Required)
def binary_search(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
When to use: Large sorted data, log-time search.
🧮 D. Sorting with Swap Logic (Bubble Sort Style)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
When to use: Learning swaps and logic structure.
📏 E. Minimum Distance Between Duplicates
def min_distance(arr):
seen = {}
min_dist = float('inf')
for i, val in enumerate(arr):
if val in seen:
min_dist = min(min_dist, i - seen[val])
seen[val] = i
return min_dist if min_dist != float('inf') else -1
When to use: Optimize with a dictionary instead of nested loops.
📐 4. Common Structures to Use Based on Problem
Problem Type | Best Data Structure |
---|---|
Uniqueness | set() |
Frequency Count | dict() or collections.Counter() |
Sequence (ordered) | list , deque |
Mapping (index to value) | dict() |
Range Query | prefix sum , segment tree |
Recursive State | dict or memo for DP |
Graph | dict of lists , set , queue for BFS |
📌 5. General Pseudocode Template to Write for Any Problem
1. Understand the input and output clearly.
2. Think of simple examples: dry run manually.
3. Break down the process in human steps:
- Loop through?
- Compare each element?
- Count something?
- Store something temporarily?
- Search or sort?
4. Write pseudocode:
- For i in range:
- Check condition
- Store or update something
5. Translate it into Python step-by-step
✅ Final Takeaway: Write, Visualize, Then Code
- Always write pseudocode first, or draw flow/decision tree.
- Use print/debug for dry-run before optimization.
- Structure code using the
Input → Logic → Output
template. - Choose logic patterns based on the problem nature, not guesswork.
Here’s a Python problem-solving framework with 15+ filled examples, all using a consistent structure (Input → Process/Logic → Output → Main). This will help you systematically approach any coding problem — from string manipulation to searching/sorting and algorithm design.
✅ Standard Template to Use
# 1. Input
def get_input():
return input("Enter data: ")
# 2. Logic (Custom core logic)
def process(data):
# Write custom logic here
return data # placeholder
# 3. Output
def show_result(result):
print("Result:", result)
# 4. Main function
def main():
data = get_input()
result = process(data)
show_result(result)
# Uncomment to run
# main()
✅ Let’s Fill It With Real Examples
1. Palindrome Check
def process(data):
return data == data[::-1]
print(process("madam")) # True
2. Binary Search
def process(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(process([1, 3, 5, 7, 9], 5)) # 2
3. Reverse Words in Sentence
def process(data):
return " ".join(data.split()[::-1])
print(process("hello world again")) # "again world hello"
4. Count Character Frequency
from collections import Counter
def process(data):
return dict(Counter(data))
print(process("banana")) # {'b':1, 'a':3, 'n':2}
5. Check Anagram
def process(s1, s2):
return sorted(s1) == sorted(s2)
print(process("listen", "silent")) # True
6. Fibonacci Series (N Terms)
def process(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
print(process(7)) # [0, 1, 1, 2, 3, 5, 8]
7. Factorial (Recursive)
def process(n):
if n == 0:
return 1
return n * process(n - 1)
print(process(5)) # 120
8. Check Consecutive Characters
def process(data):
for i in range(len(data) - 1):
if data[i] == data[i + 1]:
return True
return False
print(process("hello")) # True (l, l)
9. Find Min Distance Between Same Elements
def process(arr):
last_seen = {}
min_dist = float('inf')
for i, val in enumerate(arr):
if val in last_seen:
min_dist = min(min_dist, i - last_seen[val])
last_seen[val] = i
return min_dist if min_dist != float('inf') else -1
print(process([1, 2, 3, 2, 1, 4])) # 2 (between 2s)
10. Merge Sort
def process(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = process(arr[:mid])
right = process(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]
print(process([5, 2, 9, 1])) # [1, 2, 5, 9]
11. String Compression
def process(data):
if not data:
return ""
compressed = []
count = 1
for i in range(1, len(data)):
if data[i] == data[i - 1]:
count += 1
else:
compressed.append(data[i - 1] + str(count))
count = 1
compressed.append(data[-1] + str(count))
return "".join(compressed)
print(process("aaabbccccd")) # a3b2c4d1
12. Two Sum
def process(nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
return []
print(process([2, 7, 11, 15], 9)) # [0, 1]
13. Longest Common Prefix
def process(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
return prefix
print(process(["flower", "flow", "flight"])) # "fl"
14. Valid Parentheses
def process(s):
stack = []
pair = {')': '(', '}': '{', ']': '['}
for char in s:
if char in pair.values():
stack.append(char)
elif char in pair:
if not stack or stack.pop() != pair[char]:
return False
return not stack
print(process("({[]})")) # True
15. Find Missing Number
def process(nums):
n = len(nums) + 1
expected = n * (n - 1) // 2
return expected - sum(nums)
print(process([0, 1, 2, 4])) # 3
16. Prime Check
def process(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
print(process(17)) # True
🧠 Tips to Decide Logic Strategy
Situation | Strategy |
---|---|
Need fast lookup | Use a set() or dict() |
Need order preserved | Use list() |
Pair comparisons | Use nested loops or sort+scan |
Optimize time | Use binary search, sliding window, prefix sum |
Optimize space | Use in-place update |
Count frequency | Use collections.Counter |
Recursion works well | Tree, backtracking problems |
Index-sensitive | Consider enumerate() |
Leave a Reply