Codewars算法题(6)

第20题(字母排序问题)

问题:

Move the first letter of each word to the end of it, then add 'ay' to the end of the word.

pig_it('Pig latin is cool') # igPay atinlay siay oolcay
问题陈述:其实就是将字符串中的每一个单词的首字母移到最后,再在每个单词最后加上ay

评分较高代码:

(1)

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

首先要明确的是:对字符串进行切割(以一个单词为单位)

(2)

def pig_it(text):
    res = []

    for i in text.split():
        if i.isalpha():
            res.append(i[1:] + i[0] + 'ay')
        else:
            res.append(i)

    return ' '.join(res)
(2)是(1)的展开写

第21题:(WeIrD StRiNg CaSe)

Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.

The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').

Examples:

to_weird_case('String'); # => returns 'StRiNg'
to_weird_case('Weird string case') # => returns 'WeIrD StRiNg CaSe'
问题陈述:将字符串中每一个单词的奇数位大写,偶数位小写

自己代码:

def to_weird_case(string):
    new=""
    l=string.split()
    for i in l:
        for j in range(0,len(i)):
            if(j==0 and l.index(i)!=0):
                new=new+" "+i[j].upper() #在非首单词前面加空格,并将单词首字母大写
            elif(j%2==0):
                new+=i[j].upper()#将单词奇数位的字母大写
            else:
                new+=i[j]
    return  new
评价较高代码:
(1)
def to_weird_case_word(string):
    return "".join(c.upper() if i % 2 == 0 else c for i, c in enumerate(string.lower()))

def to_weird_case(string):
    return " ".join(to_weird_case_word(str) for str in string.split())
to_weird_case_word()函数实现的功能是将每一个单词中的奇数位字母大写偶数位字母小写
(2)
def to_weird_case(string):
    recase = lambda s: "".join([c.upper() if i % 2 == 0 else c.lower() for i, c in enumerate(s)])
    return " ".join([recase(word) for word in string.split(" ")])
再看仁兄(2)写的,其实和仁兄(1)差不多,不过使用了lambda,lambda是一个表达式,比def要简单起到函数速
写的作用。
第22题:(Good VS Evil)
问题:
 
 

Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain 'worth' when battling against others. On the side of good we have the following races, with their associated worth:

  • Hobbits - 1
  • Men - 2
  • Elves - 3
  • Dwarves - 3
  • Eagles - 4
  • Wizards - 10

On the side of evil we have:

  • Orcs - 1
  • Men - 2
  • Wargs - 2
  • Goblins - 2
  • Uruk Hai - 3
  • Trolls - 5
  • Wizards - 10

Although weather, location, supplies and valor play a part in any battle, if you add up the worth of the side of good and compare it with the worth of the side of evil, the side with the larger worth will tend to win.

Thus, given the count of each of the races on the side of good, followed by the count of each of the races on the side of evil, determine which side wins.

Input:

The function will be given two parameters. Each parameter will be a string separated by a single space. Each string will contain the count of each race on the side of good and evil.

The first parameter will contain the count of each race on the side of good in the following order:

  • Hobbits, Men, Elves, Dwarves, Eagles, Wizards.

The second parameter will contain the count of each race on the side of evil in the following order:

  • Orcs, Men, Wargs, Goblins, Uruk Hai, Trolls, Wizards.

All values are non-negative integers. The resulting sum of the worth for each side will not exceed the limit of a 32-bit integer.

Output:

Return ""Battle Result: Good triumphs over Evil" if good wins, "Battle Result: Evil eradicates all trace of Good" if evil wins, or "Battle Result: No victor on this battle field" if it ends in a tie.

ALGORITHMS
问题描述:看着问题有点唬人,其实中心思想很简单,就是在给出得分以及对应参数情况下,判断是Good获胜还是
                 Evil获胜。
自己代码:
def goodVsEvil(good, evil):
    scoreg = [1, 2, 3, 3, 4, 10]
    scoree = [1, 2, 2, 2, 3, 5, 10]
    lg = good.split()
    le = evil.split()
    sumg = sume = 0
    for i in range(0, len(scoreg)):
        sumg += scoreg[i] * int(lg[i])
    for j in range(0, len(scoree)):
        sume += scoree[j] * int(le[j])
    if sumg > sume:
        return 'Battle Result: Good triumphs over Evil'
    elif sumg < sume:
        return 'Battle Result: Evil eradicates all trace of Good'
    else:
        return 'Battle Result: No victor on this battle field'
评分较高代码:
(1)
def goodVsEvil(good, evil):
    points_good = [1, 2, 3, 3, 4, 10]
    points_evil = [1, 2, 2, 2, 3, 5, 10]

    good = sum([int(x) * y for x, y in zip(good.split(), points_good)])
    evil = sum([int(x) * y for x, y in zip(evil.split(), points_evil)])

    result = 'Battle Result: '

    if good < evil:
        return result + 'Evil eradicates all trace of Good'
    elif good > evil:
        return result + 'Good triumphs over Evil'
    else:
        return result + 'No victor on this battle field'
zip()函数是python的内置函数,接受可迭代的参数作为对象,将对象中一个个元素打包成元组,返回元组组成的列表
如果传入的参数不等,则返回列表的长度和参数中最短的相同。
例如:a=[1,2,3]b=[4,5,6]则zip(a,b的值为[(1,4),(2,5),(3,6)]
(2)
GOOD_WIN = "Battle Result: Good triumphs over Evil"
EVIL_WIN = "Battle Result: Evil eradicates all trace of Good"
DRAW = "Battle Result: No victor on this battle field"

GOOD = [1, 2, 3, 3, 4, 10]
EVIL = [1, 2, 2, 2, 3, 5, 10]

def goodVsEvil(good, evil):
    g = sum(map(lambda x, y: x * y, GOOD, [int(x) for x in good.split(' ')]))
    e = sum(map(lambda x, y: x * y, EVIL, [int(x) for x in evil.split(' ')]))
    return GOOD_WIN if g > e else EVIL_WIN if e > g else DRAW
第23题:(Count the smiley faces)

Description:
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.

Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :] 

自己的代码:
def count_smileys(arr):
    count = 0
    valid = [':)', ':D', ';)', ';D', ':~)', ':~D', ':-)', ':-D', ';~)', ';~D', ';-)', ';-D']
    for i in range(0, len(arr)):
        if arr[i] in valid:
            count += 1
    return count

感觉自己的方法low爆了~~~
评分较高代码:
(1)
from re import findall
def count_smileys(arr):
    return len(list(findall(r"[:;][-~]?[)D]", " ".join(arr))))
运用了正则表达式,嗯,显得简单了许多~~
(2)
def count_smileys(arr):
    eyes = [":", ";"]
    noses = ["", "-", "~"]
    mouths = [")", "D"]
    count = 0
    for eye in eyes:
        for nose in noses:
            for mouth in mouths:
                face = eye + nose + mouth
                count += arr.count(face)
    return count
(2)中的3个for循环就是找出了所有合理的集合
(3)
def count_smileys(arr):
    import re
    smiley = re.compile(r"[:;][-~]?[)D]")
    return sum(bool(re.match(smiley, el)) for el in arr)
用了bool和match函数!!!



201707261756持续更新中~~~





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值