text
stringlengths
37
1.41M
# Sublime Limes' Line Graphs # Data Visualization with Matplotlib import codecademylib from matplotlib import pyplot as plt months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] visits_per_month = [9695, 7909, 10831, 12942, 12495, 16794, 14161, 12762, 12777, 12439, 1...
# PYTHON SYNTAX: MEDICAL INSURANCE PROJECT # 1) Initial variables: age = 28 sex = 0 bmi = 26.2 num_of_children = 3 smoker = 0 # 2) Insurance cost formula: insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500 # 3) Print the string: print("This pers...
names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"] insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0] # Add your code here #Append a new individual, "Priscilla", to names, and her insurance cost, 8320.0, to insura...
# PYTHON FUNDAMENTALS # Python Classes: Medical Insurance Project # 1. Add more paremeters: class Patient: def __init__(self, name, age, sex, bmi, num_of_children, smoker): self.name = name self.age = age self.sex = sex self.bmi = bmi self.num_of_children = num_of_...
import time import pandas as pd from termcolor import colored from tabulate import tabulate CITY_DATA = {'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv'} MONTHS = ['All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] DAYS = ['Mon', 'Tue', 'Wed', 'Thu...
from data1 import * # Imports everything data1.py without having to reference it every time you call from it from matplotlib import pyplot as plt # Library for charting import os as os dir = os.path.join(os.getcwd(), 'static') # Gets the relative file path to the /static/ directory, where all of these functions will p...
def detectCycle(head): if head == None: return None if head.next == None: return None visited = {} visited[head] = True first = head.next while first: if first in visited: return first visited[first] = True first = first.next return None
""" Given an integer n, return the largest number that contains exactly n digits. Example For n = 2, the output should be largestNumber(n) = 99. Input/Output [execution time limit] 4 seconds (py3) [input] integer n Guaranteed constraints: 1 ≤ n ≤ 9. [output] integer The largest integer of length n. """ def l...
def valid_brackets_string(s): stacked = [] open_brackets = ["[", "(", "{"] for i in s: if i in open_brackets: stacked.append(i) else: if len(stacked) <= 0: return False open_bracket = stacked.pop() if open_bracket == "[" and i != "]": return False elif open_br...
#Access head_node => list.get_head() #Check if list is empty => list.is_empty() #Delete at head => list.delete_at_head() #Search for element => list.search() #Node class { int data ; Node next_element;} def delete(lst, value): if lst.is_empty(): return False node = lst.get_head() previous_node = None whi...
# Python 3 implementation to # reverse bits of a number # function to reverse # bits of a number def reverseBits(n): rev = 0 # traversing bits of 'n' from the right while (n > 0): # bitwise left shift 'rev' by 1 rev = rev << 1 # if current bit is '1' if (n & 1 == 1): ...
def quick_sort(arr, low, high): if low < high: p = partition(arr, low, high) quick_sort(arr, low, p - 1) quick_sort(arr, p + 1, high) def partition(arr, low, high): i = (low - 1) pivot = arr[high] for j in range(low, high): if arr[j] < pivot: i += 1 ...
print(""" Checking Whether Any Intersection in a City is Reachable from Any Other Count the number of connected components in a Directed Graph ++++++++Directed Graph Strongly Connected Components++++++ \n Compute the number of strongly connected components of a given directed graph with 𝑛 vertices and 𝑚 edges. ...
# Given a set of positive numbers, find the total # number of subsets whose sum is equal to a given number ‘S’. def count_subsets(num, sum): n = len(num) dp = [0 for x in range(sum+1)] dp[0] = 1 # with only one number, we can form a subset only when the required sum is equal to the number for s in range...
def count_islands(grid): height = len(grid) width = len(grid[0]) num_of_islands = 0 for row in range(height): for column in range(width): if grid[row][column] == '1': num_of_islands += 1 dfs(grid, row, column) return num_of_islands def dfs(grid,...
def steps(n): if n == 0: return 1 if n < 3: return n n1, n2, n3 = 1, 1, 2 for i in range(3, n + 1): n1, n2, n3 = n2, n3, n1 + n2 + n3 return n3 print(steps(3)) print(steps(4)) # Visualization: https://media.geeksforgeeks.org/wp-content/uploads/2-3.jpg
class Solution: def toLowerCase(self, str: str) -> str: answer = "" for letter in str: answer += chr(ord(letter) ^ ord(" ")) return answer
# python3 def max_pairwise_product(n, numbers): if n != len(numbers): return max_index = -1 max_index2 = -1 for i in range(n): if max_index == -1 or (numbers[i] > numbers[max_index]): max_index = i for j in range(n): if j != max_index and (max_index2 == -1 or n...
from sys import argv # read the WYSS section for how to run this script, first, second, third = argv # Declaring our variables v1 = 0 v2 = 0 v3 = 0 v4 = 0 print("The script is called:", script) print("Your first variable is:", first) print("Your second variable is:", second) print("Your third varianle is:", third) ...
class AnimalEstimacao(): def __init__(self, nome, especie, dono): self.nome = nome self.especie = especie self.dono = dono def __str__(self): return self.nome import aula2 as animal isabellita = animal.AnimalEstimacao('Isabellita', 'Capivara','Teste') class Calculadora(): ...
""" Recursion is important to understand Tree and Graph. Practice again and again. Every single day, solve a recurtion problem from leet code. It is important to explain solutions by own words for interviews, not code base. https://leetcode.com/problemset/algorithms/?search=Recursion """ def factorial(n: int) -> i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 1 16:16:28 2019 @author: xie """ import math #import time #start=time.perf_counter() def make(n): #计算因子数的函数 ans = 0 if n == 1: return 1 elif n == 2: return 2 elif n == 3: return 2 else: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 21 22:39:11 2019 @author: xie """ password = input() answord = input() word = input() dic = {} ans = '' flag = 0 for i in range(len(password)): if password[i] not in dic and '\\' not in password[i]: dic[password[i]] = answord[i] els...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 1 01:21:59 2019 @author: xie """ n = int(input()) if n < 3: print('impossible!') elif n % 3 == 0: print('YES') print(1, 1, n-2) elif n % 3 == 1: print('YES') print(1, 2, n-3) elif n % 3 == 2: print('YES') print(2, 2, n-...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 22 14:01:43 2019 @author: xie """ n = int(input()) password = input().lower() ans = '' for i in password: ans += chr((ord(i)-ord('a') + n) % 26 + ord('a')) print(ans)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 21 19:17:01 2019 @author: xie """ ans = 0 for i in range(3): ans += int(input()) print(ans)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 16 13:46:52 2019 @author: xie """ i = 1 x = 0 k = int(input()) while x <= k: x += 1/i i += 1 else: print(i-1)
out_file = open('name.txt', 'w') name = str(input("Enter your name \n")) print("My name is", name, file=out_file) out_file.close() file = open("name.txt", "r") file.read print(file.read()) file = open("numbers.txt", "r") number1 = int(file.readline()) number2 = int(file.readline()) print(number1 + number2) file.clos...
""" << --- Örnek 1 --->> # Kullanıcıdan Adını String Alıp Ekrana Yazdıran Program isim = input("Adınız: ") print("Merhabalar" , isim) # Output Adınız: Mustafa Merhabalar Mustafa # """ """ << --- Örnek 2 --->> # Kullanıcıdan Alınan iki sayının Toplamını Bulan Program sayi_1 = input("Birinci Sayiyi Giriniz: ") sa...
import sys import socket # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port 31000, 31001, 31002 server_address = ('localhost', 31002) print(f"starting up on {server_address}") sock.bind(server_address) # Listen for incoming connections sock.listen(1) # maks m...
def calcIndex(words, letters, sentences): return (0.0588 * ((letters / words) * 100) - (0.296 * (sentences / words) * 100)) - 15.8 text = input("Text: ") words = 1 letters = 0 sentences = 0 for char in text: if char.isalpha(): letters += 1 elif char.isspace(): words += 1 elif char in ...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv','new york city': 'new_york_city.csv','washington': 'washington.csv' } MONTH_DATA = ['january','february','march','april','may','june'] DAYS_DATA = {'sunday':'1','monday':'2','tuesday':'3','wednesday':'4','thursday':'5','friday'...
def f(): a='' for d in range(12):a+="On the %s day of Christmas\nMy true love sent to me\n%s\n"%("First|Second|Third|Fourth|Fifth|Sixth|Seventh|Eighth|Ninth|Tenth|Eleventh|Twelfth".split("|")[d],"\n".join("Twelve drummers drumm^,|Eleven pipers pip^,|Ten lords a-leap^,|Nine ladies danc^,|Eight maids a-milk^,|Seven swa...
def divider(): while True: nums=input('enter 2 digits(format: x y ):') (x,y)=nums.split() try: x = float(x) y = float(y) print(x/y) except ZeroDivisionError: print('Try again without zero') except ValueError: print('...
# encoding=utf-8 ''' Find the row with maximum number of 1s Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Example Input matrix 0 1 1 1 0 0 1 1 1 1 1 1 // this row has maximum 1s 0 0 0 0 Output: 2 A simple method is to do a row wise traversal of the matrix, count ...
# encoding=utf-8 ''' Print nodes at k distance from root Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root. For example, in the below tree, 4, 5 & 8 are at distance 2 from root. 1 / \ 2 3 / \ / 4 5 8 ''' # print a...
# encoding=utf-8 ''' Lexicographic rank of a string Given a string, find its rank among all its permutations sorted lexicographically. For example, rank of “abc” is 1, rank of “acb” is 2, and rank of “cba” is 6. For simplicity, let us assume that the string does not contain any duplicated characters. One simple sol...
# encoding=utf-8 ''' List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). ''' Celsius = [39.2, 36.5, 37.3, 37.8] Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ] print Fahrenheit #注意这个。 最左边的就是可以代替lambdaL了。 最右边的if就是可以代替filter. 而且filter只...
# encoding=utf-8 ''' 有向图 Graph is Tree or not We know that every Tree is a graph but reverse is not always true. In this problem, we are given a graph and we have to find out that whether it is a tree topology or not? There can be many approaches to solve this problem, out of which we are proposing one here. If nu...
# encoding=utf-8 ''' Find a triplet from three linked lists with sum equal to a given number 先全部sort好 就是简单地3sum. reverse一下chead ''' #没有见过的题目。 不过和leetcode联系紧密 class Solution: def findTrip(self, h1, h2, h3, target): h3 = self.reverse(h3) #c要逆序排序 a = h1 while a: b = h2; c = h3...
# encoding=utf-8 #g4g原题 # Smallest subarray with sum greater than a given value # sliding window, 也就是变种的cumulative sum #Google 考过 ''' Determine minimum sequence of adjacent values in the input parameter array that is greater than input parameter sum. sequence of adjacent values实际上就是sub array sum 如果是具体求。 是用cumulativ...
# encoding=utf-8 ''' ind the longest words in a given list of words that can be constructed from a given list of letters. Your solution should take as its first argument the name of a plain text file that contains one word per line. The remaining arguments define the list of legal letters. A letter may not appear in an...
# encoding=utf-8 ''' Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset. For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of t...
# encoding=utf-8 ''' Given a string (1-d array) , find if there is any sub-sequence that repeats itself. Here, sub-sequence can be a non-contiguous pattern, with the same relative order. Eg: 1. abab <------yes, ab is repeated 2. abba <---- No, a and b follow different order 3. acbdaghfb <-------- yes there is a follo...
# encoding=utf-8 ''' 给一个String 可以包含数字或者字母 找出里面的是否存在一个substring全是数字而且这个substring表示的数字可以被36整除,并且不能是0 e.g.: 360ab: True 0ab: False ''' # 我是利用那个题做的 pattern match 比如输入pattern: 2p2 和一个string:apple 输出 true class Solution: def solve(self, s1): i=0 while i<len(s1): if '0'<=s...
# encoding=utf-8 ''' Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array. Number of removals should be minimum. Examples: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements ...
# encoding=utf-8 ''' Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). 半加器: 00. 01 10 11 &是进位 ^是求和 ''' class Solution: #比较简短。 背下。 def addBi(self, x, y): while y: print x, y share = x&y #求进...
# encoding=utf-8 ''' write the most efficient (in terms of time complexity) function getNumberOfPrimes which takes in an integer N as its parameter. to return the number of prime numbers that are less than N Sample Testcases: Input #00: 100 Output #00: 25 Input #01: 1000000 Output #01: 78498 ''' class Solution: ...
# encoding=utf-8 ''' we have a random list of people. each person knows his own height and the number of tall people in front of him. write a code to make the equivalent queue. for example : input: <"Height","NumberOfTall","Name">, <6,2,"A">,<1,4,"B">,<11,0,"C">,<5,1,"D">,<10,0,"E">,<4,0,"F"> output: "F","E","D","C","B...
# encoding=utf-8 ''' Give efficient implementation of the following problem. An item consist of different keys say k1, k2, k3. User can insert any number of items in database, search for item using any key, delete it using any key and iterate through all the items in sorted order using any key. Give the most efficient...
# encoding=utf-8 ''' Given two strings str1 and str2, find if str1 is a subsequence of str2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements (source: wiki). Expected time complexity is linear. Examples: Input: str1 = ...
# encoding=utf-8 ''' 题目是给一个string,返回含有word的list。word的定义是空格(大于 等于一个)之间的或者引号之间的,如果引号里面有空格要做为一个word返回。比如string是 I have a "faux coat" 要返回[I, have, a, faux coat]。 根据空格分隔字符串,但是引号内的是整体,不可分割 如果这个字符串是一个连续分布在很多机器上的大文件,每个机器知道其前后机器是谁并且可以相互通信,那么如何继续分隔(引号可以分在两个机器上 ''' #引号的写法 \", \' #一个做法是可以先将split分割。 奇数位的就保留。 对于偶数位的。...
# encoding=utf-8 ''' Given a BST and a value x. Find two nodes in the tree whose sum is equal x. Additional space: O(height of the tree). It is not allowed to modify the tree ''' # 解法在这个文件Find a pair with given sum in a Balanced BST ''' 如果能够化为dll就容易。 ''' ''' G家 Given a BST and a number x, find two nodes in the BST wh...
# encoding=utf-8 ''' Program an iterator for a Linked List which may include nodes which are nested within other nodes. i.e. (1)->(2)->(3(4))->((5)(6). Iterator returns 1->2->3->4->5->6 '''
# encoding=utf-8 ''' Let's say there is a double square number X, which can be expressed as the sum of two perfect squares, for example, 10 is double square because 10 = 3^2 + 1^2 Determine the number of ways which it can be written as the sum of two squares 就是2-pointer版本的 two-sum O(sqrt(n)) ''' #注意这里并没有overlappi...
# encoding=utf-8 ''' # 三连棋游戏(两人轮流在一有九格方盘上划加字或圆圈, 谁先把三个同一记号排成横线、直线、斜线, 即是胜者),可以在线玩 N*N matrix is given with input red or black. You can move horizontally, vertically or diagonally. If 3 consecutive same color found, that color will get 1 point. So if 4 red are vertically then point is 2. Find the winner. Tic-tac-toe ...
# encoding=utf-8 ''' Count all possible walks(paths) from a source to a destination with exactly k edges Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’ to ‘v’ with exactly k edges on the walk. The graph is given as adjacency matrix representation where value of graph[i]...
# encoding=utf-8 ''' Output top N positive integer in string comparison order. For example, let's say N=1000, then you need to output in string comparison order as below: 1, 10, 100, 1000, 101, 102, ... 109, 11, 110, ... ''' class Solution: def dfs(self,s): if int(s)>self.n: return self.ret.append(s...
# encoding=utf-8 def f1(): return 1 def f2(): return 2 myfuctions = {'a':f1, 'b':f2} print myfuctions['a']() print myfuctions['b']() ''' 每个函数都是变量 closures and currying ''' def outer(outArg): def inner(innerArg): return outArg+innerArg return outArg func = outer(10) def make_adder(addend): ...
# encoding=utf-8 ''' Escape strings. Convert special ASCII characters to form of ‘\ooo’, where ‘ooo’ is oct digit of the corresponding special character. The ascii characters that smaller than space are regarded as special characters. ''' ''' 转化成任意的x进制: 不断while n n, d = n/x, d%x ''' class Solution: def convert(s...
# encoding=utf-8 ''' Tail Recursion What is tail recursion? A recursive function is tail recursive when recursive call is the last thing executed by the function. For example the following C++ function print() is tail recursive. // An example of tail recursive function void print(int n) { if (n < 0) return; ...
# encoding=utf-8 ''' What is the Minimum Amount not possible using an infinite supply of coins (Unbounded knapsack) You are given coins of Denominations {v1, v2 , v3, v4 ....vn } of weight {w1, w2, w3 .....wn} Now that you have a bag of capacity W . Find the smallest Value V that is not possible to have in the bag. (...
# encoding=utf-8 ''' Maximum sum such that no two elements are adjacent Question: Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return ...
# encoding=utf-8 a = [1, 3, 2] b = a[1:3] print a, b print id(a[-1]) print id(b[-1]) b[1]=1 print id(a[-1]) print id(b[-1]) # 可以看出。 用了slice,是一种shallow copy. a, b是独立的。 但是如果你不改变b的话, 也没有消费新的空间。 # 也就是说。 # a[1:3] == b[:]. 并没有开辟新的空间。 #因为python 很 smart. #所以可以放心使用。
# encoding=utf-8 ''' Find the number of zeroes Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array. Examples: Input: arr[] = {1, 1, 1, 1, 0, 0} Output: 2 Input: arr[] = {1, 0, 0, 0, 0} Output: 4 Input: arr[] = {0, 0, 0} Output...
# encoding=utf-8 ''' Maximum size square sub-matrix with all 1s Maximum size square sub-matrix with all 1s Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. 0 1 1 0 1 1 1 0 1 0 0 1 1 1 0 1 1 1 1 0 1 1 1 ...
# encoding=utf-8 #n boxes, k balls, expected number of empty boxes. ''' 比如If you have 10 balls and 5 boxes what is the expected number of boxes with no balls. #期望 : 取值xi与对应的概率Pi(=xi)之积的和称为该离散型随机变量的数学期望 x[i] 代表第几个盒子为空。的概率。 x = sum(x[i] for i in range(5) ) x[i] = 4**10/5**10 # 有一个box没有ball的概率 x = 5* (4...
# encoding=utf-8 ''' Search in an almost sorted array Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can onl...
# encoding=utf-8 ''' String compressor that turns "123abkkkkkc" to "123ab5xkc". Decompressor is already written and must remain unchanged. take into account of strings like: "123xk", "123xx" ...etc as input ''' # 普通的话。 就是如果cnt==1。 就不加上cnt了。 #按照微软的思路。 x=> -ord(x) . 用正负标记比如5个k。 变成-5 class Solution: # @return a s...
# encoding=utf-8 ''' Program to find amount of water in a given glass There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: 1 2 3 4 5 6 7 8 9 10 You can put water to only top glass. If you put more than 1 litre water to 1st glass, w...
# encoding=utf-8 ''' Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: ''' #G家考过 O(1) s...
# encoding=utf-8 #简单做法是用hash ''' Check if array elements are consecutive | Added Method 3 Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers. Examples: a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive n...
# encoding=utf-8 ''' 有两个一样的树A和B,每个节点都有父指针,要求写一个 函数,参数是A的一个子节点x,和B的根节点,要求返回B中对应x的那个节点。也就是 说A的根节点未知。这题挺简单,所以我没怎么想就说了先找到A的根节点,然后同时对 A和B做一个DFS或者BFS来找出B中对应x的节点。面试官说可以,让我写代码,写完以后 分析了一下复杂度。然后就问有没有更好的方法,我马上就意识到不需要用DFS或者BFS ,只需要在找A的根节点时记录下当前路径就行了(只需记录每个子结点是父节点的第 几个孩子),然后按同样的路径扫一下B树。复杂度只有O(height), ''' class Solution: def f...
# encoding=utf-8 ''' Count number of bits to be flipped to convert A to B ''' class Solution: def cntBits(self, n): cnt = 0 while n: cnt+=n&1 n>>=1 return cnt def countFlip(self, a, b): return self.cntBits(a^b) ''' # Turn off the rightmost se...
# encoding=utf-8 ''' There are a large number of leaves eaten by caterpillars. There are 'K"' caterpillars which jump onto the leaves in a pre-determined sequence. All caterpillars start at position 0 and jump onto the leaves at positions 1,2,3...,N. Note that there is no leaf at position 0. Each caterpillar has an ass...
#DFS is more common. BFS can find the shortest path #BFS uses while loop. DFS uses recursion __author__ = 'zhenglinyu' def BFS(s, adj): level = {} level[s] = 0 parent = {} parent[s] = None i = 1 frontier = [s] while frontier: next = [] for u in frontier: for v in...
# encoding=utf-8 ''' given a board with black (1) and white (0), black are all connected. find the max rectangle that contains all black. example: 0 0 0 0 0 0 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 the max rectangle contains all black (1) is the rectangle from (1,1) - (3, 3) ''' #leetcode maximal rectangle 用histogra...
# encoding=utf-8 ''' Given a circle with N defined points and a point M outside the circle, find the point that is closest to M among the set of N. O(LogN) ''' #我们就先假定是sorted的吧。 # ''' Assuming that the points on the circumference of the circle are "in-order" (i.e. sorted by angle about the circle's center) you could ...
# encoding=utf-8 import math ''' 0x for hexadecimal, 0 for octal and 0b for binary Find n’th number in a number system with only 3 and 4 Given a number system with only 3 and 4. Find the nth number in the number system. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 44...
# encoding=utf-8 # 如何判断一棵二叉树实际上是一个链表 #但面试完发现只要保证每个节点都只有一个子嗣即可,否则返回非 不需要遍历所有元素 class Solution: def solve(self, root): while root: if root.left and root.right: return False elif root.left: root=root.left elif root.right: root=root.right else: break retu...
# encoding=utf-8 ''' Given the relative positions (S, W, N, E, SW, NW, SE, NE) of some pairs of points on a 2D plane, determine whether it is possible. No two points have the same coordinates. e.g., if the input is "p1 SE p2, p2 SE p3, p3 SE p1", output "impossible". ''' # build 2 graphs。 x, cooridinates. y coor...
# encoding=utf-8 ''' 意思是swap子树。 Swap 2 nodes in a Binary tree.(May or Maynot be a BST) Swap the nodes NOT just their values. (preferably in Java please..(My requirement not theirs :p)) ex: 5 / \ 3 7 / \ / 2 4 6 swap 7 and 3 5 / \ 7 3 / / \ 6 2 4 ''' #注意跟面试官clear 一个是另一个parent的情况 #level order traversal class Solution:...
# encoding=utf-8 ''' Following is a simple algorithm to find out whether a given graph is Birpartite or not using Breadth First Search (BFS). 1. Assign RED color to the source vertex (putting into set U). 2. Color all the neighbors with BLUE color (putting into set V). 3. Color all neighbor’s neighbor with RED color (p...
# encoding=utf-8 ''' What is the difference between a computers heap and it's stack? ''' #看看下面这个stack overflow就理解了. ''' You can cause a stack overflow quite easily in python, as in any other language, by building an infinately recursive funcion. This is easier in python as it doesn't actually have to do anything at a...
# encoding=utf-8 ''' Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point. Write a function: int number_of_disc_intersections(...
# encoding=utf-8 ''' flatten array ''' class Solution: def flatten(self, arr): ret = [] for i in arr: if isinstance(i, list): ret+=self.flatten(i) else: ret.append(i) return ret s = Solution() print s.flatten( [ [1,2], [3,[4,5]], 6])
# encoding=utf-8 ''' Given a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual. For example, consider the s...
# encoding=utf-8 ''' check whether a given binary tree is complete or not Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far ...
# encoding=utf-8 ''' there are N nuts and N bolts, all unique pairs of Nuts and Bolts. You cant compare Nut with Nut and a Bolt with Bolt. Now ,how would you figure out matching pairs of nut and bolt from the given N Nuts and Bolts. ''' ''' 方法就是类似快排,随便找一个螺母a,用它把所有螺栓分成小于a、大于a和等于a(只有一个)。再用那个等于a的螺栓把所有螺母也划分一遍。于是就得到了一对匹配和...
# encoding=utf-8 ''' Find the seed of a number. Eg : 1716 = 143*1*4*3 =1716 so 143 is the seed of 1716. find all possible seed for a given number. ''' #暴力法 class Solution: def findseed(self, x): results = [] for n in range(x): a = [int(i) for i in list(str(n))] product = n ...
# encoding=utf-8 ''' A soda water machine,press button A can generate 300-310ml, button B can generate 400-420ml and button C can generate 500-515ml, then given a number range [min, max], tell if all the numbers of water in the range can be generated. ''' #很特别的dp class Solution: def generate(self, minV, maxV): ...
# encoding=utf-8 ''' Given a very very very large integer(with 1 million digits, say), how would you convert this integer to an ASCII string ''' # linked list ''' It's like : input - 12345678........8798989887873124234....(1 million digits) output - "12345678............8798989887873124234...." basically an itoa() ...
# encoding=utf-8 ''' Colorful Number: A number can be broken into different sub-sequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a colorful number, since product of every digit of a sub-sequence are different. That is, 3 2 4 5 (3*2)=6 (2*4)=8 (4*5)=20 (3...
# encoding=utf-8 ''' Print Nodes in Top View of Binary Tree Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n) A node x is there in output if x is the...
# encoding=utf-8 ''' Write a method to determine if two strings are anagrams of each other. e.g. isAnagram(“secure”, “rescue”) → false e.g. isAnagram(“conifers”, “fir cones”) → true e.g. isAnagram(“google”, “facebook”) → false ''' # O(n) # 也可以keep an asicii array of 256. 不过一般都可以用hashtable替代。 尽量用hashtable class Solution...
# encoding=utf-8 ''' Merge k sorted arrays | Set 1 Given k sorted arrays of size n each, merge them and print the sorted output. Example: Input: k = 3, n = 4 arr[][] = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}} ; Output: 0 1 2 3 4 5 6 7 8 9 10 11 A simple solution is to create an output...
# encoding=utf-8 ''' Microsoft Excel numbers cells as 1...26 and after that AA, AB.... AAA, AAB...ZZZ and so on. Given a number, convert it to that format and vice versa. A-Z: 26 AA- ZZ: 后面的26*26 AAA-ZZZ: 后面的26*26*26 ''' #就是十进制与26进制转换。 变成了26进制计数。 class Solution: def toStr(self, n): out = '' ...
# encoding=utf-8 ''' There are 10,000 balls and may be 500 different colors of ball Example: There are: 4 - red ball 5900 - Blue ball 3700 - Green ball 396 - mintcream ball Or there may be 10,000 red balls. Or all balls are has same range, i.e. 500 red, 500 blue, etc. We don’t know the range of any ball and number ...
# encoding=utf-8 ''' 给个Binary Search Tree. 中间有很多重复的数字(你没看错,就是有重复的)。要求找到出现次数最多的那个数字。现场coding的话关键注意点在如何inorder遍历的同时刷新max。此外如果max是最后的一组数是个边界条件。 ''' class Solution4: def findSucPre(self, root): self.pre = None; self.cnt=0 self.ret = (0, None) self.dfs(root) return self.ret def dfs...
# encoding=utf-8 ''' Asked by SG Given an array in which all numbers except two are repeated once. (i.e. we have 2n+2 numbers and n numbers are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way. 第一想法用hash。 用 extra space. but efficient XOR of two different numbers...