how to print two Sticking diamonds in python - python

I would like to write a python program to print the above shape( I am new to python)
but I have write the program of single diamond and now I have a problem to solve this,
would u guide to find the algorithm?
* *
*** ***
**********
*** ***
* *
this is the single diamond:
def Diamond(rows):
n = 0
for i in range(1, rows + 1):
for j in range (1, (rows - i) + 1):
print(end = " ")
while n != (2 * i - 1):
print("*", end = "")
n = n + 1
n = 0
print()
k = 1
n = 1
for i in range(1, rows):
for j in range (1, k + 1):
print(end = " ")
k = k + 1
while n <= (2 * (rows - i) - 1):
print("*", end = "")
n = n + 1
n = 1
print()
rows = int(input())
Diamond(rows)

I was bored, here you go.
In [36]: def print_diamonds(width, ds):
...: r = width//2
...: for i in range(-r, r+1):
...: print((' '*(abs(i)) + '*'*((r-abs(i))*2+1) + ' '*(abs(i)))*ds)
...:
In [37]: print_diamonds(5, 2)
* *
*** ***
**********
*** ***
* *

Your question is vague but here is a function for a single diamond per line. I'm not sure what do you expect. Be mor explicite.
vect = ('*', '***', '*****', '***', '*')
def method():
for i in range(0,5):
print(abs((2-i))*" ",vect[i])

Related

I need help doing this double summation in python

I'm pretty new in python and I'm having trouble doing this double summation.
I already tried using
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
and using 2 for loops but nothing seens to work
You were pretty close:
N = int(input("N: "))
M = int(input("M: "))
x = sum(sum(j ** 2 * (k + 1) for k in range(M)) for j in range(1, N + 1))
It also can be done with nested for loops:
x = 0
for j in range(1, N + 1): # [1, N]
for k in range(M): # [0, M - 1]
x += j ** 2 * (k + 1)
After a little math...
x = M * (M+1) * N * (N+1) * (2*N+1) // 12

How can I save integers displayed in the console?

I created a Python program that calculates the digits of pi and displays them in the console as the calculation is running. Eventually, it starts deleting numbers that were first displayed. How could I save the numbers as they're being displayed? Here is the code:
def calcPi(limit):
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
yield n
if counter == 0:
yield '.'
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
for d in pi_digits:
print(d, end='')
i += 1
if i == 55:
print("")
i = 0
if __name__ == '__main__':
main()
You can write to a txt file instead of printing. For example:
with open("output.txt", "a") as f:
instead of printing,
print(d, end='')
do
f.write(str(d))
and instead of printing,
print('')
do
f.write('\n')
On most UNIX operating systems you can use the tee command:
python calculate_pi.py | tee output.txt
This will let you see the output in your terminal and write it to the file at the same time.

Drawing Pattern in Python

