Home > front end >  How to print a pattern of a square wave of asterisks that is 3 units long on each side with input be
How to print a pattern of a square wave of asterisks that is 3 units long on each side with input be

Time:11-05

I'm a beginner to programming and started off with python.

I need to print the following pattern:

*** *** *** ***
* * * * * * * *
* *** *** *** *

This just looks like a square wave made of asterisks. The input is the number of asterisks. So the above example would have an input of 31.

Similarly, an input of 13 would have an output that looks like:

*** ***
* * *
* ***

I came up with the following code but it fails for most odd inputs and I can't figure out where I'm going wrong and honestly feel frustrated after trying for so long.

n=11
count = 1
if n%4 == 0:
    add = 1
else: 
    add = 2
for i in range(1,4):
    for j in range(1,2*(n//4) add):
        if(i==2 and (i j)%2==0) or ((i j-1)%4 == 0 and i!=2):
            print("-", end="")
        elif count<=n and j<n//2:
            count  =1
            print("*", end="")
        else:
            break
    print() 

P.S: I've used a hyphen instead of space for separation because it was better discernable on my terminal.

CodePudding user response:

A bit dirty but it works :)

x = 22 # change this to change the number of asterisk
l = []
i=0
while x>0:
    if i%2==0:
        x-=3
        i =1
        l.append(3) #3 asterisks
    else:
        i =1
        x-=1
        l.append(1)#1 asterisk
if x<0: # 2 or 1 asterisk tail
    l[-1] = l[-1] x

top =[] # display the top
mid=[]  # display the middle 
bot =[] # display the bottom
for i in range(len(l)): 
    if l[i]==3: # if 3 asterisks
        top.append('*')
        mid.append('*')
        bot.append('*')
    elif l[i]==2: # if 2
        if i%4==0: # to up
            top.append('')
            mid.append('*')
            bot.append('*')
        else: #to down
            top.append('*')
            mid.append('*')
            bot.append('')
    elif i%4==1:# asterisk up
        top.append('*')
        mid.append(' ')
        bot.append(' ')
    elif i%4==3: #asterisk down
        top.append(' ')
        mid.append(' ')
        bot.append('*')
        
#display the result
print(''.join(top))
print(''.join(mid))
print(''.join(bot))

for 31 asterisks :

*** *** *** ***
* * * * * * * *
* *** *** *** *

for 22 :

*** *** ***
* * * * * *
* *** *** 

I hope it'll help you :D

CodePudding user response:

Every 8 asterisks the pattern repeats. So we'll have each horizontal segment of 4 characters (including spaces) n/8 times, with n%8 extra '*'s.

The first line will repeat '*** ' n/8 times, with an additional 1, 2, or 3 '*' if n%8 is 3, 4, or 5.

The second line will repeat '* * ' n/8 times, with an additional '' if 2 <= n%8 < 6, or ' *' if n%8 >= 6.

The third line will repeat '* **' n/8 times, '' if 1 <= n%8 <= 6, or ' *' if n%8 == 7.

  • Related