Soluție HackerRank pentru Number Groups, subdomeniul Algebra, în Python 3. Include cerința formatată, exemple, explicația pașilor și cod sursă.

  • Problemă: Number Groups
  • Domeniu: Algebra
  • Limbaj: Python 3

Challenge: Number Groups

Subdomeniu: Algebra (algebra)

Scor cont: 20.0 / 20

Submission status: Accepted

Submission score: 1.0

Submission ID: 464721395

Limbaj: python3

Link challenge: https://www.hackerrank.com/challenges/number-groups/problem

Cerință

The positive odd numbers are sorted in ascending order as 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 …, and grouped as (1), (3, 5), (7, 9, 11), (13, 15, 17, 19), … and so on.

Thus, the first group is (1), the second group is (3, 5), the third group is (7, 9, 11), etc. In general, the k^text{th} group contains the next k elements of the sequence.

Given k, find the sum of the elements of the k^text{th} group. For example, for k = 3, the answer is 27:

![image](https://s3.amazonaws.com/hr-assets/0/1511935621-d85a3653c7-Numbergroups-2.png)

Complete the function `sumOfGroup` with input integer k. Return the sum of the elements of the kth group.

Constraints

- 1 ≤ k ≤ 10^6

Subtasks

- For 50% of the maximum score, k ≤ 10^3

Cod sursă

#!/bin/python3

import math
import os
import random
import re
import sys

def sumOfGroup(k):
    ls = k*(k+1)//2+1
    li = k*(k+1)//2-k+1
    a = [2*i-1 for i in range(li,ls)]
    return sum(a)
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    k = int(input().strip())

    answer = sumOfGroup(k)

    fptr.write(str(answer) + '\n')

    fptr.close()
HackerRank Algebra – Number Groups