Tuesday, April 23, 2024
HomeSoftware EngineeringFind out how to Discover the Row of the Odd Triangle in...

Find out how to Discover the Row of the Odd Triangle in Python


The problem

Given a triangle of consecutive odd numbers:

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

discover the triangle’s row figuring out its index (the rows are 1-indexed), e.g.:

odd_row(1)  ==  [1]
odd_row(2)  ==  [3, 5]
odd_row(3)  ==  [7, 9, 11]

Notice: your code must be optimized to deal with large inputs.

The answer in Python code

Possibility 1:

def odd_row(n):
    m = (n - 1) * n + 1
    return [*range(m, m + n * 2, 2)]

Possibility 2:

def odd_row(n):
    return [x for x in range(n**2-n+1, (n+1)**2-n,2)]

Possibility 3:

odd_row = lambda n:record(vary(n*(n-1)+1,n*(n+1),2))

Check circumstances to validate our resolution

take a look at.assert_equals(odd_row(1), [1])
take a look at.assert_equals(odd_row(2), [3, 5])

take a look at.assert_equals(odd_row(13), [157, 159, 161, 163, 165, 167, 169, 171,
    173, 175, 177, 179, 181])

take a look at.assert_equals(odd_row(19), [343, 345, 347, 349, 351, 353, 355, 357,
    359, 361, 363, 365, 367, 369, 371, 373, 375, 377, 379])

take a look at.assert_equals(odd_row(41), [1641, 1643, 1645, 1647, 1649, 1651, 1653,
    1655, 1657, 1659, 1661, 1663, 1665, 1667, 1669, 1671, 1673, 1675, 1677,
    1679, 1681, 1683, 1685, 1687, 1689, 1691, 1693, 1695, 1697, 1699, 1701,
    1703, 1705, 1707, 1709, 1711, 1713, 1715, 1717, 1719, 1721])
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments