Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find Elements Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
Find the Majority Element in Python with Boyer-Moore Vote
Use Boyer-Moore majority vote to find the element appearing more than n/2 times in an array in O(n) time and O(1) space.
def majority_element(nums):
candidate = None
count = 0
for num in nums:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate
if __name__ == "__main__":
nums = [2, 2, 1, 1, 1, 2, 2]
result = majority_element(nums)
print(f"Major…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.