代码之家  ›  专栏  ›  技术社区  ›  Thasreefa K

在python中生成替代模式

  •  1
  • Thasreefa K  · 技术社区  · 2 年前

    我是Python的新手,正在尝试从两组值开始生成一个替代模式:(0,0)和(10,10)。我的预期输出如下:

    0 0
    10 10
    10 -10
    20 0
    20 20
    20 -20
    30 10
    30 -10
    30 30
    30 -30
    40 0
    40 20
    40 -20
    40 40
    40 -40
    

    我试图用以下Python代码实现这一点,但它生成了不同的输出:

    N = 4
    
    for i in range(N):
        x = i * 10
        y_values = [10, -10, 0]
        for y in y_values:
            print(f"{x}, {y}")
    

    如有任何协助,我们将不胜感激。 非常感谢。

    2 回复  |  直到 2 年前
        1
  •  0
  •   Umar    2 年前

    我已经编写了一个Python脚本来使用嵌套循环生成交替模式。该模式遵循奇数和偶数索引,并且我包含了一个条件,以避免列索引为零时出现负值。

    n = 5
    
    for i in range(n):
        for j in range(i+1):
            if i % 2 == 0 and j % 2 == 0: # Check if both row and column indices are even for alternating sets
                print(f"{i*10} {j*10}")
                if j != 0: # avoid negative in 0.
                
                    print(f"{i*10} -{j*10}")  
            if i % 2 != 0 and j % 2 != 0: # Check if both row and column indices are odd for alternating sets.
            
                print(f"{i*10} {j*10}")
                print(f"{i*10} -{j*10}")
    

    它会产生你的欲望模式

    0 0
    10 10
    10 -10
    20 0
    20 20
    20 -20
    30 10
    30 -10
    30 30
    30 -30
    40 0
    40 20
    40 -20
    40 40
    40 -40
    

    使用逐位AND(&)并调整生成交替模式的条件的另一个或替代解决方案。

    n = 5
    for i in range(n):
        if i % 2 != 0:
            for j in range(1, i + 1):
                if i != j & i % 2 != 0:
                    print(i * 10, j * 10)
                    print(i * 10, -j * 10)
        elif i % 2 == 0:
            for j in range(i + 1):
                if j * 20 <= i * 10:
                    print(i * 10, j * 20)
                    if j != 0:
                        print(i * 10, -j * 20)
    
        2
  •  -2
  •   Syeda Maira Saad    2 年前

    请查看您问题的答案: https://github.com/SyedaMairaSaad/Python/blob/master/pythonStackQuestion.py

    def generate_alternative_pattern():
        # Initial values
        x, y = 0, 0
        step = 10
    
        # Print the first two sets of values
        print(x, y)
        print(x + step, y + step)
    
        # Generate the alternative pattern
        for _ in range(5):
            # Increment x and y
            x += step
            y += step
            print(x, y)
    
            # Decrement y
            y -= step
            print(x, y)
    
            # Increment y
            y += 2 * step
            print(x, y)
    
    generate_alternative_pattern()