入坑codewars第14天-Where is my parent!?(cry)

題目:

Mothers arranged dance party for children in school.On that party there are only mothers and their children.All are having great fun on dancing floor when suddenly all lights went out.Its dark night and no one can see eachother.But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want.

 

Legend:

-Uppercase letters stands for mothers,lowercase stand for their children. I.E "A" mothers children are "aaaa".
-Function input:String contain only letters,Uppercase letters are unique.

Task:

Place all people in alphabetical order where Mothers are followed by their children.I.E "aAbaBb" => "AaaBbb".

題意:

題意就是將所有的字母按照字母順序排列,並且大寫字母在前面;比如:"abBA"——>"AaBb";

代碼如下:

def find_children(dancing_brigade):
    list1=list(dancing_brigade)
    list1=sorted(list1, key=lambda c: (c.lower(),c.islower()))
    #sorted()根據每個字符的序數排序。大寫字母的序號低於全部小寫字母。
    #c將由('c', 1)進行分類和C由('c', 0)排序。按照第二位排序
    return "".join(list1)

 

#lamda就相當於一個f,lamda(x)相當於 f(x)
 
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
    a.sort(key=lambda x: x[1])

    print(a)
    # Output: [(13, -3), (4, 1), (1, 2), (9, 10)]

學到了lambda 表達式,很絕妙的運用。感謝https://stackoverrun.com/cn/q/9997188的解釋。

看看大神的代碼:

def find_children(dancing_brigade):
    return ''.join(sorted(dancing_brigade,key=lambda c:(c.upper(),c.islower())))

精簡的代碼,很巧妙。sorted就是變成列表,因此我的寫法就多此一舉,我以爲要先轉成列表才能用sorted。 

第二題:

Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.

Example:

multiplication_table(3,3)

1 2 3
2 4 6
3 6 9

-->[[1,2,3],[2,4,6],[3,6,9]]

Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.

題意:

意思就是輸入n行數和m列數,輸出n行m列二維數組,且每一行的每個數都是第一個數的倍數,規律可見例子。
比如[2,2]——>[[1,2],[2,4]]

代碼如下:

def multiplication_table(row,col):
    list1=[]
    list2=[]
    for i in range(0,row):
        a=i+1
        for j in range(0,col):
            list1.append(a*(j+1))
        list2.append(list1)
        list1=[]
    return list2

看看大神的精簡代碼:

def multiplication_table(row,col):
    return [[(i+1)*(j+1) for j in range(col)] for i in range(row)]

發現大神的思路比我好多了,這個規律就是每一個數都是行號乘以列號,因爲是從0開始因此要用(i+1)*(j+1);還是要開始學列表推導式,遇到循環學會用列表推導式! 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章