Newton method:
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
xi = x
while xi*xi > x:
xi = int((xi+x/xi)/2)
return xi
Sunday, December 17, 2017
Sunday, December 10, 2017
162. Find Peak Element
class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left,right = 0, len(nums)-1
while left < right:
mid = (left + right)//2
if nums[mid] < nums[mid+1]:
left = mid+1
else:
right = mid
return left
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left,right = 0, len(nums)-1
while left < right:
mid = (left + right)//2
if nums[mid] < nums[mid+1]:
left = mid+1
else:
right = mid
return left
500. Keyboard Row
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboard= ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
new_list=[]
for a_word in words:
lower_a_word = a_word.lower()
for line in keyboard:
if set(lower_a_word).issubset(set(line)):
new_list.append(a_word)
return new_list
best solution
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboard= ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
new_list=[]
for a_word in words:
lower_a_word = a_word.lower()
for line in keyboard:
if set(lower_a_word).issubset(set(line)):
new_list.append(a_word)
return new_list
best solution
class Solution(object):
def findWords(self, words):
line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
ret = []
for word in words:
w = set(word.lower())
if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
ret.append(word)
return ret
561. Array Partition I
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
new_array = sorted(nums)
return sum(new_array[::2])
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
new_array = sorted(nums)
return sum(new_array[::2])
Thursday, December 7, 2017
78. Subsets
from itertools import combinations
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
k = 0
new_list= []
while k < len(nums)+1:
for c in combinations(nums, k):
new_list.append(list(c))
k +=1
return new_list
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
k = 0
new_list= []
while k < len(nums)+1:
for c in combinations(nums, k):
new_list.append(list(c))
k +=1
return new_list
541. Reverse String II
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
new_list = list(s)
i = 0
while i< len(s):
if i+k > len(s):
new_list[i:] = new_list[i:][::-1]
else:
new_list[i:i+k] = new_list[i:i+k][::-1]
i = i+k*2
return ''.join(new_list)
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
new_list = list(s)
i = 0
while i< len(s):
if i+k > len(s):
new_list[i:] = new_list[i:][::-1]
else:
new_list[i:i+k] = new_list[i:i+k][::-1]
i = i+k*2
return ''.join(new_list)
Sunday, December 3, 2017
414. Third Maximum Number
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
new_list = list(set(nums))
sorted_new_list = sorted(new_list)
try:
return sorted_new_list[-3]
except:
return sorted_new_list[-1]
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = float("-inf")
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c =n, b
elif b > n > c:
c = n
return c if c != float("-inf") else a
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
new_list = list(set(nums))
sorted_new_list = sorted(new_list)
try:
return sorted_new_list[-3]
except:
return sorted_new_list[-1]
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = float("-inf")
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c =n, b
elif b > n > c:
c = n
return c if c != float("-inf") else a
Saturday, December 2, 2017
349. Intersection of Two Arrays
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1)&set(nums2))
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1)&set(nums2))
347. Top K Frequent Elements
from collections import Counter
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = Counter(nums)
k_frequent = counts.most_common(k)
return [x[0] for x in k_frequent]
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = Counter(nums)
k_frequent = counts.most_common(k)
return [x[0] for x in k_frequent]
258. Add Digits
class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:
return 0
else:
return 1 + (num - 1) % 9
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:
return 0
else:
return 1 + (num - 1) % 9
Tuesday, November 28, 2017
215. Kth Largest Element in an Array
import heapq
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
new_list = heapq.nlargest(k,nums)
return new_list.pop()
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
new_list = heapq.nlargest(k,nums)
return new_list.pop()
Saturday, November 25, 2017
67. Add Binary
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2)+int(b,2))[2:]
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2)+int(b,2))[2:]
83. Remove Duplicates from Sorted List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(None)
dummy.next = head
previous = dummy
current = head
while current:
if current.val == previous.val:
previous.next = current.next
else:
previous = current
current = current.next
return dummy.next
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(None)
dummy.next = head
previous = dummy
current = head
while current:
if current.val == previous.val:
previous.next = current.next
else:
previous = current
current = current.next
return dummy.next
203. Remove Linked List Elements
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy = ListNode(0)
previous = dummy
dummy.next = head
current = head
while current:
if current.val == val:
previous.next = current.next
else:
previous = current
current = current.next
return dummy.next
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy = ListNode(0)
previous = dummy
dummy.next = head
current = head
while current:
if current.val == val:
previous.next = current.next
else:
previous = current
current = current.next
return dummy.next
237. Delete Node in a Linked List
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
231. Power of Two
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if bin(n)[2] == "1" and bin(n)[3:] == (len(bin(n))-3) * "0":
return True
else:
return False
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if bin(n)[2] == "1" and bin(n)[3:] == (len(bin(n))-3) * "0":
return True
else:
return False
504. Base 7
class Solution:
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
divider = num
def calculation (divider):
number = ""
while divider > 0:
remainder = divider % 7
divider = divider // 7
number =str(remainder) + number
return number
if divider == 0:
return "0"
if divider < 0:
return "-" + calculation (-divider)
if divider > 0:
return calculation (divider)
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
divider = num
def calculation (divider):
number = ""
while divider > 0:
remainder = divider % 7
divider = divider // 7
number =str(remainder) + number
return number
if divider == 0:
return "0"
if divider < 0:
return "-" + calculation (-divider)
if divider > 0:
return calculation (divider)
476. Number Complement
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return int((len(bin(num))-2)*"1", 2)^num
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return int((len(bin(num))-2)*"1", 2)^num
Wednesday, November 22, 2017
682. Baseball Game
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
new_list = []
for i in range(len(ops)):
if ops[i] == "C":
new_list.pop()
elif ops[i] == "D":
new_list.append(int(new_list[-1])*2)
elif ops[i] == "+":
new_list.append(int(new_list[-1])+int(new_list[-2]))
else:
new_list.append(int(ops[i]))
return sum(new_list)
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
new_list = []
for i in range(len(ops)):
if ops[i] == "C":
new_list.pop()
elif ops[i] == "D":
new_list.append(int(new_list[-1])*2)
elif ops[i] == "+":
new_list.append(int(new_list[-1])+int(new_list[-2]))
else:
new_list.append(int(ops[i]))
return sum(new_list)
657. Judge Route Circle
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
num1 = 0
num2 = 0
for i in moves:
if i == "R":
num1 += 1
if i == "L":
num1 -= 1
if i == "U":
num2 += 1
if i == "D":
num2 -= 1
if num1 == 0 and num2 ==0:
return True
else:
return False
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
num1 = 0
num2 = 0
for i in moves:
if i == "R":
num1 += 1
if i == "L":
num1 -= 1
if i == "U":
num2 += 1
if i == "D":
num2 -= 1
if num1 == 0 and num2 ==0:
return True
else:
return False
451. Sort Characters By Frequency
class Solution:
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
a_dict = {}
b_dict = {}
new_string = ""
new_list = []
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = 1
else:
a_dict[s[i]] += 1
for (keys, values) in a_dict.items():
if values not in b_dict:
b_dict[values] = keys * values
else:
b_dict[values] = b_dict[values] + keys * values
new_list = sorted(list(b_dict.keys()))
for j in new_list:
new_string = b_dict[j] + new_string
return new_string
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
a_dict = {}
b_dict = {}
new_string = ""
new_list = []
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = 1
else:
a_dict[s[i]] += 1
for (keys, values) in a_dict.items():
if values not in b_dict:
b_dict[values] = keys * values
else:
b_dict[values] = b_dict[values] + keys * values
new_list = sorted(list(b_dict.keys()))
for j in new_list:
new_string = b_dict[j] + new_string
return new_string
Tuesday, November 21, 2017
412. Fizz Buzz
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
new_list = []
for i in range(n):
if (i+1) % 15 == 0:
new_list.append("FizzBuzz")
elif (i+1) % 3 == 0:
new_list.append("Fizz")
elif (i+1) % 5 == 0:
new_list.append("Buzz")
else:
new_list.append(str(i+1))
return new_list
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
new_list = []
for i in range(n):
if (i+1) % 15 == 0:
new_list.append("FizzBuzz")
elif (i+1) % 3 == 0:
new_list.append("Fizz")
elif (i+1) % 5 == 0:
new_list.append("Buzz")
else:
new_list.append(str(i+1))
return new_list
537. Complex Number Multiplication
class Solution:
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_list = a.split("+")
b_list = b.split("+")
first_part = int(a_list[0])*int(b_list[0]) + int(a_list[1][:-1])*int(b_list[1][:-1])*(-1)
second_part = str(int(a_list[0])*int(b_list[1][:-1]) + int(b_list[0])*int(a_list[1][:-1]))+"i"
return str(first_part)+"+"+second_part
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_list = a.split("+")
b_list = b.split("+")
first_part = int(a_list[0])*int(b_list[0]) + int(a_list[1][:-1])*int(b_list[1][:-1])*(-1)
second_part = str(int(a_list[0])*int(b_list[1][:-1]) + int(b_list[0])*int(a_list[1][:-1]))+"i"
return str(first_part)+"+"+second_part
Sunday, November 19, 2017
728. Self Dividing Numbers
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
new_list = []
def is_self_dividing (number):
for i in list(str(number)):
if int(i) == 0:
return False
elif number % int(i)!=0:
return False
return True
for number in range(left, right+1):
if is_self_dividing (number) == True:
new_list.append(number)
return new_list
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
new_list = []
def is_self_dividing (number):
for i in list(str(number)):
if int(i) == 0:
return False
elif number % int(i)!=0:
return False
return True
for number in range(left, right+1):
if is_self_dividing (number) == True:
new_list.append(number)
return new_list
387. First Unique Character in a String
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
b_dict = {}
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = i
else:
a_dict[s[i]] = -1
for (a_key, a_value) in a_dict.items():
if a_dict[a_key] != -1:
b_dict[a_key] = a_value
if b_dict == {}:
return -1
else:
return min(b_dict.values())
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
b_dict = {}
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = i
else:
a_dict[s[i]] = -1
for (a_key, a_value) in a_dict.items():
if a_dict[a_key] != -1:
b_dict[a_key] = a_value
if b_dict == {}:
return -1
else:
return min(b_dict.values())
Saturday, November 18, 2017
405. Convert a Number to Hexadecimal
class Solution:
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
digits = "0123456789abcdef"
temp = ""
number = num
if number == 0:
return "0"
elif number < 0:
number += 0x100000000
while number >0:
remain = number % 16
number = number //16
temp += digits[remain]
return temp[::-1]
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
digits = "0123456789abcdef"
temp = ""
number = num
if number == 0:
return "0"
elif number < 0:
number += 0x100000000
while number >0:
remain = number % 16
number = number //16
temp += digits[remain]
return temp[::-1]
461. Hamming Distance
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
693. Binary Number with Alternating Bits
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bits = bin(n)
for i in range(len(bits)-1):
if bits[i] == bits[i+1]:
return False
return True
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bits = bin(n)
for i in range(len(bits)-1):
if bits[i] == bits[i+1]:
return False
return True
155. Min Stack
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1=[]
self.stack2=[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: void
"""
top = self.stack1[-1]
self.stack1.pop()
if top == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1=[]
self.stack2=[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: void
"""
top = self.stack1[-1]
self.stack1.pop()
if top == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Friday, November 17, 2017
345. Reverse Vowels of a String
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
string_copy = s
vowels = "aeiouAEIOU"
vowel_string=""
new_string=""
for i in string_copy:
if i in vowels:
vowel_string+=i
print (vowel_string)
reverse_vowel_string = vowel_string[::-1]
print (reverse_vowel_string)
j = 0
for i in string_copy:
if i in vowels:
new_string += reverse_vowel_string[j]
j+=1
else:
new_string +=i
return new_string
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
string_copy = s
vowels = "aeiouAEIOU"
vowel_string=""
new_string=""
for i in string_copy:
if i in vowels:
vowel_string+=i
print (vowel_string)
reverse_vowel_string = vowel_string[::-1]
print (reverse_vowel_string)
j = 0
for i in string_copy:
if i in vowels:
new_string += reverse_vowel_string[j]
j+=1
else:
new_string +=i
return new_string
599. Minimum Index Sum of Two Lists
class Solution:
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1_dict ={}
dict_2={}
for i in range(len(list1)):
list1_dict[list1[i]] = i
for j in range(len(list2)):
if list2[j] in list1_dict:
add_index = j+list1_dict[list2[j]]
if add_index not in dict_2:
dict_2[add_index]=[]
dict_2[add_index].append(list2[j])
else:
dict_2[add_index].append(list2[j])
return dict_2[min(dict_2.keys())]
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1_dict ={}
dict_2={}
for i in range(len(list1)):
list1_dict[list1[i]] = i
for j in range(len(list2)):
if list2[j] in list1_dict:
add_index = j+list1_dict[list2[j]]
if add_index not in dict_2:
dict_2[add_index]=[]
dict_2[add_index].append(list2[j])
else:
dict_2[add_index].append(list2[j])
return dict_2[min(dict_2.keys())]
Thursday, November 16, 2017
520. Detect Capital
class Solution:
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word == "":
return False
elif word.isupper():
return True
elif word.islower():
return True
elif word[0].isupper():
if word[1:].islower():
return True
else:
return False
else:
return False
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word == "":
return False
elif word.isupper():
return True
elif word.islower():
return True
elif word[0].isupper():
if word[1:].islower():
return True
else:
return False
else:
return False
485. Max Consecutive Ones
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
count = 0
max_count = 0
for i in nums:
if i == 1:
count += 1
elif i == 0:
if max_count < count:
max_count = count
count = 0
return max_count
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
count = 0
max_count = 0
for i in nums:
if i == 1:
count += 1
elif i == 0:
if max_count < count:
max_count = count
count = 0
return max_count
219. Contains Duplicate II
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
a_dict={}
for i in range(len(nums)):
if nums[i] not in a_dict:
a_dict[nums[i]] = i
else:
if i - a_dict[nums[i]] <= k:
return True
else:
a_dict[nums[i]] = i
return False
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
a_dict={}
for i in range(len(nums)):
if nums[i] not in a_dict:
a_dict[nums[i]] = i
else:
if i - a_dict[nums[i]] <= k:
return True
else:
a_dict[nums[i]] = i
return False
28. Implement strStr()
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
Sunday, November 12, 2017
20. Valid Parentheses
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
new_string = ""
left = "({["
right = ")}]"
for i in s:
if i in left:
new_string += i
elif i in right:
if len(new_string) == 0:
return False
if right.index(i)!=left.index(new_string[-1]):
return False
else:
new_string = new_string[:-1]
return len(new_string) == 0
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
new_string = ""
left = "({["
right = ")}]"
for i in s:
if i in left:
new_string += i
elif i in right:
if len(new_string) == 0:
return False
if right.index(i)!=left.index(new_string[-1]):
return False
else:
new_string = new_string[:-1]
return len(new_string) == 0
Monday, November 6, 2017
441. Arranging Coins
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i=1
new_number = n
while new_number >= 0:
new_number = new_number-i
i += 1
return i-2
optimized version:
import math
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(2 * n + 0.25) - 0.5)
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i=1
new_number = n
while new_number >= 0:
new_number = new_number-i
i += 1
return i-2
optimized version:
import math
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(2 * n + 0.25) - 0.5)
242. Valid Anagram
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def construct_dict(a_string):
a_dict={}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
if dict_1 == dict_2:
return True
else:
return False
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def construct_dict(a_string):
a_dict={}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
if dict_1 == dict_2:
return True
else:
return False
58. Length of Last Word
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
new_string = s
new_string = new_string.lower()
new_list = new_string.split()
try:
return len(new_list[-1])
except:
return 0
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
new_string = s
new_string = new_string.lower()
new_list = new_string.split()
try:
return len(new_list[-1])
except:
return 0
Sunday, November 5, 2017
7. Reverse Integer
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
value = 0
if x >= 2147483647 or x <= -2147483647:
return 0
try:
if x > 0:
value = int(str(x)[::-1])
elif x < 0:
value = -int(str(-x)[::-1])
if value >= 2147483647 or value <= -2147483647:
return 0
return value
except OverflowError:
return 0
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
value = 0
if x >= 2147483647 or x <= -2147483647:
return 0
try:
if x > 0:
value = int(str(x)[::-1])
elif x < 0:
value = -int(str(-x)[::-1])
if value >= 2147483647 or value <= -2147483647:
return 0
return value
except OverflowError:
return 0
125. Valid Palindrome
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
else:
new_string = s
new_string = new_string.lower()
new_list = []
for i in new_string:
if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 48 and ord(i) <= 57):
new_list.append(i)
new_string = ("").join(new_list)
print (new_string)
if new_string == new_string[::-1]:
return True
else:
return False
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
else:
new_string = s
new_string = new_string.lower()
new_list = []
for i in new_string:
if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 48 and ord(i) <= 57):
new_list.append(i)
new_string = ("").join(new_list)
print (new_string)
if new_string == new_string[::-1]:
return True
else:
return False
290. Word Pattern
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
a_dict = {}
new_list = str.split()
if len(pattern) != len(new_list):
return False
else:
for i in range(len(pattern)):
if pattern[i] in a_dict:
if a_dict[pattern[i]] != new_list[i]:
return False
else:
if new_list[i] in a_dict.values():
return False
else:
a_dict[pattern[i]] = new_list[i]
return True
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
a_dict = {}
new_list = str.split()
if len(pattern) != len(new_list):
return False
else:
for i in range(len(pattern)):
if pattern[i] in a_dict:
if a_dict[pattern[i]] != new_list[i]:
return False
else:
if new_list[i] in a_dict.values():
return False
else:
a_dict[pattern[i]] = new_list[i]
return True
205. Isomorphic Strings
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
a_dict = {}
if len(s) != len(t):
return False
else:
for i in range(len(s)):
if s[i] in a_dict:
if a_dict[s[i]] != t[i]:
return False
else:
if t[i] in a_dict.values():
return False
else:
a_dict[s[i]] = t[i]
return True
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
a_dict = {}
if len(s) != len(t):
return False
else:
for i in range(len(s)):
if s[i] in a_dict:
if a_dict[s[i]] != t[i]:
return False
else:
if t[i] in a_dict.values():
return False
else:
a_dict[s[i]] = t[i]
return True
Saturday, November 4, 2017
434. Number of Segments in a String
class Solution:
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
new_list = []
new_list = s.split()
return len(new_list)
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
new_list = []
new_list = s.split()
return len(new_list)
35. Search Insert Position
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[-1] < target:
return len(nums)
elif nums[0] >= target:
return 0
else:
start_index = 0
end_index = len(nums)-1
while start_index + 1 <= end_index:
middle_index = (start_index + end_index +1)//2
if start_index + 1 == end_index:
return end_index
else:
if nums[middle_index] == target:
return middle_index
elif nums[middle_index] < target:
start_index = middle_index
else:
end_index = middle_index
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[-1] < target:
return len(nums)
elif nums[0] >= target:
return 0
else:
start_index = 0
end_index = len(nums)-1
while start_index + 1 <= end_index:
middle_index = (start_index + end_index +1)//2
if start_index + 1 == end_index:
return end_index
else:
if nums[middle_index] == target:
return middle_index
elif nums[middle_index] < target:
start_index = middle_index
else:
end_index = middle_index
217. Contains Duplicate
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
result = False
a_dict = {}
for i in range(len(nums)):
if nums[i] in a_dict:
result = True
break
else:
a_dict[nums[i]] = 1
return result
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
result = False
a_dict = {}
for i in range(len(nums)):
if nums[i] in a_dict:
result = True
break
else:
a_dict[nums[i]] = 1
return result
389. Find the Difference
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
def construct_dict(a_string):
a_dict = {}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
for a_key in dict_2.keys():
try:
dict_1[a_key]
except KeyError:
return a_key
else:
if dict_1 [a_key] != dict_2 [a_key]:
return a_key
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
def construct_dict(a_string):
a_dict = {}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
for a_key in dict_2.keys():
try:
dict_1[a_key]
except KeyError:
return a_key
else:
if dict_1 [a_key] != dict_2 [a_key]:
return a_key
409. Longest Palindrome
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
for i in range (len(s)):
if s[i] in a_dict:
a_dict[s[i]] += 1
else:
a_dict[s[i]] = 1
count = 0
unit = 0
for a_value in a_dict.values():
if a_value % 2 == 0:
count += a_value
else:
count += (a_value//2)*2
unit = 1
return count + unit
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
for i in range (len(s)):
if s[i] in a_dict:
a_dict[s[i]] += 1
else:
a_dict[s[i]] = 1
count = 0
unit = 0
for a_value in a_dict.values():
if a_value % 2 == 0:
count += a_value
else:
count += (a_value//2)*2
unit = 1
return count + unit
Friday, November 3, 2017
557. Reverse Words in a String III
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
new_list = []
new_list = s.split()
new_string=""
for i in range(0,len(new_list)):
new_list[i] = new_list[i][::-1]
new_string = " ".join(new_list)
return new_string
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
new_list = []
new_list = s.split()
new_string=""
for i in range(0,len(new_list)):
new_list[i] = new_list[i][::-1]
new_string = " ".join(new_list)
return new_string
Thursday, November 2, 2017
344. Reverse String
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
9. Palindrome Number
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x == int(str(x)[::-1]):
return True
else:
return False
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x == int(str(x)[::-1]):
return True
else:
return False
Sunday, March 26, 2017
Flatten a list
# Paste your function here
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
flattened_list = []
for item in aList:
if type(item) == type([]):
flattened_list.extend(flatten(item))
else:
flattened_list.append(item)
return flattened_list
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
flattened_list = []
for item in aList:
if type(item) == type([]):
flattened_list.extend(flatten(item))
else:
flattened_list.append(item)
return flattened_list
1. Two Sum
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a_dict = {}
for i in range (0, len(nums)):
x = nums[i]
y = target - nums[i]
if y in a_dict:
return (a_dict[y], i)
else:
a_dict[x] = i
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a_dict = {}
for i in range (0, len(nums)):
x = nums[i]
y = target - nums[i]
if y in a_dict:
return (a_dict[y], i)
else:
a_dict[x] = i
Thursday, March 16, 2017
Guess a word from a list of words
# Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
for i in secretWord:
if i not in lettersGuessed:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
wordguessed=""
for i in secretWord:
if i not in lettersGuessed:
wordguessed += "_ "
else:
wordguessed += i
return wordguessed
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
allletters=string.ascii_lowercase
availableletters=""
for i in allletters:
if i not in lettersGuessed:
availableletters += i
return availableletters
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
n=8
lettersGuessed = []
while n >= 1:
if isWordGuessed(secretWord, lettersGuessed):
print ("Congratulations, you won!")
else:
print ("Welcome to the game, Hangman!")
print ("You have "+ str(n) + " guesses left.")
print ("Available letters: " + getAvailableLetters(lettersGuessed))
guess = input ("Please think of a letter: ")
guessInLowerCase = guess.lower()
lettersGuessed.append (guessInLowerCase)
print ("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
n-=1
print ("Sorry, you ran out of guesses. The word was else.")
# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)
# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
for i in secretWord:
if i not in lettersGuessed:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
wordguessed=""
for i in secretWord:
if i not in lettersGuessed:
wordguessed += "_ "
else:
wordguessed += i
return wordguessed
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
allletters=string.ascii_lowercase
availableletters=""
for i in allletters:
if i not in lettersGuessed:
availableletters += i
return availableletters
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
n=8
lettersGuessed = []
while n >= 1:
if isWordGuessed(secretWord, lettersGuessed):
print ("Congratulations, you won!")
else:
print ("Welcome to the game, Hangman!")
print ("You have "+ str(n) + " guesses left.")
print ("Available letters: " + getAvailableLetters(lettersGuessed))
guess = input ("Please think of a letter: ")
guessInLowerCase = guess.lower()
lettersGuessed.append (guessInLowerCase)
print ("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
n-=1
print ("Sorry, you ran out of guesses. The word was else.")
# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)
# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
Wednesday, March 15, 2017
Dictionary in Python
Find the value with the maximum length in a dictionary:
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
# Your Code Here
result = None
maximum = 0
for key in aDict.keys():
if len(aDict[key]) >= maximum:
result=key
maximum = len(aDict[key])
return result
Returns the sum of the number of values associated with a dictionary
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
# Your Code Here
result=0
for key in aDict.keys():
result+=len(aDict[key])
return result
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
# Your Code Here
result = None
maximum = 0
for key in aDict.keys():
if len(aDict[key]) >= maximum:
result=key
maximum = len(aDict[key])
return result
Returns the sum of the number of values associated with a dictionary
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
# Your Code Here
result=0
for key in aDict.keys():
result+=len(aDict[key])
return result
Sunday, March 12, 2017
Binary search to find a character in a str
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
if aStr == '':
return False
if len (aStr) == 1:
return char == aStr
midindex = len(aStr)//2
midchar = aStr [midindex]
if char == midchar:
return True
elif char < midchar:
return isIn (char, aStr[:midindex])
else:
return isIn (char, aStr[midindex+1:])
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
if aStr == '':
return False
if len (aStr) == 1:
return char == aStr
midindex = len(aStr)//2
midchar = aStr [midindex]
if char == midchar:
return True
elif char < midchar:
return isIn (char, aStr[:midindex])
else:
return isIn (char, aStr[midindex+1:])
Saturday, March 11, 2017
guess my number
newnumber=int(input ("Please think of a number between 0 and 100!"))
begin=0
end=100
answer=str()
while answer!='c':
guessnumber=int((begin+end)/2)
print ("Is your secret number ", guessnumber)
answer=str(input ("Enter 'h' to indicate the guess is too high. Enter 'l' \
to indicate the guess is too low. \
Enter 'c' to indicate I guessed correctly."))
if answer=='h':
end=guessnumber
elif answer=='l':
begin=guessnumber
elif answer=='c':
print ("Game over. Your secret number was:", guessnumber)
else:
print ("Sorry, I did not understand your input.")
***************************************************************************
begin=0
end=100
answer=str()
while answer!='c':
guessnumber=int((begin+end)/2)
print ("Is your secret number ", guessnumber)
answer=str(input ("Enter 'h' to indicate the guess is too high. Enter 'l' \
to indicate the guess is too low. \
Enter 'c' to indicate I guessed correctly."))
if answer=='h':
end=guessnumber
elif answer=='l':
begin=guessnumber
elif answer=='c':
print ("Game over. Your secret number was:", guessnumber)
else:
print ("Sorry, I did not understand your input.")
***************************************************************************
print("Please think of a number between 0 and 100!")
# At the start the highest the number could be is 100 and the lowest is 0.
hi = 100
lo = 0
guessed = False
# Loop until we guess it correctly
while not guessed:
# Bisection search: guess the midpoint between our current high and low guesses
guess = (hi + lo)//2
print("Is your secret number " + str(guess)+ "?")
user_inp = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if user_inp == 'c':
# We got it right!
guessed = True
elif user_inp == 'h':
# Guess was too high. So make the current guess the highest possible guess.
hi = guess
elif user_inp == 'l':
# Guess was too low. So make the current guess the lowest possible guess.
lo = guess
else:
print("Sorry, I did not understand your input.")
print('Game over. Your secret number was: ' + str(guess))
Wednesday, March 8, 2017
Write a program that prints the longest substring of s
Assume
s is a string of lower case characters.Write a program that prints the longest substring of
s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should printLongest substring in alphabetical order is: begghIn the case of ties, print the first substring. For example, if
s = 'abcbcd', then your program should printLongest substring in alphabetical order is: abcNote: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.
s=str(input('Please enter your string: ')).lower()
letter=str()
i=0
length=len(s)
print (length)
for i in range (len(s)-1):
if s[i] < s[i+1] :
letter+=s[i]
print (letter)
elif s[i] >= s[i+1] :
break
print (letter)
Find a sub string
s=str(input('Please enter your string: ')).lower()
numberofbob=0
i=0
length=len(s)
print (length)
for i in range (len(s)):
print (s[i:i+3])
if s[i:i+3] == 'bob' :
numberofbob+=1
print (numberofbob)
numberofbob=0
i=0
length=len(s)
print (length)
for i in range (len(s)):
print (s[i:i+3])
if s[i:i+3] == 'bob' :
numberofbob+=1
print (numberofbob)
Subscribe to:
Comments (Atom)