入坑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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值