【codewars】Don't Drink the Water

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lluozh2015/article/details/78905756

instruction

Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.

这里写图片描述

The glass representation may be larger or smaller. If a liquid doesn’t fill a row, it floats to the top and to the left

Examples:
Test.describe(“Sorting array by liquid density.”)
Test.it(“Should be able to sort 3 liquids”)
Test.assert_equals(separate_liquids([[‘H’, ‘H’, ‘W’, ‘O’],[‘W’,’W’,’O’,’W’],[‘H’,’H’,’O’,’O’]]), [[‘O’, ‘O’, ‘O’, ‘O’],[‘W’,’W’,’W’,’W’],[‘H’,’H’,’H’,’H’]], “”)
Test.it(“Should be able to handle 4 liquids”)
Test.assert_equals(separate_liquids([[‘A’,’A’,’O’,’H’],[‘A’, ‘H’, ‘W’, ‘O’],[‘W’,’W’,’A’,’W’],[‘H’,’H’,’O’,’O’]]), [[‘O’,’O’,’O’,’O’],[‘A’, ‘A’, ‘A’, ‘A’],[‘W’,’W’,’W’,’W’],[‘H’,’H’,’H’,’H’]], “”)
Test.it(“Should be able to handle one row”)
Test.assert_equals(separate_liquids([[‘A’,’H’,’W’,’O’]]),[[‘O’,’A’,’W’,’H’]],”“)
Test.it(“Should be able to handle one column”)
Test.assert_equals(separate_liquids([[‘A’],[‘H’],[‘W’],[‘O’]]),[[‘O’],[‘A’],[‘W’],[‘H’]],”“)
Test.it(“Should be able to handle empty array”)
Test.assert_equals(separate_liquids([]), [], “Empty array should be returned if given.”)

my solution

def separate_liquids(glass):
    #your code here
    if len(glass) == 0:
        return []
    else:
        x ={'H':1.36,'W':1.00,'A':0.87,'O':0.80}
        b = []
        for i in glass:
            for j in i:
                b.append(j)
        c = b
        for i in range(len(c)-1):
            for j in range(len(c)-i-1):
                if x[c[j]] > x[c[j+1]]:
                    temp = c[j]
                    c[j] = c[j+1]
                    c[j+1] = temp
        r = []
        rr = []
        if len(glass) == 1:
            for i in c:
                rr.append(i)
            r.append(rr)
        else:
            kk = 0
            for i in range(len(glass)):
                for j in range(len(glass[0])):
                    rr.append(c[kk])
                    kk +=1
                r.append(rr)
                rr = []
        return r

best solution from others

def separate_liquids(glass):
    if not glass or not glass[0]:
        return glass
    cols = len(glass[0])
    flattened = reduce(lambda a, b: a + b, glass)
    flattened.sort(key=lambda v: "OAWH".index(v))
    return [flattened[i:i + cols] for i in xrange(0, len(flattened), cols)]

匿名函数

指一类无需定义标识符(函数名)的函数或子程序
当在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便

语法格式:lambda 参数:表达式
lambda语句中,开头先写关键字lambda,冒号前是参数,可以有多个,用逗号隔开;冒号右边的为表达式,需要注意的是只能有一个表达式

在内置函数 max() 求最大值,min()求最小值, map() 映射, reduce 合并, filter() 过滤 中会用到

l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(l)

>>> [1, 4, 9, 16, 25, 36, 49, 64, 81]

用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数

f = lambda x: x * x
r = f(5)
print(r)

>>> 25

也可以把匿名函数作为返回值返回

def build(x, y):
    return lambda: x * x + y * y

filter方法

用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中

filter(function, iterable)

function - 判断函数
iterable - 可迭代对象

# 过滤出1~100中平方根是整数的数
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

newlist = list(filter(is_sqr, range(1, 101)))
print(newlist)

>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
def f1(x):
    if x > 20:
        return True
    else:
        return False

l1 = [1, 2, 3, 42, 67, 16]
xx = [x for x in filter(f1, l1)]
print(xx)

>>> [42, 67]

关于filter()方法, python3和python2有一点不同

python2中返回的是过滤后的列表, 而python3中返回到是一个filter类

filter类实现了iternext方法, 可以看成是一个迭代器, 有惰性运算的特性, 相对python2提升了性能, 可以节约内存

map方法

根据提供的函数对指定序列做映射
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

map(function, iterable, …)

function - 函数,有两个参数
iterable - 一个或多个序列

    def square(x):  # 计算平方数
        return x ** 2

    x = list(map(square, [1, 2, 3, 4, 5]))  # 计算列表和:1+2+3+4+5
    print(x)

>>> [1, 4, 9, 16, 25]
    y = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))  # 使用 lambda 匿名函数
    print(y)

>>> [1, 4, 9, 16, 25]
    # 提供了两个列表,对相同位置的列表数据进行相加
    z = list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
    print(z)

>>> [3, 7, 11, 15, 19]

reduce方法

对参数序列中元素进行累积
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果

reduce(function, iterable[, initializer])

function - 函数,有两个参数
iterable - 可迭代对象
initializer - 可选,初始参数

    def add(x, y):  # 两数相加
        return x + y

    a = reduce(add, [1, 2, 3, 4, 5])  # 计算列表和:1+2+3+4+5
    print(a)

>>> 15
    b = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
    print(b)

>>> 15
    b = reduce(lambda x, y: x + y, ['W','W','O','W'])  # 使用 lambda 匿名函数
    print(b)

>>> WWOW
    b = reduce(lambda x, y: x + y, [['H', 'H', 'W', 'O'],['W','W','O','W'],['H','H','O','O']]) 
    print(b)

>>> ['H', 'H', 'W', 'O', 'W', 'W', 'O', 'W', 'H', 'H', 'O', 'O']

在Python 3中,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里 用的话要 先引入:

from functools import reduce 

sort方法

用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数

list.sort([func])

func – 可选参数, 如果指定了该参数会使用该参数的方法进行排序

返回值 - 该方法没有返回值,但是会对列表的对象进行排序

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.sort()
print ("列表排序后 : ", list1)

>>> 列表排序后 :  ['Baidu', 'Google', 'Runoob', 'Taobao']
nums = [3, 2, 8, 0, 1]
nums.sort(reverse = True)  # 降序排序
print(nums)

nums.sort(reverse = False)  # 升序排序
print(nums)

>>> [8, 3, 2, 1, 0]
>>> [0, 1, 2, 3, 8]
list1=[7, -8, 5, 4, 0, -2, -5]

# 要求1.正数在前负数在后 2.整数从小到大 3.负数从大到小
list1.sort(key=lambda x:(x<0,abs(x)))
print(list1)

>>> [0, 4, 5, 7, -2, -5, -8]
alist = [('2', '3', '10'), ('1', '2', '3'), ('5', '6', '7'), ('2', '5', '10'), ('2', '4', '10')]

# 多级排序,先按照第3个元素排序,然后按照第2个元素排序
alist.sort(key = lambda x:(int(x[2]), int(x[1])), reverse = False)
print(alist)

>>> [('1', '2', '3'), ('5', '6', '7'), ('2', '3', '10'), ('2', '4', '10'), ('2', '5', '10')]
flattened = ['H', 'H', 'W', 'O', 'W', 'W', 'O', 'W', 'H', 'H', 'O', 'O']

flattened.sort(key=lambda v: "OAWH".index(v))
print(flattened)

>>> ['O', 'O', 'O', 'O', 'W', 'W', 'W', 'W', 'H', 'H', 'H', 'H']

猜你喜欢

转载自blog.csdn.net/lluozh2015/article/details/78905756