Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generating alternative Pattern in python

I’m new to Python and trying to generate an alternative pattern starting with two sets of values: (0, 0) and (10, 10). My expected output is as follows:

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

I attempted to achieve this with the following Python code, but it generated a different output:

N = 4

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

Any assistance would be appreciated.
Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’ve written a Python script to generate an alternating pattern using nested loops. The pattern follows an odd and even indices, and I’ve included a condition to avoid negative values when the column index is zero.

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}")

it will generate your desire pattern

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

Another or alternative solution using bitwise AND (&) and adjust conditions for generating an alternating pattern.

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading