W3C高级算法挑战之python实现

最近在学python,网上很难找到对应的算法题网站,专业算法网站大部分都是国外的,之前在w3cschool看到有三个级别的Javascript脚本算法挑战,尝试用python实现,代码量相对比较少,如果你有更好的解法,还请不吝赐教,初学python,希望和大家一起日有所长。

目录

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

2.集合交集算法挑战

3.收银系统算法挑战

4.库存更新算法挑战

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

6.日期改写算法挑战

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

8.轨道周期算法挑战

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

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


如果传入字符串是一个有效的美国电话号码,则返回 true.

用户可以在表单中填入一个任意有效美国电话号码. 下面是一些有效号码的例子(还有下面测试时用到的一些变体写法):

 

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

 

在本节中你会看见如 800-692-7753 or 8oo-six427676;laskdjf这样的字符串. 你的任务就是验证前面给出的字符串是否是有效的美国电话号码. 区号是必须有的. 如果字符串中给出了国家代码, 你必须验证其是 1.如果号码有效就返回 true ; 否则返回 false.

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.

 

W3C高级算法挑战之python实现

2.集合交集算法挑战


创建一个函数,接受两个或多个数组,返回所给数组的 对等差分(symmetric difference)( or )数组.

给出两个集合 (如集合 A = {1, 2, 3} 和集合 B = {2, 3, 4}), 而数学术语 "对等差分" 的集合就是指由所有只在两个集合其中之一的元素组成的集合(A △ B = C = {1, 4}). 对于传入的额外集合 (如 D = {2, 3}), 你应该安装前面原则求前两个集合的结果与新集合的对等差分集合 (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}).

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].

 

W3C高级算法挑战之python实现

3.收银系统算法挑战


设计一个收银程序 checkCashRegister() ,其把购买价格(price)作为第一个参数 , 付款金额 (cash)作为第二个参数, 和收银机中零钱 (cid) 作为第三个参数.

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

当收银机中的钱不够找零时返回字符串 "Insufficient Funds". 如果正好则返回字符串 "Closed".

否者, 返回应找回的零钱列表,且由大到小存在二维数组中.

数据转换有点麻烦,整型和浮点型,字典与列表,解决的关键在于面额够不够找,找多少张的逻辑判断,感觉不是很完善,算法还可以改进。

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".

 

W3C高级算法挑战之python实现

4.库存更新算法挑战


依照一个存着新进货物的二维数组,更新存着现有库存(在 arr1 中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物名称的字母顺序排列.

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"]].

 

W3C高级算法挑战之python实现

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


把一个字符串中的字符重新排列生成新的字符串,返回新生成的字符串里没有连续重复字符的字符串个数.连续重复只以单个字符为准

例如, aab 应该返回 2 因为它总共有6中排列 (aabaababaababaabaa), 但是只有两个 (aba and aba)没有连续重复的字符 (在本例中是 a).

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

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

自己想没做出来,偷个巧python内置排列组合函数,嘻嘻

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.日期改写算法挑战


让日期区间更友好!

把常见的日期格式如:YYYY-MM-DD 转换成一种更易读的格式。

易读格式应该是用月份名称代替月份数字,用序数词代替数字来表示天 (1st 代替 1).

记住不要显示那些可以被推测出来的信息: 如果一个日期区间里结束日期与开始日期相差小于一年,则结束日期就不用写年份了。月份开始和结束日期如果在同一个月,则结束日期月份就不用写了。

另外, 如果开始日期年份是当前年份,且结束日期与开始日期小于一年,则开始日期的年份也不用写。

例如:

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"]

 

W3C高级算法挑战之python实现

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


用下面给定的方法构造一个对象.

方法有 getFirstName(), getLastName(), getFullName(), setFirstName(first), setLastName(last), and setFullName(firstAndLast).

所有有参数的方法只接受一个字符串参数.

所有的方法只与实体对象交互.

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()

 

W3C高级算法挑战之python实现

 

8.轨道周期算法挑战


返回一个数组,其内容是把原数组中对应元素的平均海拔转换成其对应的轨道周期.

原数组中会包含格式化的对象内容,像这样 {name: 'name', avgAlt: avgAlt}.

至于轨道周期怎么求,戳这里 on wikipedia (不想看英文的话可以自行搜索以轨道高度计算轨道周期的公式).

求得的值应该是一个与其最接近的整数,轨道是以地球为基准的.

地球半径是 6367.4447 kilometers, 地球的GM值是 398600.4418, 圆周率为Math.PI

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}]))

 

W3C高级算法挑战之python实现

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


找到你的另一半

都说优秀的程序员擅长面向对象编程,但却经常找不到另一半,这是为什么呢?因为你总是把自己局限成为一个程序员,没有打开自己的思维。

这是一个社群的时代啊,在这里你应该找到与你有相同价值观但又互补的另一半。

譬如:你编程能力强,估值11分,如果以20分为最佳情侣来计算,你应该找一个设计能力强,估值为9分的女生。

那么当你遇到一个设计能力为9分的女生,千万别犹豫,大胆去表白。千万别以为后面的瓜比前面的甜哦。

举个例子:有一个能力数组[7,9,11,13,15],按照最佳组合值为20来计算,只有7+13和9+11两种组合。而7在数组的索引为0,13在数组的索引为3,9在数组的索引为1,11在数组的索引为2。

所以我们说函数:pairwise([7,9,11,13,15],20) 的返回值应该是0+3+1+2的和,即6。

我们可以通过表格来更直观地查看数组中索引和值的关系:

 

Index 0 1 2 3 4
Value 7 9 11 13 15

思路很重要,先写出自己的处理逻辑,然后逐步分析逻辑中的数学方法,对应选择容器和方法来做

W3C高级算法挑战之python实现
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.

 

上一篇:MySQL——基础查询、取别名、去重和拼接等


下一篇:mysql之基础查询