📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
楼主: ZYYYZ
跳转到指定楼层
上一主题 下一主题
收起左侧

Data Scientist Python Coding 题整理(持续更新

   
🔗
 楼主| ZYYYZ 2021-2-9 12:02:47 | 只看该作者
全局:
24. Sum problems

(1). Two Sum (leetcode 1)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example:
Input: nums = [3,2,4], target = 6. 1point 3acres
Output: [1,2]
.
T: O(n)
S: O(n)

  1. class Solution:
  2.     def twoSum(self, nums, target):
  3.         if not nums or len(nums) < 2:. Χ
  4.             return [-1, -1]

  5.         result = [-1, -1]. 1point 3 acres
  6.         dic = {}

  7.         for i in range(len(nums)):
  8.             if target - nums[i] in dic:
  9.                 result[0] = dic[target - nums[i]]
  10.                 result[1] = i
  11.                 break
  12.                
  13.             dic[nums[i]] = i
  14.             
  15.         return result
  16.    
  17.    
  18. if __name__ == '__main__':
  19.     assert Solution().twoSum([3, 2, 4], 6) == [1, 2]
  20.     assert Solution().twoSum([3, 3], 6) == [0, 1]
复制代码



(2). 3Sum (leetcode 15)

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
.1point3acres
Notice that the solution set must not contain duplicate triplets.
.1point3acres
Example:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]. check 1point3acres for more.

T: O(n^2)
S: O(n).google  и

  1. class Solution:
  2.     def threeSum(self, nums):.google  и
  3.         result = []
  4.         nums.sort()
  5.         
  6.         for i in range(len(nums) - 2):
  7.             if i > 0 and nums[i] == nums[i - 1]:
  8.                 continue

  9.             low, high = i + 1, len(nums) - 1
  10.             total = 0 - nums[i]

  11.             while low < high:
  12.                 if nums[low] + nums[high] == total:
  13.                     result.append([nums[i], nums[low], nums[high]])

  14.                     while low < high and nums[low] == nums[low + 1]:
  15.                         low += 1
  16.                     while low < high and nums[high] == nums[high - 1]:
  17.                         high -= 1

  18.                     low += 1
  19.                     high -= 1

  20.                 elif nums[low] + nums[high] < total:
  21.                     low += 1

  22.                 else:
  23.                     high -= 1. 1point3acres.com
  24.                     
  25.         return result. 1point 3 acres
  26.     . From 1point 3acres bbs
  27.     . From 1point 3acres bbs
  28. if __name__ == '__main__':. Χ
  29.     assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2],[-1, 0, 1]]. 1point 3 acres
  30.     assert Solution().threeSum([0]) == []
复制代码
. From 1point 3acres bbs


回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-9 13:31:26 | 只看该作者
全局:
25. Sqrt(x) (leetcode 69)

Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.. 1point 3acres
.--
Example:
Input: x = 4
Output: 2

Input: x = 8.1point3acres
Output: 2

Method 1: Binary Search
T: O(logn), S:O(1).google  и
. 1point3acres.com
  1. class Solution:
  2.     def mySqrt_bin_search(self, x):
  3.         if x <= 0:
  4.             return 0
  5.         .
  6.         low, high = 1, x
  7.         while low <= high:
  8.             mid = low + (high - low)//2
  9.             if mid*mid == x:
  10.                 return mid
  11.             elif mid*mid < x:
  12.                 low = mid + 1. check 1point3acres for more.
  13.             else:
  14.                 high = mid - 1
  15.                
  16.         if high*high < x:
  17.             return high
  18.         else:. 1point 3acres
  19.             return low. 1point3acres.com
  20.         -baidu 1point3acres

  21. if __name__ == '__main__':. 1point3acres
  22.     assert Solution().mySqrt_bin_search(4) == 2.google  и
  23.     assert Solution().mySqrt_bin_search(8) == 2
复制代码
-baidu 1point3acres


Method 2: Newton's method
参考:https://en.wikipedia.org/wiki/Newton%27s_method




T: O(logn), S: O(1)

. From 1point 3acres bbs
  1. class Solution:
  2.     def mySqrt_newton(self, x):
  3.         if x <= 0:
  4.             return 0
  5. . From 1point 3acres bbs
  6.         t = x
  7.         while t*t > x:
  8.             t = (t + x//t)//2
  9.             . .и
  10.         return t.google  и
  11. . 1point3acres.com

  12. if __name__ == '__main__':
  13.     assert Solution().mySqrt_newton(4) == 2
  14.     assert Solution().mySqrt_newton(8) == 2
复制代码



回复

使用道具 举报

🔗
letttti 2021-2-9 16:02:24 | 只看该作者
全局:
mark 楼主给力!
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-11 11:40:48 | 只看该作者
全局:
26. Fibonacci 相关. check 1point3acres for more.

(1). 经典的Fibonacci Number (Leedcode 509)

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1.google  и
F(n) = F(n - 1) + F(n - 2), for n > 1.. .и

Given n, calculate F(n).
.
Example:
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

T: O(n), S: O(1)

  1. class Solution:
  2.     def fib(self, n):
  3.         if n in (0, 1):
  4.             return n
  5.         
  6.         zero, one = 0, 1
  7.         
  8.         for i in range(2, n + 1):.
  9.             two = zero + one
  10.             zero = one
  11.             one = two
  12.             
  13.         return two
  14.    
  15. if __name__ == '__main__':
  16.     assert Solution().fib(3) == 2
  17.     assert Solution().fib(4) == 3
复制代码
. 1point3acres



(2). 相关题目Climbing Stairs (Leetcode 70)

You are climbing a staircase. It takes n steps to reach the top..1point3acres
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

T: O(n), S: O(1)
.1point3acres
  1. class Solution:.--
  2.     def climbStairs(self, n):
  3.         if n <= 2:
  4.             return n
  5.         . ----
  6.         dp_1 = 1. 1point3acres
  7.         dp_2 = 2
  8.         
  9.         for i in range(2, n):
  10.             dp_3 = dp_1 + dp_2
  11.             dp_1 = dp_2
  12.             dp_2 = dp_3
  13.             
  14.         return dp_3
  15.    

  16. if __name__ == '__main__':
  17.     assert Solution().climbStairs(2) == 2
  18.     assert Solution().climbStairs(3) == 3
复制代码


回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-11 12:12:50 | 只看该作者
全局:
爱长跑的蜗牛 发表于 2021-2-3 14:26. .и
谢谢分享,第12行是不是应该是   result += s[-1] + str(cnt)  ?

都可以,结果一样的没区别。
回复

使用道具 举报

🔗
cherry-nancy 2021-2-12 06:02:07 | 只看该作者
全局:
楼主这面试的都是哪些公司啊,感觉题目很难
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-12 08:58:28 | 只看该作者
全局:
cherry-nancy 发表于 2021-2-12 06:02
楼主这面试的都是哪些公司啊,感觉题目很难

有些是我遇到的真题,有些是论坛上的面经题,有些是我在其他地方看到的面经题。
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-12 18:25:11 | 只看该作者
全局:
本帖最后由 YZDH 于 2021-2-12 18:26 编辑 . 1point3acres

27. Bag of words

For a collection of documents, find the vocabulary and the bag of word matrix.

Example:

Input:
doc1 = 'The quick brown fox jumps over the lazy wolf'
doc2 = 'The fast brown fox jumps over the lazy dog'. .и
doc3 = 'The speedy brown fox hops over the lazy dog'

Output:
(['brown',
  'dog',
  'fast',. 1point3acres
  'fox',
  'hops',. From 1point 3acres bbs
  'jumps',
  'lazy',.1point3acres
  'over',
  'quick',
  'speedy',
  'the',
  'wolf'],
[[1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 2, 1],
  [1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 2, 0],
  [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 0]]).1point3acres


  1. from collections import Counter

  2. def bag_of_words(docs):
  3.     """
  4.     Args:.
  5.     - docs: collection of documents

  6.     Returns:
  7.     - vocab: the vocabulary from the docs
  8.     - result: the bag og word matrix
  9.     """
  10.    
    .
  11.     # helper function to get bag of words for each doc in the docs
  12.     def bow_helper(doc, vocab):
  13.         doc_word_counts = Counter(doc)
  14.         doc_vec = [0]*len(vocab)
  15.         
  16.         for idx, word in enumerate(vocab):
  17.             if word in doc_word_counts:
  18.                 doc_vec[idx] += doc_word_counts[word]
  19.                
  20.         return doc_vec
  21.    
  22.     # get vocabulary of the docs
  23.     vocab  = sorted(list(set([word for doc in docs for word in doc])))
  24.     result = []
  25.    
  26.     # loop over each doc to get the bag of word matrix
  27.     for doc in docs:. Waral dи,
  28.         result.append(bow_helper(doc, vocab))
  29.         
  30.     return vocab, result
复制代码




  1. doc1 = 'The quick brown fox jumps over the lazy wolf'
  2. doc2 = 'The fast brown fox jumps over the lazy dog'
  3. doc3 = 'The speedy brown fox hops over the lazy dog'. 1point3acres


  4. docs = [[word.lower() for word in doc.split()] for doc in documents] # tokenize
  5. docs. 1point 3 acres
  6. . .и
  7. # [['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'wolf'],
  8. #  ['the', 'fast', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'],
  9. #  ['the', 'speedy', 'brown', 'fox', 'hops', 'over', 'the', 'lazy', 'dog']]


  10. bag_of_words(docs)-baidu 1point3acres

  11. # (['brown',
  12. #   'dog',
  13. #   'fast',-baidu 1point3acres
  14. #   'fox', ..
  15. #   'hops',
  16. #   'jumps',
  17. #   'lazy',
  18. #   'over',
  19. #   'quick',. .и
  20. #   'speedy',
  21. #   'the',-baidu 1point3acres
  22. #   'wolf'],. 1point3acres.com
  23. #  [[1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 2, 1],-baidu 1point3acres
  24. #   [1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 2, 0],
  25. #   [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 0]])
复制代码



. 1point3acres
.--
补充内容 (2021-2-19 02:51):
第二段代码补上:documents = [doc1, doc2, doc3]

感谢 wujiayikelly
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-12 19:25:24 | 只看该作者
全局:
28. Letter Combinations of a Phone Number (Leetcode 17)

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
Return the answer in any order.. 1point 3acres

# T: O(4^n). 1point 3 acres
# S: O(n)

  1. class Solution:. check 1point3acres for more.
  2.     def letterCombinations(self, digits):        . .и
  3.         if not digits or len(digits) == 0:
  4.             return []
  5.         
  6.         dic = {"2":"abc", "3":"def",
  7.                "4":"ghi", "5":"jkl",
  8.                "6":"mno", "7":"pqrs",
  9.                "8":"tuv", "9":"wxyz"}.google  и
  10.         
  11.         res = []
  12.         self.dfs(digits, dic, 0, "", res). .и
  13.         return res
  14.    
  15.     def dfs(self, digits, dic, index, path, res):
  16.         if len(path) == len(digits):. Waral dи,
  17.             res.append(path)
  18.             return
  19.         
  20.         for j in dic[digits[index]]:
  21.             self.dfs(digits, dic, index + 1, path + j, res)
  22.             


  23. if __name__ == "__main__":
  24.     assert Solution().letterCombinations("32") == ['da', 'db', 'dc', 'ea', 'eb', 'ec', 'fa', 'fb', 'fc']
  25.     assert Solution().letterCombinations("2") == ["a", "b", "c"]. 1point 3acres
  26.     assert Solution().letterCombinations("") == []
复制代码


回复

使用道具 举报

🔗
czhmily 2021-2-14 01:35:52 | 只看该作者
全局:
赞  常见的算法实现 还有decision tree 和 回归 期待LZ更新!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表