入坑codewars第四天-Delete occurrences of an element if it occurs more than n times、Sum of odd numbers

第一題:

Enough is enough!
Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like this sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them that he will only sit during the session if they show the same motive at most N times. Luckily, Alice and Bob are able to encode the motive as a number. Can you help them to remove numbers such that their list contains each number only up to N times, without changing the order?

Task
Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

Example
  delete_nth ([1,1,1,1],2) # return [1,1]

  delete_nth ([20,37,20,21],1) # return [20,37,21]

題意是:

給定列表lst和數字N,創建一個新列表,其中包含最多n次的每個lst數,而無需重新排序。例如,如果N = 2,輸入爲[1,2,3,1,2,1,2,3],則取[1,2,3,1,2],然後刪除[1,2,3,1,2] ]因爲這會導致1和2在結果中3次,然後取3,這導致[1,2,3,1,2,3]。

即,每個數按照原定的次序輸出在規定的個數內

比如20,37,20,21;輸入個數爲1;則依次取20,37,20(不取,因爲是第二個超過了1),21所以= 20,37,21

代碼如下,也是參考了別人的思路,非常簡短

def delete_nth(order,max_e):
    ans = []#建立一個新的列表存新數列
    for o in order:#在order列表中取數
        if ans.count(o) < max_e:#如果當前數字計數<給定的個數限制,則加到新列表ans中
            ans.append(o)
    return ans

第二題:

題目:第一眼看還以爲是楊輝三角,但是發現不是,是奇數三角

就是1、3、5、7……一堆奇數排成這樣的三角形,第一層一個數,第二層兩個數……以此類推,所以還是很簡單實現。


思路:我的思路就是很笨的方法:

首先計算每一行的第一個數是奇數列表中的第幾個,比如第五層第一個是奇數列表中的第幾個,因爲前面有1+2+3+4=10個數了,因此第五層第一個是第十一個數,也就是2*10+1

(1)計算第n層前面的數有幾個

(2)計算第n層開始的數是多少

(3)計算第n層奇數的和(循環)

代碼如下:

def row_sum_odd_numbers(n):
    x=(int)((1+n-1)*(n-1)/2)
    y=(int)(2*x+1)
    sum=0
    for i in range(y,y+2*n):
        if i%2 != 0:
            sum=sum+i
    return sum

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