Search code examples
pythonffmpeg

Is it possible to print this pattern with python?


Is it possible to print this pattern with python?

[s0][s1][s01]
[s01][s2][s012]
[s012][s3]x[s0123]
[s0123][s4]x[s01234]

This is for a ffmpeg filter_complex. So, basically it searches for number of images in a directory and construct below command for me to use for a different purpose. So far I have managed to get the below output:

ffmpeg -loop 1 -t 5 -i 3.png -loop 1 -t 5 -i 5.png -loop 1 -t 5 -i 4.png -loop 1 -t 5 -i 6.png -loop 1 -t 5 -i 1.png -loop 1 -t 5 -i 2.png -filter_complex "[0]scale=816:1456[s0];[1]scale=816:1456[s1];[2]scale=816:1456[s2];[3]scale=816:1456[s3];[4]scale=816:1456[s4];[5]scale=816:1456[s5];

But I'm stuck at obtaining the above pattern.

PS:

In my project the pattern will be used to create something like below:

"[s0][s1]xfade=transition=pixelize:duration=0.2:offset=4[s01];[s01][s2]xfade=transition=pixelize:duration=0.2:offset=8[s012];[s012][s3]xfade=transition=pixelize:duration=0.2:offset=12[s0123];[s0123][s4]xfade=transition=pixelize:duration=0.2:offset=16[s01234];[s01234][s5]xfade=transition=pixelize:duration=0.2:offset=20,format=yuv420p" out.mp4

I tried using an array in for loop, but it does not provide the expected output.

def print_pattern(num_lines):
    for i in range(num_lines):
        for j in range(i + 1):
            print(j, end='')
        print(' and', i + 1, 'and', end=' ')
        for j in range(i + 1):
            print(j, end='')
        for k in range(i + 1):
            print(k + j + 1, end='')
        print()

num_lines = 4  # Change this variable to control the number of lines
print_pattern(num_lines)

This is the output.

0 and 1 and 01
01 and 2 and 0123
012 and 3 and 012345
0123 and 4 and 01234567

Solution

  • You don't need the for k loop. Just increase the range of the second for j loop by 1.

    def print_pattern(num_lines):
        for i in range(num_lines):
            for j in range(i + 1):
                print(j, end='')
            print(' and', i + 1, 'and', end=' ')
            for j in range(i + 2):
                print(j, end='')
            print()
    
    print_pattern(5)
    

    Output:

    0 and 1 and 01
    01 and 2 and 012
    012 and 3 and 0123
    0123 and 4 and 01234
    01234 and 5 and 012345
    

    You can also simplify a little by starting the range of the outer loop at 1, so you don't have to keep writing i+1.

    def print_pattern(num_lines):
        for i in range(1, num_lines+1):
            for j in range(i):
                print(j, end='')
            print(' and', i, 'and', end=' ')
            for j in range(i + 1):
                print(j, end='')
            print()