CodeWars刷题记录20180911-Python

1、Simple Pig Latin

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 !

 解答:

def pig_it(text):
    strList = text.split()
    for i in xrange(len(strList)):
        if strList[i].isalpha():
            strList[i] = strList[i][1:len(strList[i])] + strList[i][0] + 'ay' 
    return ' '.join(strList)

2、 Calculate Fibonacci return count of digit occurrences

A farmer raises rabbits. Each rabbit gives birth to one rabbit when it turns 2 months old, and then to one rabbit each month. Rabbits never die, and we ignore hares. How many rabbits will the farmer have in the n-th month, if he starts with one newborn rabbit?

Fibonacci numbers are generated by setting F0=0, F1=1, and then using the formula

Fn = Fn-1 + Fn-2

Your task is to efficiently calculate the nth element in the Fibonacci sequence and then count the occurrence of each digit in the number returning a list of integer pairs sorted in descending order.

10 ≤ N ≤ 100000

f(10)=55 returns

a = [(2, 5)]

two occurances of the digit 5

f(10)=55 
      ^^
      ||

f(10000) returns 

a = [(254, 3),
     (228, 2),
     (217, 6),
     (217, 0),
     (202, 5),
     (199, 1),
     (198, 7),
     (197, 8),
     (194, 4),
     (184, 9)]

If two integers have the same count sort them in descending order.

Your algorithm must be efficient.

解答:

def calc(n):
    if n == 0:
        return (0, 1)
    elif n == 1:
        return (1, 1)
    else:
        a, b = calc(n // 2)
        p = a * (2 * b - a)
        q = b * b + a * a
        return (p, q) if n % 2 == 0 else (q, p + q)

# 一种计算斐波那契数列第n个值的高效算法,可计算超大数
def fib(n):
    if n >= 0:
        return calc(n)[0]
    else:
        return -calc(-n)[0] if n % 2 ==0 else calc(-n)[0]

# 排序规则
def takeFirst(elem):
    return elem[0]


def fib_digits(n):
    res = []
    for i in xrange(10):
        if str(fib(n)).count(str(i)) > 0:
            res.append((str(fib(n)).count(str(i)), i)) 
    res.sort(key = takeFirst, reverse = True)
    if len(res) >= 2:
        for i in xrange(len(res)-1):
            if res[i][0] == res[i+1][0]:
                res[i],res[i+1] = res[i+1],res[i]
    return res

3、Encrypt this!

You want to create secret messages which can be deciphered by the Decipher this! kata. Here are the conditions:

  1. Your message is a string containing space separated words.
  2. You need to encrypt each word in the message using the following rules:
    • The first letter needs to be converted to its ASCII code.
    • The second letter needs to be switched with the last letter
  3. Keepin' it simple: There are no special characters in input.

Examples:

encrypt_this("Hello") == "72olle"
encrypt_this("good") == "103doo"
encrypt_this("hello world") == "104olle 119drlo"

解答:

def encrypt_this(text):
    if len(text) == 0:
        return text
    strList = text.split()
    for i,s in enumerate(strList):
        if len(s) == 1:
            strList[i] = str(ord(s))
        elif len(s) == 2:
            strList[i] = str(ord(s[0]))+s[1]
        else:
            strList[i] = str(ord(s[0])) + s[len(s)-1] + s[2:len(s)-1] + s[1]
    return ' '.join(strList)

4、Sudoku Solution Validator

Sudoku Background

Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9. 
(More info at: http://en.wikipedia.org/wiki/Sudoku)

Sudoku Solution Validator

Write a function validSolution/ValidateSolution/valid_solution() that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions.

The board is always 9 cells by 9 cells, and every cell only contains integers from 0 to 9.

Examples

validSolution([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 5, 3, 4, 8],
  [1, 9, 8, 3, 4, 2, 5, 6, 7],
  [8, 5, 9, 7, 6, 1, 4, 2, 3],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 6, 1, 5, 3, 7, 2, 8, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 4, 5, 2, 8, 6, 1, 7, 9]
]); // => true
validSolution([
  [5, 3, 4, 6, 7, 8, 9, 1, 2], 
  [6, 7, 2, 1, 9, 0, 3, 4, 8],
  [1, 0, 0, 3, 4, 2, 5, 6, 0],
  [8, 5, 9, 7, 6, 1, 0, 2, 0],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 0, 1, 5, 3, 7, 2, 1, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 0, 0, 4, 8, 1, 1, 7, 9]
]); // => false

