Codewar 笔记

article/2025/11/11 16:06:58

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 = 0for s in inputStr:if s in 'aeiou':num = num+1# your code herereturn 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 itertoolsdef 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, …]) 多个序列,将每个序列对应的元素打包成一个个元组,返回由这些元组组成的列表

http://chatgpt.dhexx.cn/article/KCHZvowS.shtml

相关文章

codewar刷题,苦海造舟之始

今天又是被惨虐的一天&#xff0c;尽管今天是我这篇处女座发布的日子。   事情是这样的&#xff0c;身为一个刚迈步进入编程领域的小白&#xff0c;在无忧无虑&#xff0c;轻松惬意的心情下刷完了一套python课后&#xff0c;偶然间&#xff0c;很突然地了解到codewars这么个玩…

Codewar一些积累No.2 从矩阵的加法体会vector的用法

用代码实现矩阵加法问题 最近在Codewar上看到一个有趣的问题是关于矩阵的加法问题. 题目中, 我所要编写的函数的传入参数是两个向量, 而且此向量是嵌套的, 具体内容如下: std::vector<std::vector<int> > matrixAddition(std::vector<std::vector<int> …

Java到底好不好学

Java到底好不好学 答案是&#xff1a;不难学。很多人都以为编程是个很高深的东西&#xff0c;其实不然&#xff0c;真正学习了你会发现编程比你高中学的数理化要简单的多。说它不难呢&#xff0c;如果学深入了&#xff0c;还算有很多东西要学习&#xff0c;比如你学Java&#…

java面试为何那么难

java面试为何那么难 “面试造火箭、工作拧螺丝”&#xff0c;曾经这么一句调侃的话总是用来形容IT行业中的面试情况。作为一个流浪的程序猿&#xff0c;多年以来作为应聘者也好、面试官也罢&#xff0c;渐渐感受到java开发的面试不再仅仅在“造火箭”那么容易。 我的就职历程…

java面试为何那么难?

“面试造火箭、工作拧螺丝”&#xff0c;曾经这么一句调侃的话总是用来形容IT行业中的面试情况。作为一个流浪的程序猿&#xff0c;多年以来作为应聘者也好、面试官也罢&#xff0c;渐渐感受到java开发的面试不再仅仅在“造火箭”那么容易。 五年前的java面试是怎么样的 用HT…

女生学java开发难吗?女生适合学java吗?

女生学java开发&#xff1f;Java开发看上去是一项系统性很强、入门很难的“高大上”学科&#xff0c;前端、代码这些普通人基本不会接触到的名词&#xff0c;吓怕了众多初学者。大部分人对于Java程序员都有一个既定印象&#xff0c;那就是程序员都是男生。女程序员可以说是“稀…

自学java难吗?给java初学者的一些建议。

自学java到底难不难&#xff1f; 其实学习java说难不难&#xff0c;说简单也不简单。如今互联网十分发达&#xff0c;各种学习资料&#xff0c;视频&#xff0c;文档都可以在网上找到。可以说如今是一个全民自学的时代&#xff0c;你要你有决心和时间&#xff0c;足不出户便能…

java编程难学吗?

java是一门面向对象编程语言&#xff0c;不仅吸收了C语言的各种优点&#xff0c;还摒弃了C里难以理解的多继承、指针等概念&#xff0c;因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表&#xff0c;极好地实现了面向对象理论&#xff0c;…

初学者的困境,Java自学难吗

Java自学起来难吗&#xff1f;动力节点小编告诉你&#xff0c;虽然Java适合新手入门&#xff0c;但是难度不能算简单哦&#xff0c;毕竟也是一门知识体系比较多的技术知识。在学习Java编程时&#xff0c;您会遇到一些简单的概念&#xff0c;如变量和函数。但也有更抽象、复杂的…

学python和java哪个难?,java和python哪个难学

java和python哪个好学 ①python比Java简单&#xff0c;学习成本低&#xff0c;开发效率高;②Java运行效率高于python&#xff0c;尤其是纯python开发的程序&#xff0c;效率极低;③Java相关资料多&#xff0c;尤其是中文资料;④Java版本比较稳定&#xff0c;python2和3不兼容导…

该说不说,Java面试是真的难

作为一名优秀的程序员&#xff0c;技术面试都是不可避免的一个环节&#xff0c;一般技术面试官都会通过自己的方式去考察程序员的技术功底与基础理论知识。 如果你参加过一些大厂面试&#xff0c;肯定会遇到一些这样的问题&#xff1a; 1、看你项目都用的框架&#xff0c;熟悉…

java到底难在哪里?

作为一个已经上岸和还不错的程序员来说&#xff0c;java到底难在哪里&#xff0c;在我看来可能难在坚持吧&#xff0c;毕竟过程是难熬的&#xff0c;毕竟走出了新手村. 今天我把读者自学上岸并成功入行的经验分享给大家&#xff0c;希望能帮助到大家。他自学的时候经常来咨询我…

java到底有多难

74%的人认为不难 有人曾经做过统计&#xff0c;询问500多已经参加工作的 Java开发者&#xff0c;“学习java是否困难&#xff1f;”有74%的人认为不难&#xff0c;说难学的仅占26%&#xff0c;那么这74%全部都是聪明人&#xff0c;智商比普通人高吗&#xff1f;显然不是的。 …

自学Java难吗?别在听一些人说了

总听到一些人在说自学Java有多难多难&#xff0c;确实&#xff0c;Java不是那么容易能够掌握的语言&#xff0c;可自己都没有尝试学过&#xff0c;就只听别人的一面之词&#xff0c;岂不是要错过这门前途似锦的开发语言了。 自学难&#xff0c;其实跟你的学习能力&#xff0c;…

自学java难吗?给java初学者的一些建议

自学java到底难不难&#xff1f; 其实学习java说难不难&#xff0c;说简单也不简单。如今互联网十分发达&#xff0c;各种学习资料&#xff0c;视频&#xff0c;文档都可以在网上找到。可以说如今是一个全民自学的时代&#xff0c;你要你有决心和时间&#xff0c;足不出户便能…

学java难不难?java应该怎么学?

学java到底难不难&#xff0c;对于这个问题&#xff0c;我们专门做过一个调查&#xff0c;超过1000名已经在职的java从业者&#xff0c;其中有80%的程序员觉得学java不难&#xff0c;20%的程序员觉得前期有点难&#xff0c;其中对于50%自学的新手认为java很难学&#xff0c;遇到…

Java学起来难吗?没基础能学懂吗?

这个问题是许多想要学习软件开发的小伙伴们比较纠结的&#xff0c;怕自己选错学不好&#xff0c;浪费钱&#xff0c;浪费精力。首先我们要知道Java学起来并不难&#xff0c;但学起来也不会轻松。Java是一门语言&#xff0c;和我们的汉语、英语是一样的&#xff0c;只是说编程语…

学JAVA难不难?

经常有童鞋问小编&#xff0c;零基础可以学JAVA吗&#xff1f;JAVA难吗&#xff1f; 答案是&#xff1a;可以&#xff01; 今天就给想学习JAVA的朋友提些学习建议&#xff0c;以及Java的学习路线&#xff0c;希望帮助大家少走弯路。 学Java必须具备的几个条件&#xff1a; 01学…

斐讯R1音箱安装悟空遥控,并实现DLNA推送

2019独角兽企业重金招聘Python工程师标准>>> 再粘贴一遍太烦了&#xff0c;直接贴我有道云笔记的链接吧&#xff1a; 文章链接 转载于:https://my.oschina.net/u/2396236/blog/2966034

斐讯盒子T1_【YYF固件】无语音实用版刷机固件及教程分享

斐讯盒子T1_【YYF固件】无语音实用版刷机固件及教程分享 固件特点&#xff1a; 1、安卓启动界面和安卓开机动画&#xff1b; 2、默认实用桌面&#xff0c;可自行安装其它第三方桌面&#xff1b; 3、关闭、蓝牙生成日志文件&#xff0c;减少空间占用&#xff1b; 4、比之前版…