I didn't know how to describe it in the question properly, so I'll try again here.
I have to solve this question where my code should print different types of squares. I have all of that figured out, however, I'm stuck at the printing part.
So, I start by inputting 4 as the size, and it results in different types of squares being made. For example, these two:
first = ""
for j in range(size-1):
first += "*" * size + "\n"
first += "*" * size
two = ""
for j in range(size-1):
if j == 0:
two += "*" * size + "\n"
else:
two += "*" + ((size - 2) * " ") + "*" + "\n"
two += "*" * size
Now, I have to print them like this:
**** ****
**** * *
**** * *
**** ****
separated by a '\t'.
Since these squares are 'stored' in different strings, this is unfamiliar territory for me as the cursor is at the end of the first square. I don't know what to do, help pls.
There are many ways for that, one is here:
>>> v = '\n'.join([i+'\t' + j for i,j in list(zip([i for i in first.split('\n') if i], [ i for i in two.split('\n') if i]))])
>>> print(v)
**** ****
**** * *
**** * *
**** ****
What i did:
Splitted both strings at newline character, then took corresponding parts and joined them by tab in between, then assembled the whole string.
You can change the data structure you use. Let the square will be not a string, but list of strings, where each string is line should be printed.
Then you can for each line write line_first + '\t' + line_two and print it.
This code worked as you expect.
first = []
for j in range(size - 1):
first.append("*" * size)
first.append("*" * size)
two = []
for j in range(size - 1):
if j == 0:
two.append("*" * size)
else:
two.append("*" + ((size - 2) * " ") + "*")
two.append("*" * size)
for f, t in zip(first, two):
print(f + '\t' + t)
Related
So I have to print * in the shape of A which I did.
pattern = ""
for row in range(7):
for col in range(5):
if ((col==0 or col==4) and row!=0) or ((row==0 or row==3) and (col>0 and col<4)):
pattern = pattern + "*"
else:
pattern = pattern + " "
pattern = pattern + "\n"
pattern = pattern + " "
print(pattern, end="")
OUTPUT:
***
* *
* *
*****
* *
* *
* *
But I want to print more A horizontally.
Example: L displayed as star program 3 times looks as below
* * *
* * *
* * * * * * * * *
Please help!
I did not change a lot in your code, but thought that putting it in a function might be useful. As you can see in the last line, you now just have to call it with the number of letters you want to print. Furthermore, I added a for-loop in between yours, in order to get all the required symbols into the according line.
Lastly, I added an if/else staement that checks this is the end of the row and otherwise does not go into the next line.
def multiplePatterns(n):
pattern = ""
for row in range(7):
for i in range(n):
for col in range(5):
if ((col==0 or col==4) and row!=0) or ((row==0 or row==3) and (col>0 and col<4)):
pattern = pattern + "*"
else:
pattern = pattern + " "
if i == n-1:
pattern = pattern + "\n"
else:
pattern += " "
pattern = pattern + " "
return pattern
print(multiplePatterns(2))
The easiest way is to use a library like pyfiglet : https://pypi.org/project/pyfiglet/ .
If you want to do it yourself, python console write per line, you must print your text (ex:"AAA") line per line.
if your final goal is just that, then:
print(" *** *** ***")
print("* * * * * *")
print("* * * * * *")
print("***** ***** *****")
print("* * * * * *")
print("* * * * * *")
print("* * * * * *")
will do the job.
If your goal is to write any text, then its probably better to create some kind of "font" with each letter in a list.
I'm supposed to create a recursive statement that if first calls triangle(n) it returns
'******\n *****\n ****\n ***\n **\n *'
This above is called for triangle(6) and if I print(triangle(6)) it returns below.
******
*****
****
***
**
*
Then I must create another code recursive_triangle(x, n) that returns a string with the LAST x lines of a right triangle of base and height n. For example if I did recursive_triangle(3, 6) it returns
' ***\n **\n *'
and if i print it should returns
***
**
*
So far my code is
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if n == 1:
return "*"
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1)
for print(triangle(4)) this is what i got
****
***
**
*
How do I modify the code to get the output above?
Your recursion case is ill-formed:
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1)
First of all, this code returns after a single iteration: return ends your function instance, so i never gets to a value of 2. You need to do something simple, and then recur on a simpler case to handle the rest.
Next, triangle exists only to call recursive_triangle. Then, recursive_triangle needs to call itself, not loop back to triangle.
Finally, note that recursive_triangle utterly ignores the parameter k. This value is critical to determine where in the line to place the asterisks.
Each instance of recursive_triangle should produce a single line of the triangle -- you have that correct -- and then concatenate that line with the remainder of the triangle, returning that concatenated whole to the instance that called it. You'll want something roughly like:
else:
line = ... # build a line of k-n spaces and n asterisks
return line + recursive_triangle(k, n-1)
Can you take it from there? Among other things, remember to insert a few useful print commands to trace your execution flow and the values you generate.
First of all, there are better ways to achieve this.
However, if you really want to go this way, the following code can fix the spacing issues.
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if n == 1:
return "*"
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1).replace("\n", "\n ")
which gives you
****
***
**
*
in Python 3.6.5.
You can count the row with r and use a secondary parameter to count the spaces, s
def triangle (r = 0, s = 0):
if r is 0:
return ""
else:
return (" " * s) + ("*" * r) + "\n" + triangle (r - 1, s + 1)
print (triangle(5))
# *****
# ****
# ***
# **
# *
code.py:
#!/usr/bin/env python3
import sys
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if k == 0:
return ""
else:
return "\n".join(["".join([" " * (n - k), "*" * k]), recursive_triangle(k - 1, n)])
#return " " * (n - k) + "*" * k + "\n" + recursive_triangle(k - 1, n)
def main():
print("triangle(6):\n{:s}".format(triangle(6)))
print("recursive_triangle(3, 6):\n{:s}".format(recursive_triangle(3, 6)))
print("repr recursive_triangle(2, 4): {:s}".format(repr(recursive_triangle(2, 4))))
print("repr triangle(4): {:s}".format(repr(triangle(4))))
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
Notes:
To make things simpler, you can look at recursive_triangle(k, n)'s argument meanings like:
k: Recursion step, and also the number of "*" characters. Decrements with every recursive function call
n: 1st (longest) triangle line length (the number of SPACEs + k). Remains constant inside recursion
Current line contains n - k SPACEs followed by k "*" s (n characters in total). Lines are joined together via [Python 3]: str.join(iterable) (or "manually", in the (next) commented line)
The function calls itself until there are no more "*" characters (k becomes 0)
Output:
(py35x64_test) e:\Work\Dev\StackOverflow\q052652407>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32
triangle(6):
******
*****
****
***
**
*
recursive_triangle(3, 6):
***
**
*
repr recursive_triangle(2, 4): ' **\n *\n'
repr triangle(4): '****\n ***\n **\n *\n'
This is the assignment:
Write a python function that accepts a character and an integer and then uses that character to create a triangular structure like the example below. Make sure that the number of lines is in the range 1 to 10 and that only the first character in the user entered symbol is used if they enter more than one character.
Symbol? *
Lines? 4
*
* *
* * *
* * * *
I've got all of it except the spacing right... here's what I figured out so far.
def Triangle():
lines = -1
while lines not in range(1,11):
symbol=input("Symbol? ")
lines=input("Lines? ")
for i in range(lines + 1):
spaces = lines - i
print ((' ' * spaces) + (symbol * i))
This prints out:
*
**
***
****
Can't seem to get this right... thoughts?
Also if anyone has ideas on how to ensure only the first character is used as the symbol as noted in the question, that'd be awesome.
You need add in spaces after each symbol:
print ((' ' * spaces) + ((symbol + ' ') * i))
I am trying to print out an arrow head using *s.
So far my code looks like this.
def head(n):
while n > 0:
print n * "*"
n = n - 1
print head(input())
and it works but if for example I enter 11, it prints this:
***********
**********
*********
********
*******
******
*****
****
***
**
*
But I want it to print like this:
*
***
*****
*******
*********
***********
Which has less arrows, but I can't figure out how to do it.
It makes the function a little simpler to think in terms of how many lines do you want:
def head(lines):
for n in range(1,lines*2,2): # count 1,3,5...
print(('*'*n).center(lines*2-1))
Output:
>>> head(5)
*
***
*****
*******
*********
Here's an alternate way to use a variable length format that is a little less obvious:
def head(lines):
for n in range(1,lines*2,2):
print('{:^{}}'.format('*'*n,lines*2-1))
use string formatting:
def head(size):
n=1
while n < size+1:
stars = n * "*"
print '{:^30}'.format(stars)
n += 2
it will center your asterisks on the field 30 chars wide.
def printHead(n):
for l in range(1,n):
print " "*(n-l)+"*"*(1 if l==1 else 2*l-1)
Each row has level-1 spaces. Then if it's the first level one start, otherwise it has 2*level-1.
>>> printHead(6)
*
***
*****
*******
*********
def head(n):
total = 2 * n - 1
s = ''
for i in xrange(1, n + 1):
k = 2 * i - 1
s += ' ' * ((total - k) / 2) + '*' * k + '\n'
return s
The number of stars on a line is equal to 2n - 1 where n is the line number.
I wouldn't call the parameter "n" in this function as it is not clear to me whether it refers to lines or stars.
You can use the center function to surround a string with whitespace, based on a specified width. You want the arrow to be centred around the longest line so you need 2 variables, one to keep track of the current line and another to remember the largest line.
You want to iterate in the opposite direction to what you have demonstrated, as you want the arrow to point up, not down.
I think this should work for you:
def head(total_lines):
for current_line in range(1, total_lines + 1):
print ((2 * current_line - 1) * "*").center(2 * total_lines - 1)
Yes, this is a homework task. But just please, if you're going to give me the code please tell me what you've done in detail. I am extremely new to this.
So the task is to print an ASCII diamond depending on what width the user inputs. I can do the first half of the diamond, just not the bottom half, for some reason I just cannot see how to do it.
Here's my code:
wid = int(input("Width: "))
i = 1
while i <= wid:
print(" " * (wid - i) + "* " * i)
i = i + 1
Which will output the following if wid = 5:
Width: 5
*
* *
* * *
* * * *
* * * * *
I tried to explain the code with comments. I hope it helps.
wid = int(input("Width: "))
#no. of lines will be double the width
#each loop prints a line.
for i in range(wid *2):
#first half of the diamond
if i<=wid:
no_of_spaces = wid - i
no_of_stars = i
print(" "*no_of_spaces + "* "*no_of_stars)
#next half of the diamond
else:
no_of_spaces = i - wid
no_of_stars = 2*wid - i
print(" "*no_of_spaces + "* "*no_of_stars)
i=1
j=input("ENTER NO =")
l=0
for i in range(i,j-((j/2)-1),1):
print (' ' * ((j+1)/2-i)+'*' *(i*2-1))
l=(j/2+1)
while (i==l):
i=1
for i in range(i,j,1):
print (' ' *((i*2)-i)+'*' *(j-i*2))
if [i==j-1]:
l=raw_input('<press enter to exit>')
You start with i = 1 and go until i > wid to make the top. To make the bottom of the diamond, you must do the reverse of what you did for the top. The code is easy, but I won't write it unless you want me to.
after your while
i=i-2
while i>0:
print(" "*(wid-i)+"* "*i)
i=i-1;
One method
The simplest way would probably be have two loops; one counting i up to width, another counting i back down to 1.
width = int(input("Width: "))
i = 1
while i < width:
print " " * (width-i) + "* " * i
i += 1
while i > 0:
print " " * (width-i) + "* " * i
i -= 1
This is a bit unattractive because it's a little clumsy, but it's simple.
Another method
Another method is to have have a loop that counts to twice the width, doing one of two things. What it does depends on if i has passed the point of maximum width or not. So it does 'up' and 'down' in the same loop, counting i from 1 up to width*2.
width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*width-i)
i += 1
This:
print " " * (width-i) + "* " * i
...is your code. Spaces count from width down to 0, *'s from 1 up to width.
And this:
print " " * (i-width) + "* " * (2*width-i)
...is the same thing but inverted. Spaces count from 0 back up to width, and the *'s go back down from width to 1. This comes into play when i exceeds width.
Width: 4
* # first half does this onward
* *
* * *
* * * *
* * * # second half does the rest downward
* *
*
And another
Another alternative, more complex way is to use a for loop on a list that contains numbers counting up and down. For example: [1, 2, 3, 2, 1]
To make this list, this code has to be. I know, it's a bit ugly:
rows = []
for i in range(1, max+1):
rows.append(i)
rows += rows[-2::-1]
Then, you see, we run the for loop off it.
width = int(input("Width: "))
rows = []
for i in range(1, width+1):
rows.append(i)
rows += rows[-2::-1] # takes a reversed list and adds it on to the end: [1, 2, 3, 2, 1]
for i in rows:
print " " * (width-i) + "* " * i
i iterates through each of the numbers in the rows list, which looks something like [1, 2, 3, 2, 1]. Then we just need one printing gizmo.
In python, there's almost always a shorter and less comprehensible way of doing for loops, and in this case, we can get rid of two extra lines by shortening the first for loop:
width = int(input("Width: "))
rows = [ i for i in range(1, width+1)] # Brain-bending way of doing a for loop
rows += rows[-2::-1]
for i in rows:
print " " * (width-i) + "* " * i
And if you're feeling a bit crazy, here's a mere two line version of the whole thing!
width = int(input("Width: "))
print "\n".join([ " "*(width-i) + "* "*i for i in [ i for i in range(1, width+1) ]+[ i for i in range(1, width+1) ][-2::-1] ])
But I don't recommend this style of coding in general.
Sorry, I got a bit carried away at the end... but the best thing I can say to you now is try everything and play around!
Hope that helps. :)
Since some good methods have been addressed, here are some fun little hacky solutions.
Here's one using Python 2.7 string.center just for shits.
import string
width = int(raw_input("Width:"))
for i in range(width):
print string.center(i * " *", width * 2 )
for i in range(width,0,-1):
print string.center(i * " *", width * 2 )
And here's an outrageous one that ouputs using HTML to center.
file = open('file.html','w')
file.write("<div align='center'>")
for i in range(width):
file.write(i * " *")
file.write("<br>")
for i in range(width,0,-1):
file.write(i * " *")
file.write("<br>")
file.write("</div>")
file.close()
import webbrowser
webbrowser.open("file.html")
check it out (for python 2.7x) :
Filled ASCII Diamond :
width = 1
width += int(raw_input('Width : '))
for i in range (1,width):
for j in range (width,i,-1):
print " ",
for j in range (1,i,1):
print " * ",
print
for i in range (width,1,-1):
for j in range (width,i,-1):
print " ",
for j in range (1,i,1):
print " * ",
print
This works!! But not in any Browser window . . .