Erlo

W3C高级算法挑战之python实现

时间:2019-03-15 20:01   阅读:35次   来源:博客园页面报错

点赞 打赏

×打赏

支付宝

微信

最近在学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.

 

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

 

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

 

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

 

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: "10t
            
        
下一篇:Centos7.6下安装Python3.7

评论留言

还没有评论留言,赶紧来抢楼吧~~

Erlo大厅()

* 这里是“吐槽厅”,所有人可看,只保留当天信息。

  • Erlo.vip2019-05-24 14:45:43Hello、欢迎使用吐槽厅,这里是个吐槽的地方。
  • 返回顶部