使用python中的数字生成特定模式

时间:2016-03-24 14:51:09

标签: python

我试图在python中创建一个特定的模式,但不能获得相同的输出。这是我想要的输出

import pytest
from hamcrest import assert_that, calling, is_not, raises

@pytest.mark.parametrize('func, args, kwargs', [
    [list_get, (), {}],
    [list_get, (key, "city", 0), {}],
    [list_get, (key, "contact_no", 1, {}, policy, ""), {}],
    [list_get, (), {'key': key}],
])
def test_func_dont_raises(func, args, kwargs):
    assert_that(calling(func).with_args(*args, **kwargs), is_not(raises(Exception)))

我写的代码是

1
1 3
1 3 5
1 3 5 7
1 3 5 7 9

我得到的输出模式是:

from __future__ import print_function
for i in range(1, 11, 1):
    print()
    for j in range(1 , i):
        print(j ,end ="")

我可以做出哪些改变以获得正确的输出?

5 个答案:

答案 0 :(得分:1)

您可以使用最后一个参数跳过范围。

您可以尝试for i in range(1, 11, 2):

答案 1 :(得分:0)

看起来你只需要一步2并在每一步打印数字到目前为止。 end的{​​{1}}关键字参数控制它应该在...结尾打印的内容。默认换行符很好。默认print也是您所需要的,因此您只需要解压缩收集的整数以在每次迭代时打印。

sep=' '

我确信有更好的方法可以解决这个问题,但这有一个理想的输出。

答案 2 :(得分:0)

试试这个

from __future__ import print_function
for i in range(2, 11, 2):
    print()
    for j in range(1 , i, 2):
        print(j ,end =" ")

答案 3 :(得分:0)

您可以使用以下方法获得所需的输出:

number_list = []
# N is the number up to, but not including, which you want to print
for number in range(1, N, 2):
    number_list.append(number)
    print number_list

如果您关心格式化,可以执行以下操作:

number_list = []
# N is the number up to, but not including, which you want to print
for number in range(1, N, 2):
    number_list.append(number)
    for element in number_list:
        print element,
    print

答案 4 :(得分:0)

要获取奇数,请使用range(1,n,2)并将数字附加到list,然后构建类似'{} ' * len的格式字符串,其中lenlist的长度

def print_odds(n):
    odds = []
    for o in range(1,n,2):
        odds.append(o)
        odd_string = '{} ' * len(odds)
        print(odd_string.rstrip().format(*odds))