I am trying to draw the following pattern in Python:
# #
## ##
### ###
########
I can get the two right triangles separately but cannot figure out how to make them into one. Would anone be able to help me?
My code for the left triangle is:
rows = 4
for i in range(0, rows):
for j in range(0, i+1):
print('#', end='')
print()
My code for the right triangle is:
for i in range(0,rows):
for j in range(0, rows-i):
print(' ',end='')
for k in range(0, i+1):
print('#',end='')
print()
I'm trying to combine them somehow but haven't been successful.
Here's one way to go about it. '#' * x prints a increasing number of '#'s and space [(2*x):] slices the eight spaces in the string space.
space = ' '
for x in range (1, 5) :
print ('#' * x + space [(2*x):] + '#' * x)
And here is a version without slicing.
y = 6
for x in range (1, 5) :
print ('#' * x, end = '')
if y > 0 : print (' ' * y, end = '')
print ('#' * x)
y = y - 2
This is a pattern program
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
the code for this program will be:
for i in range(0,7):
for j in range(0,i+1):
print("*",end=" ")
print("\r")
for m in range(5,-1,-1):
for n in range(0,m+1):
print("*",end=" ")
print("\r")
try using string formatting with spacers like so:
>>>print("{:<4}{:>4}".format('#','#'))
# #
>>>print("{:x^7}".format('#'))
xxx#xxx
#f-strings
x = '#'
>>>print(f'{x:>5}')
#
The formatting spacers add padding, to the left right, or both sides of a string
I ended up doing:
col=8
x=2
y=col-1
for i in range(1, col//2+1):
for j in range(1, col+1):
if(j>=x and j<=y):
print(' ', end='')
else:
print('#', end='')
x=x+1
y=y-1
print()
Here assuming no.of lines l = 4
The min space starts with s = 2.
No.of hashes to print based on lines end = l * 2.
l = 4
space = 2
end = l * 2
for i in range(1, l + 1):
print('#'*i, end='')
print(' '*(end - space), end='')
print('#'*i)
space = space + 2

How to print a triangle in python?

I want to make a function to print triangle like the following picture. User can insert the row number of the triangle. The total lenght of first row is must an odd.
I try to use below code :
def triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = 5
triangle(n)
Here is the expected output image :
and here is my actual output image :
but I can't remove the star middle star. And it's not Upside - Down Triangle
You could try a different way.
def triangle(n) :
for i in range(1,n+1) :
for j in range(1,i) :
print (" ",end="")
for j in range(1,(n * 2 - (2 * i - 1))
+1) :
if (i == 1 or j == 1 or
j == (n * 2 - (2 * i - 1))) :
print ("*", end="")
else :
print(" ", end="")
print ("")
n = 5
triangle(n)
Not sure how cool implementation is this but it gives results:
def triangle(n):
print(' '.join(['*']*(n+2)))
s = int((n/2)+1)
for i in range(s):
star_list = [' ']*(n+2)
star_list[-i-2] = ' *'
star_list[i+1] = '*'
print(''.join(star_list))
n = 5
triangle(n)
Output:
* * * * * * *
* *
* *
*
for n = 7:
* * * * * * * * *
* *
* *
* *
*
I would try a recursive solution where you call the printTriangle() function. This way, it will print the point first and move it's way down the call stack.

How to remove this extra trailing space at the end of each line in python3

I am trying to print this pattern using print() function in python3.
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 1 0
0 1 0
0
the following are the two ways I implemented this.
numeric approach
limit = int(input())
space = ' '
for i in range(0, limit + 1):
print(space * (limit - i), end='')
for j in range(2 * i + 1):
if j > i:
print(i - (j - i), end=' ')
else:
print(j, end=" ")
print()
for i in range(0, limit)[::-1]:
print(space * (limit - i), end='')
for j in range(2 * i + 1)[::-1]:
if j > i:
print(i - (j - i), end=' ')
else:
print(j, end=" ")
print()
string and list comprehension approach
gap = ' '
y = int(input())
y = y + 1
for n in range(1, y + 1):
str1 = ' '.join(str(e) for e in list(range(n)))
str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
print(gap * (y - n) + str1 + " " + str2.strip())
for n in range(1, y)[::-1]:
str1 = ' '.join(str(e) for e in list(range(n)))
str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
print(gap * (y - n) + str1 + " " + str2.strip())
the pattern is printing right but when I am submitting this to online judge it do not accept.
wrong answer 1st lines differ - expected: ' 0', found: ' 0 '
it expects to remove that extra space after the 0.
PROBLEM: In both of the code snippet I am unable to remove the last line extra space. I do not know how to achieve this Pattern and also not to have that extra space after the number at the end of each line.
The problem appears to be the expression gap * (y - n) + str1 + " " + str2.strip(). For the first line, str is null, so you have str1 followed by a space, followed by nothing, which means that you have a space at the end of your line. The solution is to add the lists together first, then join:
for n in range(1, y + 1):
list1 = [str(e) for e in list(range(n))]
list2 = [str(e) for e in list(range(n - 1))[::-1]]
print(gap * (y - n)+" ".join(list1+list2))
BTW, an alternative to list(range(n - 1))[::-1] is list(range(n-2,-1,-1)).
You can also combine list comprehensions with various tricks, such as
[str(e) if e < n else str(2*n-e) for e in range(2*n+1) ]

Categories

Resources