I am having trouble to get my function to work. My functions needs to be a parameter which accepts *Asterisk characters and will print out 1 asterisk, 3 ast., 5, any odd numbers in the subsequent lines. So first line will have 1 ast, second line 3 ast., and so on. The parameter will accept any odd int.
My attempt:
def arrowHead(n):
spaces = n / 2
for x in range(1, n+2, 2):
string_ln = ''
for num in range(spaces):
string_ln = string_ln + ' '
for num2 in range(x): string_ln = string_ln + '*'
spaces = spaces - 1
print string_ln
final_string = ''
for x in range(n / 2):
final_string = final_string + ' '
final_string = final_string + '*'
for x in range(3):
print final_string
You're not going to be able to print an arrow head this way, because you can't print characters in between spaces!
You could try something like this?
def arrow(n):
for x in range(n+1):
print (' '*n)+(' *'*x)
n -= 1
>> arrow(7)
>>
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
If you want to debug a Python script, you can use pdb. For example, in your system's shell or command line:
python -m pdb yourscript.py
You can then step through your script using n (which skips function calls), s (which steps into function calls), print the state of variables using p yourvarname, and use several other commands (try using help to see them all and then help somecommand to see detailed help).
Not clear with your question, but if you want to print asterisk odd number of times, go with this
def arrowHead(n):
print '*' * (2*n-1)
Update:-
>>> def arrow(n,flag=1):
if flag<n:
print (' '*(arrow(n,flag+1))+' * '*(n-(2*flag-1)))
return 2*flag-1
>>> arrow(10)
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Related
How to print this pattern? I have done regular patterns but I am unable to get odd stars.
You could use a simple list comprehension:
n = 5
print("\n".join((a := [("* "*i).center(n*2 + 1) for i in range(1, n + 1) if i&1]) + a[::-1][1:]))
*
* * *
* * * * *
* * *
*
You can change n to anything you want
How can I make a perfect Christmas tree in python? i have here my code but its not working well, it needs to print '~~' in the first for loop.
height = 7
for a in range(1, (height + height) - 3):
if a % 2 != 0:
if a == 1:
print(a * 'o')
else:
print(a * '* ')
for a in range(height + 1):
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
Output of my code is:
o
* * *
* * * * *
* * * * * * *
* * * * * * * * *
~~~~~~~~|~~~~~~~~
~~~~~~~~|~~~~~~~~
my desired output is:
~~~~~~~~o~~~~~~~~
~~~~~~* * *~~~~~~
~~~~* * * * *~~~~
~~* * * * * * *~~
* * * * * * * * *
~~~~~~~~|~~~~~~~~
~~~~~~~~|~~~~~~~~
def values():
yield 'o'
for i in range(3, 10, 2):
yield ' '.join('*' * i)
yield from '||'
for v in values():
print('{:~^17}'.format(v))
Prints:
~~~~~~~~o~~~~~~~~
~~~~~~* * *~~~~~~
~~~~* * * * *~~~~
~~* * * * * * *~~
* * * * * * * * *
~~~~~~~~|~~~~~~~~
~~~~~~~~|~~~~~~~~
Or:
for v in ['o'] + [' '.join('*' * i) for i in range(3, 10, 2)] + ['|', '|']:
print('{:~^17}'.format(v))
Here is an example using the string method center.
for x in range(1, 30, 2):
s = '*' * x
print(s.center(30))
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
>>>
EDIT: Including the tildes.
limit = 30
for x in range(1, limit, 2):
tildes = '~' * ((limit-x)//2)
out = tildes + '*' * x + tildes
print(out)
~~~~~~~~~~~~~~*~~~~~~~~~~~~~~
~~~~~~~~~~~~~***~~~~~~~~~~~~~
~~~~~~~~~~~~*****~~~~~~~~~~~~
~~~~~~~~~~~*******~~~~~~~~~~~
~~~~~~~~~~*********~~~~~~~~~~
~~~~~~~~~***********~~~~~~~~~
~~~~~~~~*************~~~~~~~~
~~~~~~~***************~~~~~~~
~~~~~~*****************~~~~~~
~~~~~*******************~~~~~
~~~~*********************~~~~
~~~***********************~~~
~~*************************~~
~***************************~
*****************************
I have modified your code a little bit, well here's the code:
height = 7
z = height - 3
x = 1
for i in range(1, (height + height) - 3):
if i % 2 != 0:
if(i==1):
print('~~' * z + 'o' +'~~' * z)
else:
print('~~' * z + '* ' * (x-1)+ '*' *1 +'~~' * z)
x+=2
z-=1
for a in range(height + 1):
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
Output:
~~~~~~~~o~~~~~~~~
~~~~~~* * *~~~~~~
~~~~* * * * *~~~~
~~* * * * * * *~~
* * * * * * * * *
~~~~~~~~|~~~~~~~~
~~~~~~~~|~~~~~~~~
I edited your code just a little:
height = 7
width = 17
for a in range(1, (height + height) - 3):
if a % 2 != 0:
if a == 1:
sym = 'o'
curly = ''.join(['~' for i in range((width-len(sym))//2)])
print(curly + a * sym + curly)
else:
sym = a * '* '
curly = ''.join(['~' for i in range((width - len(sym)) // 2)])
print(curly + sym + curly)
for a in range(height + 1):
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
if a % (height + 1) == 1:
test = height - 3
print(test * '~~' + a * '|' + test * '~~')
~~~~~~~~o~~~~~~~~
~~~~~* * * ~~~~~
~~~* * * * * ~~~
~* * * * * * * ~
* * * * * * * * *
~~~~~~~~|~~~~~~~~
~~~~~~~~|~~~~~~~~
It's not perfect but no Christmas tree is 100% straight.
It is a simple programming problem. So let's create a simple program for solving it.
First, we need to draw our tree. in each line, our tree has an odd number of starts for showing tree and some ~ characters for representing the background. If we want to have a tree which its height is equal to the height variable. at the heightth line, we don't want to have any ~ character. But in the first line, we want to have only one * character.
So it seems to be a good idea to having a for loop that counts from height to the zero and relates the number of ~ characters somehow to it.
Let's see the code first:
for i in range(height, 0, -1):
print("~" * (i - 1)) // repeating `~` character (i - 1) times
If you run this code, you will get the following output:
~~~~~~
~~~~~
~~~~
~~~
~~
~
Now let's add the * characters for drawing the tree. We should have the exact opposite relation for * characters from ~.
for i in range(height, 0, -1):
print("~" * (i - 1), end="")
print("*" * (((height - i) *2) + 1))
We add end="" at the end of the previous print function. Because print will add a newline character at the end in each call and we want to prevent it (because we want to add * characters after ~ characters).
Then we want to add * characters at each line. But we want to count their number
for 1 to height * 2. But we only need the odd numbers. That's what we did in the second line. Now, we have the following number of * characters at each line: 1, 3, 5, 7,...
Below is the output of that code (We considered that height = 7):
~~~~~~*
~~~~~***
~~~~*****
~~~*******
~~*********
~***********
*************
As you can see, now we have our Christmas tree. But our background is incomplete.
The only thing we should do is to repeat our first print statement. But this time we should not add end="" because we want that newline at the end of each line.
for i in range(height, 0, -1):
print("~" * (i - 1), end="")
print("*" * (((height - i) *2) + 1), end="")
print("~" * (i - 1))
Now our tree is complete:
~~~~~~*~~~~~~
~~~~~***~~~~~
~~~~*****~~~~
~~~*******~~~
~~*********~~
~***********~
*************
You can add other things to your tree by following this simple approach. I hope this helps you.
Try using more conditionals to handle the number of stars (*). Drop a comment below if that doesn't work.
Like, you could do:
if '1star' do this..:
elif '2stars' do this..:
I would code it like this:
sky=8
tree=1
for i in range(0,5):
if i==0:
print(sky*'~'+tree*'o'+sky*'~')
else:
print(sky*'~'+tree*'*'+sky*'~')
sky-=1
tree+=2
sky=8
tree=1
for i in range(0,2):
print(sky*'~'+tree*'|'+sky*'~')
I modified the Christmas tree so that it looked thinner.
This is my code:
var = 14
for i in range(1, var + 1):
print(" " * (var - i) + "*" * i + "*" * (i - 1))
Sample output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
I m trying to print the following triangle in python, but not able to
*#####
**####
***###
****##
*****#
I am only able to print '*', but not hashes.
here's my code to print '*'
max = 6
for x in range(1,max+1):
for y in range(1,x+1):
print '*',
print
length = 6
for x in range(1, length+1):
print(x * '*' + (length - x) * '#') # integer * (string), concatenate the string integer times
How to Print * in a triangle shape in python?
*
* *
* * *
* * * *
* * * * *
This is one of the coding interview questions.
def print_triangle(n):
for i, j in zip(range(1,n+1), range(n,0,-1)):
print(" "*j, '* '*i, " "*j)
print_triangle(5)
I'm confused and frustrated as to why my program is not executing the way it should. I am trying to create a right triangle using asterisks on python ver 3. I am using the exact code from the text book and it comes out as a straight line. Please enlighten me.
example
size = 7
for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
results in
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
all in one column
In Python, indentation counts. The final print should be aligned with the second for.
size = 7
for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
Result:
*
**
***
****
*****
******
*******
An empty print function effectively means "move to a new line". if both print statements occur at the same indentation level, then every time you print an asterisk, you'll move to the next line. If the second print goes outside the inner for loop, you'll only get 7 newlines.
as an alternative you can use one for loop !
>>> s=''
>>> for i in range(7):
... s+='*'
... print (s)
...
*
**
***
****
*****
******
*******
It may not be the most readable solution but if you fancy oneliners this is one way of doing it:
print "\n".join(["".join(["*" for col in range(row+1)]) for row in range(7)])
EDIT
Just to make it even shorter:
print "\n".join(["*" * (row+1) for row in range(7)])
str1 = 'x '
str2 = ' ' #give space within the inverted comma
for i in range (1,6):
print((str2 * (5 - i)) + (str1 * i))
#print((str1 * i)+(str2 * (5 - i)))
other program:
str1 = 'x '
str2 = '' #give empty string(remove sace from the single inverted comma)
for i in range (1,6):
print((str2 * (5 - i)) + (str1 * i))
#print((str1 * i)+(str2 * (5 - i)))
My goal is to create a hollow diamond using python.
Sample input:
Input an odd Integer:
9
Sample output:
*
* *
* *
* *
* *
* *
* *
* *
*
But so far, I have the following code that is not working right. Please help me to modify the code to achieve the goal above:
a=int(input("Input an odd integer: "))
k=1
c=1
r=a
while k<=r:
while c<=r:
print "*"
c+=1
r-=1
c=1
while c<=2*k-1:
print "*"
c+=1
print "\n"
k+=1
r=1
k=1
c=1
while k<=a-1:
while c<=r:
print " "
c+=1
r+=1
c=1
while c<= 2*(a-k)-1:
print ("*")
c+=1
print "\n"
k+=1
The code above return a result that is very far from my goal.
Input an odd integer: 7
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
I am actually converting the code from this post: http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern written in C language and will modify later for the hollow one but I can't get it... There is something wrong with my conversion..
A Hollow diamond is the solution to the equation
|x|+|y| = N
on an integer grid. So Hollow diamond as a 1-liner:
In [22]: N = 9//2; print('\n'.join([''.join([('*' if abs(x)+abs(y) == N else ' ') for x in range(-N, N+1)]) for y in range(-N, N+1)]))
*
* *
* *
* *
* *
* *
* *
* *
*
Your problem is that you keep using print. The print statement (and the function in Python 3) will add a line-break after what you printed, unless you explicitely tell it not to. You can do that in Python 2 like this:
print '*', # note the trailing comma
Or in Python 3 (with the print function) like this:
print('*', end='')
My solution
I took my own take at the problem and came up with this solution:
# The diamond size
l = 9
# Initialize first row; this will create a list with a
# single element, the first row containing a single star
rows = ['*']
# Add half of the rows; we loop over the odd numbers from
# 1 to l, and then append a star followed by `i` spaces and
# again a star. Note that range will not include `l` itself.
for i in range(1, l, 2):
rows.append('*' + ' ' * i + '*')
# Mirror the rows and append; we get all but the last row
# (the middle row) from the list, and inverse it (using
# `[::-1]`) and add that to the original list. Now we have
# all the rows we need. Print it to see what's inside.
rows += rows[:-1][::-1]
# center-align each row, and join them
# We first define a function that does nothing else than
# centering whatever it gets to `l` characters. This will
# add the spaces we need around the stars
align = lambda x: ('{:^%s}' % l).format(x)
# And then we apply that function to all rows using `map`
# and then join the rows by a line break.
diamond = '\n'.join(map(align, rows))
# and print
print(diamond)
def diamond(n, c='*'):
for i in range(n):
spc = i * 2 - 1
if spc >= n - 1:
spc = n - spc % n - 4
if spc < 1:
print(c.center(n))
else:
print((c + spc * ' ' + c).center(n))
if __name__ == '__main__':
diamond(int(input("Input an odd integer: ")))
this is not pretty, but its a function that does what you want:
def make_diamond(size):
if not size%2:
raise ValueError('odd number required')
r = [' ' * space + '*' + ' ' * (size-2-(space*2)) + '*' + ' ' * space for space in xrange((size-1)/2)]
r.append(' ' * ((size-1)/2) + '*' + ' ' * ((size-1)/2))
return '\n'.join(r[-1:0:-1] + r)
first i check to make sure its an odd number,
then i create a list of the lines from the center downwards.
then i create the last point.
then i return them as as a string, with a mirror of the bottom on top without the center line.
output:
>>> print make_diamond(5)
*
* *
* *
* *
*
>>> print make_diamond(9)
*
* *
* *
* *
* *
* *
* *
* *
*
Made it in one single loop ;)
x = input("enter no of odd lines : ") #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2
print ( " " * i + "*" )
i = i-1 #i=1
while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
print (" "* a + "*" + " "*b + "*")
y = y-2 # 2,0,-2
i = i-1 # 1,0,-1, -2 (loop wont run for -2)
i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")
The previous answer has got two corrections, which've been done here :
import math
x = int(input("enter no of odd lines : ")) #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2
print ( " " * i + "*" )
i = i-1 #i=1
while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
print (" "* a + "*" + " "*b + "*")
y = y-2 # 2,0,-2
i = i-1 # 1,0,-1, -2 (loop wont run for -2)
i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")
Note : Now this works for both python 2.5x and python 3.x
If you wish to know the difference in the two answers, then google it!
sizeChoice = 13
N = sizeChoice//2
for column in range (-N, N + 1):
for row in range (-N, N + 1):
if abs(column) + abs(row) == N:
print ("*", end = " ")
else:
print(" ", end = " ")
print ( )
this code works perfectly to print a hollow diamond where you can set diagonal length upto user requirement
n=int(input('Enter Odd Diagonal length :'))-1
j=n-1
print(' '*(n)+'*')
for i in range(1, 2*n):
if i>n:
print(' '*(i-n)+'*'+' '*(2*j-1)+'*')
j-=1
else:
print(' '*(n-i)+'*'+' '*(2*i-1)+'*')
if n>1:
print(' '*n+'*')
Hallow Diamond in Python using only print function
for i in range(1,6):
print(' '*(5-i) + '*'*1 + ' '*(i-1) + ' '*max((i-2),0) + '*'*(1%i) )
for j in range(4,0,-1):
print(' '*(5-j) + '*'*1 + ' '*(j-1) + ' '*max((j-2),0) + '*'*(1%j) )