【每日一题1119】奇数之和

:woman_mage: 给定如下阵型的数字:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...

请编写一个函数,计算出第 n 行元素的和值。

题目难度:简单
题目来源:codewars: Sum of odd numbers

def solution(n: int) -> int:
    # your code

assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859
def solution(n: int) -> int:
    sol_list = []

    def num_generator(start_index, end_index):
        yield [i for i in range(1, n ** 4, 2)][start_index: end_index]

    index = 0
    if n == 1:
        sol_list = [1]
    else:
        for i in range(1, n+1):
            sol_list = num_generator(index, index + i).__next__()
            index = index + i
    return sum(sol_list)


assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859
def solution(n: int) -> int:
    numCount = sum([i for i in range(1, n + 1)])
    return sum([(1 + 2*i) for i in range(numCount-n,numCount)])

assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859

这样写会不会很离谱

def solution(n: int) -> int:
    n = pow(n,3)
    return n
assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859

python一行解题大法

def solution(n:int):
	return n**3
1 Like
def solution(n: int) -> int:
    x = 0
    row = 0
    while row < n:
        row += 1
        nums = (row + 1) * row / 2
        x0 = x
        x = nums ** 2
        result = int(x - x0)
    return result


assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859

为你点赞!

def solution(n: int) -> int:
    num = 0
    res = 0
    # 计算一个有多少个元素
    for i in range(1, n+1):
        num += i
    # 每个元素放入列表中
    list1 = [(2*j+1) for j in range(num)]
    # 确定第 n 行开始元素的 index 值
    start = num - n
    # 取出来进行相加
    for t in range(start, num):
        res += list1[t]

    return res

assert solution(1) == 1
assert solution(2) == 8
assert solution(13) == 2197
assert solution(19) == 6859
1 Like
public int solution3(int n) {
        if (n == 1) {
            return 1;
        }
        int res = 0;
        int init = 1;
        int m = n * (n - 1) / 2 + n;
        for (int i = 1; i < m; i++) {
            init += 2;
            if (m - n <= i) {
                res += init;
            }
        }
        return res;
    }

墙都不服就服你!

关闭