解答:

# 验证是否包含1-9
def valid(l):
    for i in xrange(1,10):
        if l.count(i) != 1:
            return False
    return True


def validSolution(board):
    # 验证行
    for i in xrange(9):
        if not valid(board[i]):
            return False
    # 验证列
    for i in xrange(9):
        column = []
        for j in xrange(9):
            column.append(board[j][i])
        if not valid(column):
            return False
    # 验证3*3阵列
    for i in xrange(0,9,3):
        for j in xrange(0,9,3):
            block = []
            block.extend(board[j][i:i+3])
            block.extend(board[j+1][i:i+3])
            block.extend(board[j+2][i:i+3])
            if not valid(block):
                return False
    return True

 5、Simple directions reversal

In this Kata, you will be given directions and your task will be to find your way back.

solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']
solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) =  ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']

解答:

def reverseDirection(str):
    if str == 'Left':
        return 'Right'
    if str == 'Right':
        return 'Left'

def solve(arr):
    if len(arr) == 1:
        return arr
    res = []
    res.append('Begin' + ' ' + ' '.join(arr[len(arr)-1].split()[1:]))
    for i in xrange(len(arr)-1,0,-1):
        res.append(reverseDirection(arr[i].split()[0]) + ' ' + ' '.join(arr[i-1].split()[1:]))
    return res

 6、Range Extraction

A format for expressing an ordered list of integers is to use a comma separated list of either

  • individual integers
  • or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")

Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

Example:

solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"

解答:

def solution(args):
    res = [[args[0]]]
    for i in range(1, len(args)):
        if abs(args[i] - args[i-1]) == 1:
            res[len(res)-1].append(args[i])
        else:
            res.append([args[i]])
    for i in range(len(res)):
        if len(res[i]) >= 3:
            res[i] = str(res[i][0]) + '-' + str(res[i][len(res[i])-1])
        elif len(res[i]) == 1:
            res[i] = str(res[i][0])
        elif len(res[i]) == 2:
            res[i] = str(res[i][0]) + ',' +str(res[i][1])

    return ','.join(res)

 7、Positions Average

Suppose you have 4 numbers: '0', '9', '6', '4' and 3 strings composed with them:

s1 = "6900690040"
s2 = "4690606946"
s3 = "9990494604"

Compare s1 and s2 to see how many positions they have in common: 0 at index 3, 6 at index 4, 4 at index 8 ie 3 common positions out of ten.

Compare s1 and s3 to see how many positions they have in common: 9 at index 1, 0 at index 3, 9 at index 5 ie 3 common positions out of ten.

Compare s2 and s3. We find 2 common positions out of ten.

So for the 3 strings we have 8 common positions out of 30 ie 0.2666... or 26.666...%

Given a set of n strings our function pos_average will calculate the average percentage of positions that are the same between the (n * (n-1)) / 2 sets of strings taken amongst the given 'n' strings.

解答:

def pos_average(s):
    strList = s.split(', ')
    count = 0
    if len(strList) == 0 or len(strList) == 1:
        return 0
    for i in range(len(strList)-1):
        for j in range(i+1, len(strList)):
            for k in range(len(strList[i])):
                if strList[i][k] == strList[j][k]:
                    count += 1
    return count/len(strList)/(len(strList)-1)*2/len(strList[0])*100

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洒满阳光的午后

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值