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 , 单独的一行记录加锁 表级,直接锁定整张表,在你锁定期间,其它进程无法对该表进行写 ...
随机推荐
- CodeForces - 691E Xor-sequences 【矩阵快速幂】
题目链接 http://codeforces.com/problemset/problem/691/E 题意 给出一个长度为n的序列,从其中选择k个数 组成长度为k的序列,因为(k 有可能 > ...
- InnoDB存储引擎内存缓冲池管理技术——LRU List、Free List、Flush List
InnoDB是事务安全的MySQL存储引擎,野山谷OLTP应用中核心表的首选存储引擎.他是基于表的存储引擎,而不是基于数据库的.其特点是行锁设计.支持MVCC.支持外键.提供一致性非锁定读,同时被设计 ...
- linux中安装php
1.在php官网找到对应的php版本下载下来(php官网地址http://php.net) 2.把下载下来的安装包放入到linux系统中 3.解压php压缩包,通过tar -zxvf + 下载下来 ...
- Qt事件机制---信号通过事件实现,事件可以过滤,事件更底层,事件是基础,信号是扩展。
转:http://www.cnblogs.com/findumars/p/8001484.html Qt事件机制(是动作发生后,一种通知对象的消息,是被动与主动的总和.先处理自己队列中的消息,然后再处 ...
- 【Flask】sqlalchemy 排序
### 排序:1. order_by:可以指定根据这个表中的某个字段进行排序,如果在前面加了一个-,代表的是降序排序.2. 在模型定义的时候指定默认排序:有些时候,不想每次在查询的时候都指定排序的方式 ...
- libstdc和glibc的一些共享库问题
1./usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found错误的解决 原因是没有GLIBCXX_3.4.15版本,或是更高的版本输入命令 ...
- QT中文乱码处理
在程序中直接使用中文,需要在程序中加入以下代码: #include <QTextCodec> int main(int argc, char **argv) { QApplication ...
- Java properties配置文件工具类
/* * Copyright (c) 2017. Panteng.Co.Ltd All rights reserved */ import org.apache.log4j.Logger; impor ...
- 正则表达式java,javaScript应用
dfa nfa 混合:捕获:断言: 正则引擎大体上可分为不同的两类:DFA和NFA,而NFA又基本上可以分为传统型NFA和POSIX NFA. 1.正则语法 捕获组: 没用()的字符都是一个一个 ...
- session共享个人小结
一.需求问题: 如果你的网站是存放在一个机器上,那么是不存在这个问题的,因为会话数据就在这台机器,但是如果你使用了负载均衡把请求分发到不同的机器呢? 这个时候会话id在客户端是没有问题的, 但是如果用 ...