今日codewars

题目:
The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.
就是给我们三个数字让我们以十六进制组合成字符串输出

我的代码:

def rgb(r, g, b):
    input_num = [r, g, b]
    output = []
    for i in input_num:
        if i < 16:
            if i < 0:
                i = 0
            output.append(str(hex(i)).replace('x', ''))
        elif i > 255:
            i = 255
            output.append(str(hex(i)).replace('0x', ''))
        else:
            output.append(str(hex(i)).replace('0x', ''))
    return ''.join(output).upper()

嗯。。挺复杂的

高亮代码:

def limit(num):
	if num < 0:
		return 0
	elif num > 255:
		return 255
	return num


def rgb(r,g,b):
	return '{:02X}{:02X}{:02X}'.format(limit(r),limit(g),limit(b))

format():格式化函数,按照前面指定的格式输出 02X:十六进制输出,如果小于2位则用0补齐,大于两位则原样输出

题目:
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

就是要求我们顺时针遍历一个n×n的数组

这是我第一个自己做出来的4级难度的题,开心

分析:
首先判断这个数组是不是空的,如果空的就直接返回一个空列表即可
接下来的思路看程序即可(我估计我想的又是很复杂,别人肯定又是几行代码搞定)

我的代码:

def snail(array):
    if len(array[0]) == 0:
        return []
    else:
        output = []
        while len(array) != 1:
            l = len(array[0])
            output.extend(array[0])
            array.remove(array[0])
            for i in range(l-1):
                output.append(array[i][l-1])
                array[i].pop()
    #翻转 先整体反转 再单个列表反转
            array.reverse()
            for list1 in array:
                list1.reverse()
    #终止条件 是len(array) = 1
        output.append(array[0][0])
        return output

高亮代码:

def snail(array):
	a = []
	while array:
		a.extend(list(array.pop(0)))
		array = zip(*array)
		array.reverse()
	return a

果然你大爷还是你大爷…

zip:将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。就是把对应位置的元素组成一个个列表
列表前加*:将列表解开成两个独立的参数
同时要再次记住:list1.reverse()不返回任何值,但是会给列表排序

题目:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
要求:给定我们一个字符串,输出时第一个字符必须是#,同时,如果输入或结果为空要返回False,输出字符串长度大于0时也要返回False

测试案例:

Test.describe("Basic tests")
Test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False')
Test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.')
Test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.')
Test.assert_equals(generate_hashtag('Codewars      '), '#Codewars', 'Should handle trailing whitespace.')
Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.')
Test.assert_equals(generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.')
Test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.')
Test.assert_equals(generate_hashtag('codewars  is  nice'), '#CodewarsIsNice', 'Should deal with unnecessary middle spaces.')
Test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')

我的代码:

def generate_hashtag(s):
    s = s.strip()
    if len(s) == 0:
        return False
    else:
        new_list = s.split()
        output = []
        for string in new_list:
            if string != '':
                string = string.capitalize()
                output.append(string)
        output.insert(0,'#')
        out_str = ''.join(output)
        if len(out_str) > 140 or len(out_str) == 0:
            return False
        else:
            return out_str
                

高亮:

def generate_hasntag(s):
	output = '#'
	for word in s.split():
		output += word.capitalize()
	
	return False if (len(s) == 0 or len(output) > 140 ) else output

注意:split()默认按所有空格分隔,包括空格换行制表符,所有的空都被消掉了

题目:
We want to create a function that will add numbers together when called in succession.
add(1)(2); return3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10

别人的代码:

class add(int):
    def __call__(self,n):
        return add(self+n)
        

没搞懂…网上的也没看懂
可能是第一个数作为self,第二个数作为n,这俩数相加又作为self,第三个数作为n,如此循环

题目:
Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42.
These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764.
The sum of the squared divisors is 2500 which is 50 * 50, a square!
Given two integers m, n (1 <= m <= n) we want to find all integers
between m and n whose sum of squared divisors is itself a square.
42 is such a number.
The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements,
first the number whose squared divisors is a square and then the sum
of the squared divisors.
就是给我们两个数字,让我们输出这两个数字中 因子的平方和是一个完全平方数的数字

我的代码:

def list_squared(m, n):
    output = []
    for i in range(m,n+1):
        num = 0
        for j in range(1,i //2 +1):
            if i % j == 0:
                num += j**2
        num += i**2
        if num ** 0.5 == int(num ** 0.5):
            output.append([[i,num]])
    return output

虽然对但是超时了= =

高亮:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值