Codewar 笔记

1. Weight for weight

题目:

For example 99 will have “weight” 18, 100 will have “weight” 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by “weights” of these numbers?

Example:
“56 65 74 100 99 68 86 180 90” ordered by numbers weights becomes: “100 180 90 56 65 74 68 86 99”

最优答案:
在这里插入图片描述
小归纳:
sorted函数:

  • 方法返回的是一个新list,另一个函数sort()在原来list排序
  • 语法:sorted( iterable, key=None, reverse=False)

另一个例子:

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> result_list = sorted(example_list, key=lambda x: x*-1)
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
>>>```

lambda函数:冒号左边是参数,可包含多个参数;右边是表达式
例子:

a = lambda x,y: x+y
print(a(5,6))

#结果为:11

2. Vowel Count

题目:

Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.

我的答案:

def getCount(inputStr):
    num = 0
    for s in inputStr:
        if s in 'aeiou':
            num = num+1
    # your code here
    return num

最优答案:

def getCount(inputStr):
    return sum(1 for let in inputStr if let in "aeiouAEIOU")

小归纳:

  • 列表推导
  • 注意考虑大小写
  • 巧用sum函数

3. Sort the odd

题目:

You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn’t an odd number and you don’t need to move it. If you have an empty array, you need to return it.

Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

我的答案:

def sort_array(source_array):
    # Return a sorted array.
    l = []
    l2 = []
    for i in source_array:
        if i%2 == 0:
            l.append([source_array.index(i),i])
        else: 
            l2.append(i)
    l2 = sorted(l2)
    for k in l:
        l2.insert(k[0],k[1])
    return l2

改进:

def sort_array(source_array):
    l = []
    l2 = []
    l = [[k,v] for k,v in enumerate(source_array) if v%2 == 0]
    l2 = sorted((x for x in source_array if x%2 != 0))
    for k in l:
        l2.insert(k[0],k[1])
    return l2

最优答案:

def sort_array(arr):
  odds = sorted((x for x in arr if x%2 != 0), reverse=True)
  return [x if x%2==0 else odds.pop() for x in arr]

小归纳:

  • 我的答案-用list嵌套来定位到偶数的下标及其值,将奇数项进行排序那步可以再简化
  • enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
  • pop函数,默认去掉序列中的最后一个元素,可自定义下标去掉对应的元素;函数返回的是被去掉的那个元素

4. Tribonacci Sequence

题目:

well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won’t get to hear non-native Italian speakers trying to pronounce it 😦

So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence:
[1, 1 ,1, 3, 5, 9, 17, 31, …]

我的答案:

def tribonacci(l, n):
    while len(l)< n:
        l.append(l[-1] +l[-2] +l[-3])
    return l[:n]   

最优答案:

def tribonacci(signature, n):
  res = signature[:n]
  for i in range(n - 3): res.append(sum(res[-3:]))
  return res

其他答案:

def tribonacci(signature,n):
    while len(signature) < n:
        signature.append(sum(signature[-3:]))
    
    return signature[:n]

小归纳:

  • 我的答案跟第三个答案思路相同,while循环,但他的答案巧用sum和下标拆分
  • 最优的答案,用的是for循环,但感觉我的答案更加简洁,易懂

5. Directions Reduction

题目:求最简路线

Once upon a time, on a way through the old wild mountainous west,…
… a man was given directions to go from one point to another. The directions were “NORTH”, “SOUTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too.

Going to one direction and coming back the opposite direction right away is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it’s important to save yourself some energy, otherwise you might die of thirst!

How I crossed a mountain desert the smart way.
The directions given to the man are, for example, the following (depending on the language):
[“NORTH”, “SOUTH”, “SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”]
You can immediatly see that going “NORTH” and immediately “SOUTH” is not reasonable, better stay to the same place! So the task is to give to the man a simplified version of the plan. A better plan in this case is simply:
[“WEST”]

最优答案:

opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}

def dirReduc(plan):
    new_plan = []
    for d in plan:
        if new_plan and new_plan[-1] == opposite[d]:
            new_plan.pop()
        else:
            new_plan.append(d)
    return new_plan

第二优答案:

def dirReduc(arr):
    dir = " ".join(arr)
    dir2 = dir.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'')
    dir3 = dir2.split()
    return dirReduc(dir3) if len(dir3) < len(arr) else dir3

小归纳:

  • 用字典的key和value 来建立对立方向关系
  • 最优答案中的if 语句很巧妙,用and运算符,来避免下标溢出的情况
  • 主要解题思路:相邻两个元素不能是对立关系,否则就两者同时清除
  • 第二优答案用的递归方式,用replace 函数清除掉对立的相邻两个方向,直到没有为止

6. The observed PIN

题目:

The keypad has the following layout:
┌───┬───┬───┐│ 1 │ 2 │ 3 │├───┼───┼───┤│ 4 │ 5 │ 6 │├───┼───┼───┤│ 7 │ 8 │ 9 │└───┼───┼───┘│ 0 │└───┘
He noted the PIN 1357, but he also said, it is possible that each of the digits he saw could actually be another adjacent digit
(horizontally or vertically, but not diagonally). E.g. instead of the
1 it could also be the 2 or 4. And instead of the 5 it could also be
the 2, 4, 6 or 8.

我的答案:

import itertools

def get_pins(observed):
  '''TODO: This is your job, detective!'''
  l = []
  num_l = {'1':[1,2,4], '2':[1,2,3,5], '3':[2,3,6], '4':[1,4,5,7], '5': [2,4,5,6,8], '6':[3,5,6,9],'7':[4,7,8],'8':[5,7,0,8,9],'9':[6,8,9], '0':[0,8]}
  result_l = []
  for item in observed:
      l.append(num_l[item])
  combin_num = list(itertools.product(*l))  
  for single_tu in combin_num:
      x = ''
      for i in list(single_tu):
          x = x+str(i)
      result_l.append(str(x))
  return result_l

优秀答案:

PINS = {'1': '124', '2': '1253', '3': '236', '4': '1457', '5': '24568',
        '6': '3569', '7': '478', '8': '57890', '9': '689', '0': '08'}

def get_pins(observed):
    return list(map(''.join, product(*[PINS[num] for num in observed])))

小归纳:

  • itertools模块中的product 函数:计算笛卡尔积,返回所有的元组组合
  • 笛卡尔积(两个集合X和Y的笛卡尔积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员)
  • *args:接受任意个参数,**kwargs:接受任意个关键字参数
  • map函数,map(function, iterable, …): 函数,一个或多个序列

7. Did I Finish my Sudoku?

题目:

简要概括,判断9*9的一个矩阵是否完成了数独(数独的横列和纵列以及每个九宫格都是包含1-9且都是唯一的)
期望:返回‘Finished’ 或者 ‘Try again’
test.assert_equals(done_or_not([[1, 3, 2, 5, 7, 9, 4, 6, 8]
,[4, 9, 8, 2, 6, 1, 3, 7, 5]
,[7, 5, 6, 3, 8, 4, 2, 1, 9]
,[6, 4, 3, 1, 5, 8, 7, 9, 2]
,[5, 2, 1, 7, 9, 3, 8, 4, 6]
,[9, 8, 7, 4, 2, 6, 5, 3, 1]
,[2, 1, 4, 9, 3, 5, 6, 8, 7]
,[3, 6, 5, 8, 1, 7, 9, 2, 4]
,[8, 7, 9, 6, 4, 2, 1, 3, 5]]), ‘Try again!’);

思路:

  • 横列可以直接通过一层for循环来获得
  • 竖列:用zip函数,形成新的竖列
  • 区域是嵌套循环遍历,巧用切片
  • 判断是否符合条件,用set函数判断

答案:

def done_or_not(board): #board[i][j]
    for row in board:
        if len(set(row))<9:
            return 'Try again!'
    for col in zip(*board):
        if len(set(col))<9:
            return 'Try again!'
    
    for i in range(3):
        for j in range(3):
            l = []
            for row in board[i*3:i*3+3]:
                l = l + row[j*3:j*3+3]
            if len(set(l))<9:
                return 'Try again!'
                
    return 'Finished!'    

小归纳:

  • set函数:返回一个去除重复项并进行排序的列表
  • zip函数:zip([iterable, …]) 多个序列,将每个序列对应的元素打包成一个个元组,返回由这些元组组成的列表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值