1.判断电话号码算法挑战

2.集合交集算法挑战

3.收银系统算法挑战

4.库存更新算法挑战

5.排列组合去重算法挑战

6.日期改写算法挑战

7.类及对象构建算法挑战

8.轨道周期算法挑战

9.数据组合求值算法挑战

1.判断电话号码算法挑战

555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555

```def telephoneCheck(s):
i = 0
for x in s:
if x.isdigit(): i += 1
if "(" in s or ")" in s:
if "(" not in s or ")" not in s:
return False
if s[0] == "(" and s[-1] == ")": return False
if i == 10:
return True
elif i == 11:
return True if s[0] == "1" else False
else:
return False

print(telephoneCheck("1 555-555-5555"))  # 应该返回 true.
print(telephoneCheck("1 (555) 555-5555"))  # 应该返回 true.
print(telephoneCheck("555-555-5555"))  # 应该返回 true.
print(telephoneCheck("(555)555-5555"))  # 应该返回 true.
print(telephoneCheck("1(555)555-5555"))  # 应该返回 true.
print(telephoneCheck("1 555)555-5555"))  # 应该返回 false.
print(telephoneCheck("123**&!!asdf#"))  # 应该返回 false.
print(telephoneCheck("(6505552368)"))  # 应该返回 false
print(telephoneCheck("(275)76227382"))  # 应该返回 false.```

2.集合交集算法挑战

`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` 应该返回 `[1, 4, 5]`

```import functools

def sym(*args):
def diff(lst1, lst2):
lst = []
for i in lst1:
if i not in lst2:
lst.append(i)
for i in lst2:
if i not in lst1:
lst.append(i)
return list(set(lst))

lst = functools.reduce(diff, args)
return lst

print(sym([1, 2, 3], [5, 2, 1, 4]))  # 应该返回 [3, 4, 5].
print(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]))  # 应该返回 [1, 4, 5]
print(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]))  # 应该返回 [1, 4, 5].
print(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]))  # 应该返回 [2, 3, 4, 6, 7].
print(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]))  #  应该返回 [1, 2, 4, 5, 6, 7, 8, 9].```

3.收银系统算法挑战

`cid` 是一个二维数组，存着当前可用的找零.

```from math import floor

def checkCashRegister(price, cash, cid):
num = round(cash - price, 2)  # 浮点数精度问题，用round函数精确到分位即可得出金额准确数值
dct = {"PENNY": 0.01, "NICKEL": 0.05, "DIME": 0.1, "QUARTER": 0.25, "ONE": 1, "FIVE": 5, "TEN": 10, "TWENTY": 20,
"ONE HUNDRED": 100}
dct_rev = {v: k for k, v in dct.items()}
# 面额作为键，数量作为值，去掉0和大于需找零金额的键，得到dct_aftdel
dct_aftdel = {dct[i[0]]: round(i[1] / dct[i[0]]) for i in cid if i[1] and dct[i[0]] <= num}
sum_all = sum([i[1] for i in cid if dct[i[0]] in dct_aftdel])
if sum_all < num:
return "Insufficient Funds"
elif sum_all == num:
return "Closed"
else:
print(f"要找{num}元")
print(f"从这些钱里面找：{dct_aftdel}")
print(f"这些钱里面一共有{sum_all}元")
dct_return = {}
for i in sorted(dct_aftdel, reverse=True):
if i <= num:
if floor(num / i) <= dct_aftdel[i]: # 例如：要找他90，你有5张20，只需找他4张，如果只有4张，则4张都找给他
dct_return[i] = floor(num / i)  # 向下取整
print(f"找了{floor(num / i)}张{i}块的，还剩", end="")
num -= i * floor(num / i)
print(f"{round(num, 2)}")
num = round(num, 2)  # num_temp为浮点型，自减完之后需要分位取整

else:
dct_return[i] = dct_aftdel[i]
num -= i * dct_aftdel[i]
print(f"找了{dct_aftdel[i]}张{i}块的，还剩{round(num, 2)}")
num = round(num, 2)
lst_return = [[dct_rev[k], k * v] for k, v in dct_return.items()]
return lst_return

print(checkCashRegister(19.50, 20.00,
[["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00],
["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]))
# 应该返回 [["QUARTER", 0.50]].
print(checkCashRegister(3.26, 100.00,
[["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00],
["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]))
# 应该返回 [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].
print(checkCashRegister(19.50, 20.00,
[["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0],
["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]))
# 应该返回 "Insufficient Funds".
print(checkCashRegister(19.50, 20.00,
[["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0],
["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]))
# 应该返回 "Insufficient Funds".
print(checkCashRegister(19.50, 20.00,
[["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0],
["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]))
# 应该返回 "Closed".```

4.库存更新算法挑战

`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` 应该返回 `[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]`.

