codewar代码练习2——7级晋升6级
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 = 1
a = [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+=1
else:
ans = 'NO'
return ans
else:
if 25 and 50 in a:
a.remove(25)
a.remove(50)
a.append(100)
i+=1
elif a.count(25) >= 3:
a.remove(25)
a.remove(25)
a.remove(25)
a.append(100)
i+=1
else:
ans = 'NO'
return ans
except ValueError:
ans = 'NO'
return ans
ans = '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] += 1
change = paid-25.0
for bill in (50,25):
while (bill <= change and till[bill] > 0):
till[bill] -= 1
change -= bill
if change != 0:
return 'NO'
return 'YES'
and
def tickets(a):
n25 = n50 = n100 = 0
for e in a:
if e==25 : n25+=1
elif e==50 : n25-=1; n50+=1
elif e==100 and n50>0 : n25-=1; n50-=1
elif e==100 and n50==0: n25-=3
if 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:
pass
c = ' '.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 = None
for i in iterable:
if i != pre:
list.append(i)
pre = i
return list
Best solution from others:
def unique_in_order(iterable):
result = []
prev = None
for char in iterable[0:]:
if char != prev:
result.append(char)
prev = char
return 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.
codewar代码练习2——7级晋升6级的更多相关文章
- codewar代码练习1——8级晋升7级
最近发现一个不错的代码练习网站codewar(http://www.codewars.com).注册了一个账号,花了几天的茶余饭后时间做题,把等级从8级升到了7级.本文的目的主要介绍使用感受及相应题目 ...
- 行为级和RTL级的区别(转)
转自:http://hi.baidu.com/renmeman/item/5bd83496e3fc816bf14215db RTL级,registertransferlevel,指的是用寄存器这一级别 ...
- CSS 各类 块级元素 行级元素 水平 垂直 居中问题
元素的居中问题是每个初学者碰到的第一个大问题,在此我总结了下各种块级 行级 水平 垂直 的居中方法,并尽量给出代码实例. 首先请先明白块级元素和行级元素的区别 行级元素 一块级元素 1 水平居中: ( ...
- 学习总结:CSS(二)块级与行级元素特性、盒模型、层模型、BUG与BFC、浮动模型
一.元素的块级与行级特性 在CSS属性display控制元素是否及如何显示的特性,常用的值有none.inline.block.inline-block,在CSS3中还有一些新的特性状态,在这里不做讨 ...
- 51nod图论题解(4级,5级算法题)
51nod图论题解(4级,5级算法题) 1805 小树 基准时间限制:1.5 秒 空间限制:131072 KB 分值: 80 难度:5级算法题 她发现她的树的点上都有一个标号(从1到n),这些树都在空 ...
- js input复选框选中父级同时子级也选中
js实现复选框选中父级元素子级元素也选中,没有子级元素选中父级也不选中的效果 HTML <tr> <td> <label> <input name=" ...
- 操作系统学习笔记5 | 用户级线程 && 内核级线程
在上一部分中,我们了解到操作系统实现多进程图像需要组织.切换.考虑进程之间的影响,组织就是用PCB的队列实现,用到了一些简单的数据结构知识.而本部分重点就是进程之间的切换. 参考资料: 课程:哈工大操 ...
- [数据库事务与锁]详解五: MySQL中的行级锁,表级锁,页级锁
注明: 本文转载自http://www.hollischuang.com/archives/914 在计算机科学中,锁是在执行多线程时用于强行限制资源访问的同步机制,即用于在并发控制中保证对互斥要求的 ...
- MySQL行级锁,表级锁,页级锁详解
页级:引擎 BDB. 表级:引擎 MyISAM , 理解为锁住整个表,可以同时读,写不行 行级:引擎 INNODB , 单独的一行记录加锁 表级,直接锁定整张表,在你锁定期间,其它进程无法对该表进行写 ...
随机推荐
- MyEclipse工具栏的隐藏与显示及自定义
Myeclipse的工具栏 1.隐藏 工具栏---->右键---->hide toolbar 2.显示 window ----> show toolbar 3.自定义 ...
- iOS copy 和 mutableCopy 学习
(参考 iOS 52个技巧学习心得笔记 第二章 对象 , 消息, 运行期)的对象部分 关于Copy 有个经典问题”大部分的时候NSString的属性都是copy,那copy与strong的情况下到底 ...
- css的继承性理解
1) 所有的text 相关属性都被继承: 如 font-family font-size; font-style;font-weight;font;font-variant;letter-spacin ...
- awk的内置函数
常见awk内置数值函数
- HttpUtils工具类
HttpUtils工具类 package net.hs.itn.teng.common.util; import java.io.IOException; import java.io.Unsuppo ...
- OWASP十大攻击类型详解
随着WEB应用技术的不断进步与发展,WEB应用程序承载了越来越多的业务,而随之而来的也是WEB应用所面临的越来越复杂的安全问题.而WEB日志作为WEB安全中的一个重要组成部分,不但可在事后起到追踪和溯 ...
- OC_内存管理
引言: 1.OC中的对象都是分配在堆中的 声明对象的格式: Person *person = [Person new ...
- dll和lib
lib:里面包含了很多源代码,工程会将这些源代码加入自己的项目中编译: dll:动态编译库,允许可执行文件在运行中加载里面的资源. 使用lib需注意两个文件:(1).h头文件,包含lib中说明输出的类 ...
- Java Comparator方法 和 Comparable接口
默认的排序方法: 让类继承Comparable接口,重写compareTo方法. 示例代码: package com.imooc.collection; import java.util.HashSe ...
- JQuery 操作 iframe
JQuery访问iframe内的元素 $("iframe#Main", top.document).contents().find("#id"); JQuery ...