楼主: 李浩泉
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] LC Python 刷题笔记 有志者事竟成

   
🔗
 楼主| 李浩泉 2020-8-6 04:18:14 | 只看该作者
全局:

3-4级DE电面时候中等难度的题,5道题里面的第2-3道题

Sort the numbers in an array. But the position of zeros should not be changed.

Input: A List.

Output: An Iterable (tuple, list, iterator ...).

Example:

except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7]) == [1, 3, 0, 0, 4, 4, 5, 0, 7]
except_zero([0, 2, 3, 1, 0, 4, 5]) == [0, 1, 2, 3, 0, 4, 5]


  1. def except_zero(items):
  2.     list1 = []
  3.     for num in items:
  4.         if num != 0:
  5.             list1.append(num)
  6.     list1.sort()
  7.    
  8.     j = 0
  9.     for i in range(len(items)):
  10.         if items[i] != 0:
  11.             items[i] = list1[j]
  12.             j += 1
  13.     return items
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-6 06:50:54 | 只看该作者
全局:
比较经典的排序题

Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should not modify the contents of the original iterable.

Input: Iterable

Output: Iterable

Example:

reverse_ascending([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3]) == [10, 7, 5, 4, 8, 7, 2, 3, 1]
  1. def reverse_ascending(items):
  2.     if len(items) == 0: return []
  3.     list1 = []
  4.     list2 = []
  5.     block = 0
  6.     for num in items:
  7.         if num > block:
  8.             list2.append(num)
  9.             block = num
  10.         else:
  11.             list2 = sorted(list2,reverse=True)
  12.             list1 = list1 + list2
  13.             list2 = []
  14.             list2.append(num)
  15.             block = num
  16.     if list2 != []:
  17.         list2 = sorted(list2,reverse=True)
  18.         list1 = list1 + list2
  19.         return list1
  20.     else:
  21.         return list1


  22. if __name__ == '__main__':
  23.     print("Example:")
  24.     print(reverse_ascending([1, 2, 3, 4, 5]))

  25.     # These "asserts" are used for self-checking and not for an auto-testing
  26.     assert list(reverse_ascending([1, 2, 3, 4, 5])) == [5, 4, 3, 2, 1]
  27.     assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [10, 7, 5, 4, 8, 7, 2, 3, 1]
  28.     assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1]
  29.     assert list(reverse_ascending([])) == []
  30.     assert list(reverse_ascending([1])) == [1]
  31.     assert list(reverse_ascending([1, 1])) == [1, 1]
  32.     assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1]
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-6 07:32:00 | 只看该作者
全局:
本帖最后由 李浩泉 于 2020-8-6 07:33 编辑

同样的题,SDE可能要modify in place,DE就简单一些,随便建list,加循环,不需要太多考虑复杂度。

A given list should be "compressed" in a way so, instead of two (or more) equal elements, staying one after another, there is only one in the result Iterable (list, tuple, iterator ...).

Input: List.

Output: "Compressed" Iterable (list, tuple, iterator ...).


compress([
  5, 5, 5,
  4, 5, 6,
  6, 5, 5,
  7, 8, 0,
  0]) == [5, 4, 5, 6, 5, 7, 8, 0]
compress([1, 1, 1, 1, 2, 2, 2, 1, 1, 1]) == [1, 2, 1]

  1. from typing import Iterable


  2. def compress(items: list) -> Iterable:
  3.     if len(items) < 2: return items
  4.     list1 = []
  5.     c = float('inf')
  6.     for num in items:
  7.         if num != c:
  8.             list1.append(num)
  9.             c = num
  10.     return list1


  11. if __name__ == '__main__':
  12.     print("Example:")
  13.     print(list(compress([
  14.   5, 5, 5,
  15.   4, 5, 6,
  16.   6, 5, 5,
  17.   7, 8, 0,
  18.   0])))

  19.     # These "asserts" are used for self-checking and not for an auto-testing
  20.     assert list(compress([
  21.   5, 5, 5,
  22.   4, 5, 6,
  23.   6, 5, 5,
  24.   7, 8, 0,
  25.   0])) == [5, 4, 5, 6, 5, 7, 8, 0]
  26.     assert list(compress([1, 1, 1, 1, 2, 2, 2, 1, 1, 1])) == [1, 2, 1]
  27.     assert list(compress([7, 7])) == [7]
  28.     assert list(compress([])) == []
  29.     assert list(compress([1, 2, 3, 4])) == [1, 2, 3, 4]
  30.     assert list(compress([9, 9, 9, 9, 9, 9, 9])) == [9]
  31.     print("Coding complete? Click 'Check' to earn cool rewards!")
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-6 11:29:36 | 只看该作者
全局:



Given an iterable of ints , create and return a new iterable whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position.

Input: Iterable of ints.

Output: Iterable of ints.

Example:

list(median_three([1, 2, 3, 4, 5, 6, 7])) == [1, 2, 2, 3, 4, 5, 6]
list(median_three([1])) == [1]
list(median_three([-1, 0, 1])) == [-1, 0, 0]

  1. from typing import Iterable

  2. def median_three(els: Iterable[int]) -> Iterable[int]:
  3.     list1 = els[:2]
  4.     for i in range(2,len(els)):
  5.         list2 = els[i-2:i+1]
  6.         list2.sort()
  7.         list1.append(list2[1])
  8.     return list1

  9. if __name__ == '__main__':
  10.     print("Example:")
  11.     print(list(median_three([1, 2, 3, 4, 5, 6, 7])))
  12.    
  13.     # These "asserts" are used for self-checking and not for an auto-testing
  14.     assert list(median_three([1, 2, 3, 4, 5, 6, 7])) == [1, 2, 2, 3, 4, 5, 6]
  15.     assert list(median_three([1])) == [1]
  16.     print("Coding complete? Click 'Check' to earn cool rewards!")
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-6 12:17:07 | 只看该作者
全局:
本帖最后由 李浩泉 于 2020-8-6 12:19 编辑

再次遭到了10万点暴击!!!

There is a list which contains integers or other nested lists which may contain yet more lists and integers which then… you get the idea. You should put all of the integer values into one flat list. The order should be as it was in the original list with string representation from left to right.

Data Pipeline ETL 之前的数据清洗

Input data: A nested list with integers.

Output data: The one-dimensional list with integers.

Example:

flat_list([1, 2, 3]) == [1, 2, 3]
flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1]


SDE给DE5定的标准答案:

  1. def flat_list(array):
  2.     return sum(([x] if type(x) != list else flat_list(x) for x in array), [])
复制代码





我的答案:

  1. def flat_list(array):
  2.     list1 = str(array).replace('[','').replace(']','').replace(' ','').split(',')
  3.     if len(list1) == 0 or list1 == ['']: return []
  4.     list2 = []
  5.     for c in list1:
  6.         if c != '':
  7.             list2.append(int(c))
  8.     return list2
复制代码





回复

使用道具 举报

全局:
加油加油!!冲啊,关注下,在职da想跳槽感觉需要刷题,今年bar好高啊,没抽到h1b也很受限
回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-6 23:26:52 | 只看该作者
全局:
上一道题是清理列表,这一道题是清理字典。

感觉面试DE,如果刷LC算法可能是在浪费时间,DE不考算法,但是DE的coding操作对基本功要求非常高。

You are given a dictionary where the keys are strings and the values are strings or dictionaries. The goal is flatten the dictionary, but save the structures in the keys. The result should be the a dictionary without the nested dictionaries. The keys should contain paths that contain the parent keys from the original dictionary. The keys in the path are separated by a "/". If a value is an empty dictionary, then it should be replaced by an empty string (""). Let's look at an example:

{
    "name": {
        "first": "One",
        "last": "Drone"
    },
    "job": "scout",
    "recent": {},
    "additional": {
        "place": {
            "zone": "1",
            "cell": "2"}
    }
}

The result will be:

{"name/first": "One",           #one parent
"name/last": "Drone",
"job": "scout",                #root key
"recent": "",                  #empty dict
"additional/place/zone": "1",  #third level
"additional/place/cell": "2"}

Input: An original dictionary as a dict.

Output: The flattened dictionary as a dict.

Example:

flatten({"key": "value"}) == {"key": "value"}
flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"}
flatten({"empty": {}}) == {"empty": ""}


  1. def flatten(dictionary):
  2.     if all(type(v) is str for v in dictionary.values()):
  3.         return dictionary
  4.     dic = {}
  5.     for key in dictionary.keys():
  6.         if type(dictionary[key]) is str:
  7.             dic[key] = dictionary[key]
  8.         elif len(dictionary[key])==0:
  9.             dic[key] = ''
  10.         else:
  11.             E = flatten(dictionary[key])
  12.             for keyE in E:
  13.                 dic[key+'/'+keyE] = E[keyE]
  14.     return dic



  15. if __name__ == '__main__':
  16.     test_input = {"key": {"deeper": {"more": {"enough": "value"}}}}
  17.     print('Input : {}'.format(test_input))
  18.     print('Output: {}'.format(flatten(test_input)))

  19.     #These "asserts" using only for self-checking and not necessary for auto-testing
  20.     assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
  21.     assert flatten(
  22.         {"key": {"deeper": {"more": {"enough": "value"}}}}
  23.     ) == {"key/deeper/more/enough": "value"}, "Nested"
  24.     assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
  25.     assert flatten({"name": {
  26.                         "first": "One",
  27.                         "last": "Drone"},
  28.                     "job": "scout",
  29.                     "recent": {},
  30.                     "additional": {
  31.                         "place": {
  32.                             "zone": "1",
  33.                             "cell": "2"}}}
  34.     ) == {"name/first": "One",
  35.           "name/last": "Drone",
  36.           "job": "scout",
  37.           "recent": "",
  38.           "additional/place/zone": "1",
  39.           "additional/place/cell": "2"}
  40.     print('You all set. Click "Check" now!')
复制代码


回复

使用道具 举报

地里匿名用户
🔗
匿名用户-8ZMJY  2020-8-10 06:57:25
李浩泉 发表于 2020-8-6 23:26
上一道题是清理列表,这一道题是清理字典。

感觉面试DE,如果刷LC算法可能是在浪费时间,DE不考算法,但 ...

lz清理字典这属于电面的难度还是onsite的难度啊?
大龄转码真的心酸,想求问lz说说onsite是不是难度更大,能不能给个例题,好给其他大龄转码的伙伴一个参考啊?感激不尽!
回复

使用道具 举报

全局:
去一般的公司做到senior就有这个工资了吧。不需要天分啥的,有点经验就行。
回复

使用道具 举报

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

本版积分规则

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