```def updateInventory(lst1, lst2):
lst_name = [i[1] for i in lst1] + [i[1] for i in lst2]
lst_quntity = [i[0] for i in lst1] + [i[0] for i in lst2]
dct = {}
# 字典去重名时计算数量
for i, j in zip(lst_name, lst_quntity):
if dct.get(i):
dct[i] = dct.get(i) + j
else:
dct[i] = j
lst = sorted([i for i in dct.items()])  # 按字母排序
lst = list(map(lambda x: list(reversed(x)), lst))  # 逆序
return lst

print(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]],
[[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]))
# 应该返回 [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]
print(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]],
[]))
# 应该返回 [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]].
print(updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7,
"Toothpaste"]]))
# 应该返回 [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]].
print(updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]],
[[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1,
"Toothpaste"]]))
# 应该返回 [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]].```

5.排列组合去重算法挑战

`permAlone("aaa")` 应该返回 0.

`permAlone("aabb")` 应该返回 8.

```import itertools

def permAlone(s):
num = 0
for i in itertools.permutations(s, len(s)):
for x in range(len(i) - 1):
if i[x] == i[x + 1]:
break
else:
num += 1
return num

print(permAlone("aab")) # 应该返回 2.
print(permAlone("aaa")) # 应该返回 0.
print(permAlone("abc")) # 应该返回 6.
print(permAlone("aabb")) # 应该返回 8.
print(permAlone("abcdefa")) # 应该返回 3600.
print(permAlone("abfdefa")) # 应该返回 2640.
print(permAlone("zzzzzzzz")) # 应该返回 0.```

6.日期改写算法挑战

`makeFriendlyDates(["2016-07-01", "2016-07-04"])` 应该返回 `["July 1st, 2016","4th"]`

`makeFriendlyDates(["2016-07-01", "2018-07-04"])` 应该返回 `["July 1st, 2016", "July 4th, 2018"]`.

`makeFriendlyDates(["2016-12-01", "2017-02-03"])` should return `["December 1st, 2016","February 3rd"]`.

```def makeFriendlyDates(lst):
dct1 = {1: "January", 2: "Februry", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August",
9: "September", 10: "October", 11: "November", 12: "December"}
dct2 = {1: "1st", 2: "2nd", 3: "3rd", 4: "4th", 5: "5th", 6: "6th", 7: "7th", 8: "8th", 9: "9th", 10: "10th",
11: "11th", 12: "12th", 13: "13th", 14: "14th", 15: "15th", 16: "16th", 17: "17th", 18: "18th", 19: "19th",
20: "20th", 21: "21st", 22: "22nd", 23: "23rd", 24: "24th", 25: "25th", 26: "26th", 27: "27th", 28: "28th",
29: "29th", 30: "30th", 31: "31st"}

date1 = lst[0].split("-")
date1 = list(map(int, date1))
date2 = lst[1].split("-")
date2 = list(map(int, date2))

if date1[0] == date2[0]:  # 同年
if date1[1] == date2[1]:
if date1[2] == date2[2]:
return [f"{dct1[date1[1]]} {dct2[date1[2]]}", f" {date1[0]}"]  # 同月同日
else:
return [f"{dct1[date1[1]]} {dct2[date1[2]]} {date1[0]}", f"{dct2[date2[2]]}"]  # 同月不同日
else:
return [f"{dct1[date1[1]]} {dct2[date1[2]]}, {date1[0]}", f" {dct1[date2[1]]} {dct2[date2[2]]}"]  # 不同月
else:
if date2[0] == date1[0] + 1 and (date2[1] < date1[1] or (date2[1] == date1[1] and date2[2] < date1[2])):
return [f"{dct1[date1[1]]} {dct2[date1[2]]}, {date1[0]}",
f" {dct1[date2[1]]} {dct2[date2[2]]}"]  # 不同年相隔一年以内
else:
return [f"{dct1[date1[1]]} {dct2[date1[2]]}, {date1[0]}",
f" {dct1[date2[1]]} {dct2[date2[2]]}, {date2[0]}"]  # 不同年相隔超过一年

print(makeFriendlyDates(["2016-07-01", "2016-07-04"]))
# 应该返回 ["July 1st, 2016","4th"]
print(makeFriendlyDates(["2016-07-01", "2018-07-04"]))
# 应该返回 ["July 1st, 2016", "July 4th, 2018"].
print(makeFriendlyDates(["2016-12-01", "2017-02-03"]))
# 应该返回 ["December 1st, 2016","February 3rd"].
print(makeFriendlyDates(["2016-12-01", "2018-02-03"]))
# 应该返回 ["December 1st, 2016","February 3rd, 2018"].
print(makeFriendlyDates(["2017-03-01", "2017-05-05"]))
# 应该返回 ["March 1st, 2017","May 5th"]
print(makeFriendlyDates(["2018-01-13", "2018-01-13"]))
# 应该返回 ["January 13th, 2018"].
print(makeFriendlyDates(["2022-09-05", "2023-09-04"]))
# 应该返回 ["September 5th, 2022","September 4th"].
print(makeFriendlyDates(["2022-09-05", "2023-09-05"]))
# 应该返回 ["September 5th, 2022","September 5th, 2023"]```

