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

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

   
🔗
 楼主| ZYYYZ 2021-2-3 09:28:39 | 只看该作者
全局:
6. Smallest difference of two arrays.1point3acres

Given two arrays of integers, compute the pair of values with the smallest non-negative difference.
Example: arr1: [1,3,15,11,2] and arr2: [23,127,135,19,8], then smallest difference 11-8 = 3

  1. def find_smallest_diff(arr1, arr2):
  2.     # T: O(mlogm + nlogn)
  3.     # S: O(1)
  4.     if not arr1 and not arr2:.1point3acres
  5.         return 0
  6.     if len(arr1) == 0:
  7.         return min(lst2)
  8.     if len(arr2) == 0:
  9.         return min(lst1)
  10.    
  11.     arr1.sort()
  12.     arr2.sort()
  13.    
  14.     p1, p2 = 0, 0
  15.     min_diff = float('inf')
  16.    
  17.     len1 = len(arr1)
  18.     len2 = len(arr2)
  19.    
  20.     while p1 < len1 and p2 < len2:
  21.         if abs(arr1[p1] - arr2[p2]) < min_diff:
  22.             min_diff = abs(arr1[p1] - arr2[p2])
  23.    
  24.         if arr1[p1] < arr2[p2]:
  25.             p1 += 1
  26.         else:
  27.             p2 += 1
  28.             
  29.     return min_diff. check 1point3acres for more.


  30. if __name__ == "__main__":
  31.     assert find_smallest_diff([1,3,15,11,2], [23,127,135,19,8]) == 3
  32.     assert find_smallest_diff([1,2,11,15], [4,12,19,23,127,235]) == 1
复制代码
. .и

回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-3 09:48:30 | 只看该作者
全局:
7. Dutch National Flag Problem (荷兰国旗问题)
此题即Leetcode 75 Sort Colors

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.. 1point3acres.com

Example:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

  1. # [url]https://leetcode.com/problems/sort-colors/[/url]. .и


  2. class Solution:
  3.     def sortColors(self, nums):
  4.         """
  5.         Do not return anything, modify nums in-place instead.
  6.         """
  7.         # T: O(n)
  8.         # S: O(1)
  9.         if not nums or len(nums) == 0:
  10.             return
  11.         
  12.         left, right = 0, len(nums) - 1
  13.         index = 0
    . 1point 3acres
  14.         . Χ
  15.         while index <= right:. Χ
  16.             if nums[index] == 0:
  17.                 self.swap(nums, index, left)
  18.                 index += 1
  19.                 left += 1
  20.                
  21.             elif nums[index] == 1:
  22.                 index += 1
  23.                
  24.             else:
  25.                 self.swap(nums, index, right)
  26.                 right -= 1
  27.         
  28.     def swap(self, nums, i, j):
  29.         nums[i], nums[j] = nums[j], nums[i].
  30.         

  31.         
  32. if __name__ == "__main__":
  33.     arr1 = [2, 0, 2, 1, 1, 0]
  34.     Solution().sortColors(arr1)
  35.     assert arr1 == [0, 0, 1, 1, 2, 2]. check 1point3acres for more.
  36.    
  37.     arr2 = [2, 0, 1]
  38.     Solution().sortColors(arr2)
  39.     assert arr2 == [0, 1, 2]
复制代码


回复

使用道具 举报

🔗
xtang3 2021-2-3 10:05:23 | 只看该作者
本楼:
全局:
非常感谢!
回复

使用道具 举报

🔗
AZKnight 2021-2-3 10:08:57 | 只看该作者
全局:
应该会用到,收藏了,
谢谢分享
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-3 11:27:58 | 只看该作者
全局:
8 Count Primes (leetcode 204)

Count the number of prime numbers less than a non-negative number, n.

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.. Waral dи,

算法:.
埃拉托色尼筛选法,详见https://zh.wikipedia.org/wiki/%E ... C%E7%AD%9B%E6%B3%95.

  1. class Solution:
  2.     def countPrimes(self, n: int) -> int:
  3.         # T: O(nloglogn), S: O(n)
  4.         if n <= 2:
  5.             return 0
  6.         
  7.         is_prime = [True]*n
  8.         is_prime[0], is_prime[1] = False, False
  9.         . 1point 3 acres
  10.         for i in range(2, int((n - 1)**0.5) + 1):
  11.             if is_prime[i]:
  12.                 for j in range(i**2, n, i):
  13.                     is_prime[j] = False
  14.                     
  15.         return len([x for x in range(2, n) if is_prime[x]]). 1point3acres.com
  16.    
  17.     . 1point3acres.com
  18. if __name__ == "__main__":
  19.     assert Solution().countPrimes(10) == 4
复制代码


回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-3 11:48:22 | 只看该作者
全局:
9. Most Frequent Words

Given a file that contains the text of a document and an integer k, return a list of the top k most frequent words.
. check 1point3acres for more.
比如程序同路径下文件test.txt
  1. """. 1point3acres
  2. test.txt:
  3. This is an apple
  4. I like the orange
  5. An apple is red. 1point3acres
  6. """
复制代码
. 1point3acres



