Loading...
More Python Posts
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 calculationsSECONDS_PER_DAY = 86400SECONDS_PER_HOUR = 3600SECONDS_PER_MINUTE = 60# Handle negative timestamps and convert to integertimestamp = int(timestamp_epoch)# Calculate days since epoch and remaining secondsdays_since_epoch = timestamp // SECONDS_PER_DAYremaining_seconds = timestamp % SECONDS_PER_DAY# Calculate hours, minutes, secondshours = remaining_seconds // SECONDS_PER_HOURremaining_seconds %= SECONDS_PER_HOURminutes = remaining_seconds // SECONDS_PER_MINUTEseconds = remaining_seconds % SECONDS_PER_MINUTE# Calculate date (simplified, ignoring leap seconds)year = 1970days = days_since_epochwhile days >= 365:is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)days_in_year = 366 if is_leap else 365if days >= days_in_year:days -= days_in_yearyear += 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] = 29month = 0while days >= month_lengths[month]:days -= month_lengths[month]month += 1# Convert to 1-based indexing for month and daymonth += 1day = days + 1# Format the output stringreturn f"{year:04d}-{month:02d}-{day:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"# Example timestamp (Unix epoch seconds)timestamp = 1697054700formatted_date = format_timestamp(timestamp)print(formatted_date + " UTC") # Output: 2023-10-11 18:45:00
# function which return reverse of a stringdef isPalindrome(s):return s == s[::-1]# Driver codes = "malayalam"ans = isPalindrome(s)if ans:print("Yes")else:print("No")
# Python code to find the URL from an input string# Using the regular expressionimport redef Find(string):# findall() has been used# with valid conditions for urls in stringregex = 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 Codestring = 'My Profile: https://codecatch.net'print("Urls: ", Find(string))
# 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 classclass Node:# Constructor to initialize the node objectdef __init__(self, data):self.data = dataself.next = Noneclass LinkedList:# Function to initialize headdef __init__(self):self.head = None# Function to reverse the linked listdef reverse(self):prev = Nonecurrent = self.headwhile(current is not None):next = current.nextcurrent.next = prevprev = currentcurrent = nextself.head = prev# Function to insert a new node at the beginningdef push(self, new_data):new_node = Node(new_data)new_node.next = self.headself.head = new_node# Utility function to print the linked LinkedListdef printList(self):temp = self.headwhile(temp):print temp.data,temp = temp.next# Driver program to test above functionsllist = 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()
from collections import Counterdef find_parity_outliers(nums):return [x for x in numsif x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]]find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]
# Python program for implementation of Bubble Sortdef bubbleSort(arr):n = len(arr)# Traverse through all array elementsfor 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 placefor 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 elementif arr[j] > arr[j+1] :arr[j], arr[j+1] = arr[j+1], arr[j]# Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90]bubbleSort(arr)print ("Sorted array is:")for i in range(len(arr)):print ("%d" %arr[i]),