7.类及对象构建算法挑战

python基础的构造类、魔法初始化方法、实例方法

```class Person:
def __init__(self, s):
self.fullname = s
self.firstname = s[:s.find(" ")]
self.lastname = s[s.find(" ") + 1:]
# self.fullname = self.firstname + " " + self.lastname

def getFirstName(self):
print(f"FirstName是：{self.firstname}")
return self.firstname

def getLastName(self):
print(f"LastName是：{self.lastname}")
return self.lastname

def getFullName(self):
print(f"FullName是：{self.fullname}")
return self.fullname

def setFirstName(self, s):
print(f"FirstName:{self.firstname}被修改为{s}")
self.firstname = s
self.fullname = s + " " + self.lastname

def setLastName(self, s):
print(f"LastName:{self.lastname}被修改为{s}")
self.lastname = s
self.fullname = self.firstname + " " + s

def setFullName(self, s):
print(f"FullName:{self.fullname}被修改为{s}")
self.fullname = s
self.firstname = s[:s.find(" ")]
self.lastname = s[s.find(" ") + 1:]

bob = Person('Bob Ross')
bob.getFullName()

bob.setFirstName("David")
bob.getFirstName()

bob.setLastName("Alen")
bob.getLastName()

bob.setFullName("Bruce Lee")
bob.getFullName()```

8.轨道周期算法挑战

```orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]) 应该返回 [{name: "sputnik", orbitalPeriod: 86400}].

import math

def orbitalPeriod(lst):
r = 6367.4447
GM = 398600.4418
for dct in lst:
avgAlt = 2 * math.pi * math.sqrt(((dct["avgAlt"] + r) ** 3) / GM)
dct["orbitalPeriod"] = round(avgAlt)
del dct["avgAlt"]
return lst

print(orbitalPeriod([{"name": "sputnik", "avgAlt": 35873.5553}]))
print(orbitalPeriod(
[{"name": "iss", "avgAlt": 413.6}, {"name": "hubble", "avgAlt": 556.7}, {"name": "moon", "avgAlt": 378632.553}]))```

9.数据组合求值算法挑战

Index

0

1

2

3

4

Value

7

9

11

13

15

```def pairwise(lst, n):
if not lst: return 0  # 空列表返回0
# 字典去重，元素作为键，重复值索引放列表作为值
dct = {j: [] for j in lst}
for d in dct:
dct[d] = [i for i, j in enumerate(lst) if j == d]
# print(dct)
# 当n为偶数，元素为n/2，且有奇数对时，删掉最后一个元素的索引值
if n % 2 == 0:
if lst.count(n / 2) % 2 == 1:
dct[n / 2].pop()
# 找另一半n-d，找不到则删键,找到了删右边多余的索引值
for d in dct.copy():
if n - d not in dct:
dct.pop(d)
else:
dct[d] = dct[d][:min(len(dct[d]), len(dct[n - d]))]
# print(dct)
# 加总所有字典值
result = sum([sum(i) for i in dct.values()])
return result

print(pairwise([1, 4, 2, 3, 0, 5], 7))  # 应该返回 11.
print(pairwise([1, 3, 2, 4], 4))  # 应该返回 1.
print(pairwise([1, 1, 1], 2))  # 应该返回 1.
print(pairwise([0, 0, 0, 0, 1, 1, 2], 1))  # 应该返回 10.
print(pairwise([], 100))  # 应该返回 0.```

0 条评论

• Python生成html邮件

最近在学习Python，这是我第一个Python脚本。没有技术含量，之前不知道zip()函数，想让2个结果对应起来，弄了好久，后来问了做php的同事，才知道。

• 用Python实现一个简单的WebSoc

windows python 2.79, chrome37 firefox35通过

• python3--基础综合测试

解释：char类型在python中不存在，它是其他编程语言的一种数据类型，比如C/C++,JAVA

• 拯救阿波罗14号！那些伟大太空计划背后的计算机工程师们

外太空旅行近一周后的凌晨，回程中的阿波罗14号突然面临一个严峻的问题：它可能没办法正常降落了。

• 打卡群刷题总结0611——区域和检索-数组不可变

链接：https://leetcode-cn.com/problems/range-sum-query-immutable

• 利用php新特性过静态查杀

最近在研究webshell免杀，抽出心得的一个新颖的点。原因是突然想到既然php7.1不能利用可变函数的assert，那就利用php7的新特性来绕过查杀正则，最...

• 学界 | MIT提出像素级声源定位系统PixelPlayer：无监督地分离视频中的目标声源

选自arxiv 作者：Hang Zhao、Chuang Gan、Andrew Rouditchenko、Carl Vondrick Josh McDermott...

• 堆排序和优先队列的核心，堆究竟是怎样的数据结构？

和链表、二叉树以及数组这些热门的数据结构相比，堆相对比较冷门。如果你对数据结构了解不深的话，可能很少听说。但是我们经常用到它，虽然可能你并不一定能感知到。比如说...