Skip to content

Instantly share code, notes, and snippets.

View jones's full-sized avatar

Tristan Jones jones

  • Berkeley, CA
View GitHub Profile
@jones
jones / happy.py
Created September 2, 2015 21:05
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Thos…
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seenNums = set()
while n > 1 and (n not in seenNums):
seenNums.add(n)
n = sum(map(lambda x: x**2, map(int, list(str(n)))))
@jones
jones / groupanagrams.py
Created September 2, 2015 23:55
Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note: For the return value, each inner list's elements must follow the lexicographic order. All inputs will be in lower-case.
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
from itertools import groupby
sortedAnagrams = sorted(sorted(strs), key=lambda a: sorted(a))
return [list(v) for k,v in groupby(sortedAnagrams, key=lambda a: sorted(a))]
@jones
jones / mergeintervals.py
Created September 3, 2015 05:14
Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]