Home > OS >  Write a function with 2 arguments (string and integer) and it should print out a square of character
Write a function with 2 arguments (string and integer) and it should print out a square of character

Time:11-04

Here is my function, but it doesn't properly work. The 1st output line is fine, but the 2nd line starts text from beginning instead of continuing it. :

def squared(text, length):
    for i in range(length):
        if i%length==0: 
            result=text*length
        
        print(result[0:length])
        
if __name__ == "__main__":
    squared("abc", 5)

The out put must be:

abcab
cabca
bcabc
abcab
cabca

CodePudding user response:

You could cycle around the text and for each line islice the next 5. That way you don't have to manage any indices and mod math.

from itertools import cycle, islice

def squared(text, length):
    letters = cycle(text)  # lazy iterator -> abcabcabcabc....
    for i in range(length):
        print("".join(islice(letters, length)))
        # print(*islice(letters, length), sep="")

>>> squared("abc", 5)
abcab
cabca
bcabc
abcab
cabca

Some docs

  • Related