这个文件的word count:
  1. {'this': 1, 'is': 2, 'an': 2, 'apple': 2, 'i': 1, 'like': 1, 'the': 1, 'orange': 1, 'red': 1}
复制代码


. 1point 3 acres
所以如果要找到top 3 most frequent words,就是 ['is', 'an', 'apple']

. Χ
  1. def top_k_freq_words(filename, k):
  2.     with open(filename, "r") as file:
  3.         s = file.read()
  4.         
  5.     words = s.split()
  6.     cnt = {}
  7.    
  8.     for word in words:
  9.         cnt[word.lower()] = cnt.get(word.lower(), 0) + 1
  10.    
  11.     data = list(cnt.items())
  12.     data.sort(key=lambda x: x[1], reverse=True)
  13.    
  14.     return [x[0] for x in data[:k]]

  15. . Χ
  16. if __name__ == "__main__":
  17.     assert top_k_freq_words("test.txt", 3) == ['is', 'an', 'apple']
复制代码
.google  и


回复

使用道具 举报

全局:
多谢楼主!超级有用,希望能持续更新下去,感谢感谢!
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-3 13:13:41 | 只看该作者
全局:
10. Welford's online algorithm

Welford’s algorithm is online or parallel algorithm for calculating means and variances.

It is often useful to be able to compute the variance in a single pass, inspecting each value x_i only once; for example, when the data are being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. . 1point3acres

这个算法可以不需要占据内存计算数据流的aggregation statistics。The calulation can be done on the fly.

算法和Implementation参考:.1point3acres
https://en.wikipedia.org/wiki/Al ... ce#Online_algorithm
https://www.johndcook.com/blog/standard_deviation.1point3acres
. 1point3acres
  1. import math

  2. class Running_Stats:
  3.    
  4.     def __init__(self):. 1point3acres.com
  5.         self.n = 0
  6.         self.m_old = 0 # m stands for mean
  7.         self.m_new = 0
  8.         self.ss_old = 0 # ss stands for sum of squares
  9.         self.ss_new = 0. .и
  10.         .google  и
  11.     def clear(self):.--
  12.         self.n = 0. 1point 3 acres
  13.         
  14.     def push(self, x):
  15.         self.n += 1
  16.         .google  и
  17.         if self.n == 1:.--
  18.             self.m_old  = self.m_new = x
  19.             self.ss_old = 0
  20.         else:
  21.             self.m_new  = self.m_old + (x - self.m_old)/self.n
  22.             self.ss_new = self.ss_old + (x - self.m_old)*(x - self.m_new)
  23.             
  24.             self.m_old  = self.m_new
  25.             self.ss_old = self.ss_new
  26.             
  27.     def mean(self):
  28.         return self.m_new if self.n else 0.0
  29.    
  30.     def var(self):. Χ
  31.         return self.ss_new/(self.n - 1) if self.n > 1 else 0.0
  32.    
  33.     def std_dev(self):
  34.         return math.sqrt(self.var())
  35.    
  36. . ----
  37.    
  38. if __name__ == "__main__":    . From 1point 3acres bbs
  39.     rs = Running_Stats()
  40.     rs.push(17.0)
  41.     rs.push(19.0). 1point3acres
  42.     rs.push(24.0)

  43.     mean = rs.mean(). Waral dи,
  44.     variance = rs.var(). From 1point 3acres bbs
  45.     stdev = rs.std_dev()

  46.     print(f'Mean: {mean}, Variance: {variance}, Std. Dev.: {stdev}')
  47.     # Mean: 20.0, Variance: 13.0, Std. Dev.: 3.605551275463989
复制代码
. 1point3acres.com
. Waral dи,
回复

使用道具 举报

🔗
 楼主| ZYYYZ 2021-2-3 13:54:52 | 只看该作者
全局:
11. Word Break (leetcode 139).--
.
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:-baidu 1point3acres

The same word in the dictionary may be reused multiple times in the segmentation.-baidu 1point3acres
You may assume the dictionary does not contain duplicate words.. From 1point 3acres bbs

Example:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation:
Return true because "applepenapple" can be segmented as "apple pen apple".. 1point3acres.com
Note that you are allowed to reuse a dictionary word.

  1. class Solution:-baidu 1point3acres
  2.     # T:O(n^2), S:O(n)
  3.     def wordBreak(self, s, wordDict):
  4.         dp = [False]*(len(s) + 1)
  5.         dp[0] = True
  6.         
  7.         for i in range(1, len(s) + 1):
  8.             for j in range(i):
  9.                 if dp[j] and s[j:i] in wordDict:
  10.                     dp[i] = True
  11.                     break
  12.                     
  13.         return dp[len(s)]
  14.    
  15.    
  16. if __name__ == '__main__':
  17.     assert Solution().wordBreak("leetcode", ["leet", "code"]) == True
  18.     assert Solution().wordBreak("applepenapple", ["apple", "pen"]) == True
  19.     assert Solution().wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]) == False
复制代码

.1point3acres
回复

使用道具 举报

全局:
YZDH 发表于 2021-2-2 13:12
1. Weighted Sampling
. Χ
You are given n numbers as well as probabilities p_0, p_1, ... , p_{n - 1},  ...

好题啊,学到了
回复

使用道具 举报

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

本版积分规则

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