Skip to main content

Selection sort

Nov 19, 2022CodeCatch
Loading...

More Python Posts

Unix Time to Human Readable Time

Jun 26, 2025AustinLeath

0 likes • 1 view

def format_timestamp(timestamp_epoch):
"""
Convert epoch timestamp to formatted datetime string without using datetime package.
Args:
timestamp_epoch (int/float): Unix epoch timestamp (seconds since 1970-01-01 00:00:00 UTC)
Returns:
str: Formatted datetime string in 'YYYY-MM-DD HH:MM:SS' format
"""
# Constants for time calculations
SECONDS_PER_DAY = 86400
SECONDS_PER_HOUR = 3600
SECONDS_PER_MINUTE = 60
# Handle negative timestamps and convert to integer
timestamp = int(timestamp_epoch)
# Calculate days since epoch and remaining seconds
days_since_epoch = timestamp // SECONDS_PER_DAY
remaining_seconds = timestamp % SECONDS_PER_DAY
# Calculate hours, minutes, seconds
hours = remaining_seconds // SECONDS_PER_HOUR
remaining_seconds %= SECONDS_PER_HOUR
minutes = remaining_seconds // SECONDS_PER_MINUTE
seconds = remaining_seconds % SECONDS_PER_MINUTE
# Calculate date (simplified, ignoring leap seconds)
year = 1970
days = days_since_epoch
while days >= 365:
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
days_in_year = 366 if is_leap else 365
if days >= days_in_year:
days -= days_in_year
year += 1
# Month lengths (non-leap year for simplicity, adjusted later for leap years)
month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
month_lengths[1] = 29
month = 0
while days >= month_lengths[month]:
days -= month_lengths[month]
month += 1
# Convert to 1-based indexing for month and day
month += 1
day = days + 1
# Format the output string
return f"{year:04d}-{month:02d}-{day:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
# Example timestamp (Unix epoch seconds)
timestamp = 1697054700
formatted_date = format_timestamp(timestamp)
print(formatted_date + " UTC") # Output: 2023-10-11 18:45:00

Palindrome checker

Nov 19, 2022CodeCatch

0 likes • 6 views

# function which return reverse of a string
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

Find URL in string

Nov 19, 2022CodeCatch

0 likes • 0 views

# Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)
return [x[0] for x in url]
# Driver Code
string = 'My Profile: https://codecatch.net'
print("Urls: ", Find(string))

Reverse a linked list

Nov 19, 2022CodeCatch

0 likes • 0 views

# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next'
#variable is getting created in each loop.
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print "Given Linked List"
llist.printList()
llist.reverse()
print "\nReversed Linked List"
llist.printList()

find parity outliers

Nov 19, 2022CodeCatch

0 likes • 4 views

from collections import Counter
def find_parity_outliers(nums):
return [
x for x in nums
if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]
]
find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]

Bubble sort

Nov 19, 2022CodeCatch

0 likes • 3 views

# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),