codewar 代码练习2——7级晋升6级

article/2025/11/11 15:24:38

7级晋升到6级的过程中以做6级题以及以前未完成的题目为主,一般选择算法题或者基础题。相比之前从8级升级7级(参见此博客:http://blog.csdn.net/m0_37324740/article/details/78408249)的难度有所提前,并且一些题目结合了一些简单的场景,也很有意思。

No.8
Topic:Vasya - Clerk
Instruction:

The new “Avengers” movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. An “Avengers” ticket costs 25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

Return YES, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return NO.

Examples:
这里写图片描述

My solution:

def tickets(people):if people[0] != 25:ans = 'NO'else:i = 1a = [25]while i < len(people):try:if people[i] == 25:a.append(25)i+=1                elif people[i] == 50:if 25 in a:a.remove(25)a.append(50)i+=1else:ans = 'NO'return anselse:if 25 and 50 in a:a.remove(25)a.remove(50)a.append(100)i+=1elif a.count(25) >= 3:a.remove(25)a.remove(25)a.remove(25)a.append(100)i+=1else:ans = 'NO'return ansexcept ValueError:ans = 'NO'return ansans = 'YES' return ans

Best solutions from others:

def tickets(people):till = {100.0:0, 50.0:0, 25.0:0}for paid in people:till[paid] += 1change = paid-25.0for bill in (50,25):while (bill <= change and till[bill] > 0):till[bill] -= 1change -= billif change != 0:return 'NO'return 'YES'

and

def tickets(a):n25 = n50 = n100 = 0for e in a:if   e==25            : n25+=1elif e==50            : n25-=1; n50+=1elif e==100 and n50>0 : n25-=1; n50-=1elif e==100 and n50==0: n25-=3if n25<0 or n50<0:return 'NO'return 'YES'

貌似我当时跑程序的时候出现了valueerror,但是一下子找不到原因,所以用了try语句。

No.9
Topic:Simple Pig Latin
Instruction:Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.
Examples:

pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldWay !

My solution:

def pig_it(text):a = text.split() b = list(map(lambda x: x[1:len(x)] + x[0] + 'ay', a))if len(b[len(b)-1]) == 3:b[len(b)-1] = a[len(a)-1]else:passc = ' '.join(b)return c

Best solution from others:

def pig_it(text):lst = text.split()return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])

No.10
Topic:Decode the Morse code
Instruction:
In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world.
The Morse code encodes every character as a sequence of “dots” and “dashes”. For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·.

NOTE: Extra spaces before or after the code have no meaning and should be ignored.

In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words.

Your task is to implement a function decodeMorse(morseCode), that would take the morse code as input and return a decoded human-readable string.

For example:

decodeMorse('.... . -.--   .--- ..- -.. .')
#should return "HEY JUDE"

The Morse code table is preloaded for you as a dictionary, feel free to use it. In CoffeeScript, C++, Go, JavaScript, PHP, Python, Ruby and TypeScript, the table can be accessed like this: MORSE_CODE[’.–’], in Java it is MorseCode.get(’.–’), in C# it is MorseCode.Get(’.–’), in Haskell the codes are in a Map String String and can be accessed like this: morseCodes ! “.–”, in Elixir it is morse_codes variable.

All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly because otherwise the engine would simply ignore the tests, resulting in a “valid” solution.

这道题我当时写的代码没有通过,很可惜没有保存下载,题目的思路不难,嵌套循环并用到替换。

Best solution from others:

def decodeMorse(morseCode):return ' '.join(''.join(MORSE_CODE[letter] for letter in word.split(' ')) for word in morseCode.strip().split('   '))

No.11
Topic:Who likes it?
Instruction:
You probably know the “like” system from Facebook and other pages. People can “like” blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

My solution:

def likes(names):if len(names) == 0:a = 'no one likes this'elif len(names) == 1:a = names[0] + ' ' + 'likes this'elif len(names) == 2:a = names[0] + ' ' +'and' + ' ' + names[1] + ' ' +'like this'elif len(names) == 3:a = names[0] + ',' + ' ' + names[1] + ' ' + 'and' +' ' + names[2] + ' ' + 'like this'else:a = names[0] + ',' + ' ' + names[1] + ' ' + 'and' +' ' + str((len(names)-2)) + ' ' + 'others like this' return a

Best solutions from others:

def likes(names):n = len(names)return {0: 'no one likes this',1: '{} likes this', 2: '{} and {} like this', 3: '{}, {} and {} like this', 4: '{}, {} and {others} others like this'}[min(4, n)].format(*names[:3], others=n-2)

and

def likes(names):if len(names) == 0:return "no one likes this"elif len(names) == 1:return "%s likes this" % names[0]elif len(names) == 2:return "%s and %s like this" % (names[0], names[1])elif len(names) == 3:return "%s, %s and %s like this" % (names[0], names[1], names[2])else:return "%s, %s and %s others like this" % (names[0], names[1], len(names)-2)

No.12
Topic:Unique In Order
Instruction:Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
Examples:

unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3])       == [1,2,3]

My solution:

def unique_in_order(iterable):list = []pre = Nonefor i in iterable:if i != pre:list.append(i)pre = ireturn list

Best solution from others:

def unique_in_order(iterable):result = []prev = Nonefor char in iterable[0:]:if char != prev:result.append(char)prev = charreturn result

No.13
Topic:Dubstep
Instruction:
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.

Let’s assume that a song consists of some number of words. To make the dubstep remix of this song, Polycarpus inserts a certain number of words “WUB” before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including “WUB”, in one string and plays the song at the club.

For example, a song with words “I AM X” can transform into a dubstep remix as “WUBWUBIWUBAMWUBWUBX” and cannot transform into “WUBWUBIAMWUBX”.

Recently, Jonny has heard Polycarpus’s new dubstep track, but since he isn’t into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.
Examples:
这里写图片描述
My solution:

def song_decoder(song):a = song.replace('WUB',' ').strip()b = ' '.join(a.split())return b

Best solution from others:

def song_decoder(song):return " ".join(song.replace('WUB', ' ').split())

总结:

  1. 如何写嵌套循环
  2. 格式化字符串的使用
  3. 多个空格合并单个空格
  4. strip函数删除字符串两端空格
  5. 用lambda和map对列表中每个元素做相同的操作
  6. Practice makes perfect.

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

相关文章

R数据分析,codewar的年终总结,和一周年总结

前阵子单位各个部门都在要求弄总结&#xff0c;想想自己这个公众号也写了快一年了&#xff0c;专门回去翻了翻&#xff0c;这个公众号发布的第一篇文章是在2021年的1月17日&#xff0c;我想2022年的1月17日我就把现在敲的文字推出来吧&#xff0c;也算是一个年终和周年总结。 …

CodeWar题目

打算把不同网站上面的题目分开整理&#xff0c;免得麻烦。Code War上面我还是刷了一堆6级及以下的题目的&#xff0c;不过价值不大&#xff0c;这种不太能够训练实际解决问题的能力&#xff0c;所以我已经很久没上过了&#xff0c;有时间了可能会重新上去刷题吧&#xff0c;到时…

Codewar 笔记

1. Weight for weight 题目&#xff1a; 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”…

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;只是说编程语…