Codewars-python 20190117

本文探讨了四个有趣的算法挑战,包括字符串操作和排序算法。通过具体的代码示例,展示了如何实现字符串的倒序排列、根据数字排序句子、生成累积字符串以及寻找下一个完全平方数。这些挑战不仅考验了算法思维,还提供了实际的编程解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Descending Orders
input:324189
output:984321
知识点:’’.join
[::-1]:list倒序排列

def Descending_Order(num):
    #Bust a move right here
    num = list(str(num))
    return int(''.join(sorted(num)[::-1]))

2.Your Order,please
input:“is2 Thi1s T4est 3a”
output:“Thi1s is2 3a T4est”
方法一:

def order(sentence):
  # code here'
    sentence = sentence.split()
    Arr = ['']*len(sentence)
    for s in sentence:
        for c in s:
            if c.isdigit(): #只想到了这一步
                Arr[ord(c)-ord('1')] = s
                break
    return ' '.join(Arr)

方法二:

def order(words):
	return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))

3.Mumbling
input:“abcd”
output:“A-Bb-Ccc-Dddd”
自己方法:

def accum(s):
	s = list(s)
	result = []
	reslut1 = []
	for i in range(len(s)):
    	result.append((i+1)*s[i])
	for j in result:
   		j = j.capitalize()
    	result1.append(j)
	return str('-'.join(result1))

大神做法:

def accum(s):
    return '-'.join(c.upper()+c.lower()*i for i, c in enumerate(s))

4.Find the next perfect square!

import math
def find_next_square(sq):
    # Return the next square if sq is a square, -1 otherwise
    a = math.sqrt(sq)  
    if a - int(a) > 0:#判断是否为int类型
        return -1
    else:
        return int(pow((a+1),2))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值