Please help. I need to create this pattern:
*
* $
* $ *
* $ * $
* $ * $ *
* $ * $
* $ *
* $
*
The best I can do is:
rows = 5
for i in range(0, 1):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")
for i in range(0, rows):
for j in range(0, i + 1):
d = "$"
print("*",d, end=' ')
print("\r")
for i in range(rows, 0, -1):
for j in range(0, i - 1):
print("*", d, end=' ')
print("\r")
But it is not what I need. I desperately need help.
You cna simplify a bit : a loop for the increase from 1 to 4, another for the decrease from 5 to 1, then depend on odd/even values choose the correct symbol
rows = 5
for i in range(1, rows):
for j in range(i):
print('*' if j % 2 == 0 else "$", end=" ")
print()
for i in range(rows, 0, -1):
for j in range(i):
print('*' if j % 2 == 0 else "$", end=" ")
print()
Can be done in one outer loop
rows = 3
for i in range(-rows + 1, rows):
for j in range(rows - abs(i)):
print('*' if j % 2 == 0 else "$", end=" ")
print()
Slightly different approach:
N = 5
result = []
for i in range(N):
s = [('*', '$')[j % 2] for j in range(i+1)]
result.append(s)
print(*s)
for i in range(N-2, -1, -1):
print(*result[i])
You can use the abs function to handle the inflection point with one loop:
print(
*(
' '.join(
'*$'[m % 2]
for m in range(rows - abs(rows - n - 1))
)
for n in range(2 * rows - 1)
),
sep='\n'
)
Or the above in one line, if you prefer:
print(*(' '.join('*$'[m % 2] for m in range(rows - abs(rows - n - 1))) for n in range(2 * rows - 1)), sep='\n')
Demo: https://replit.com/#blhsing/KnowledgeableWellwornProblem
Related
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.
I'm trying to get these shapes:
if num=9
*
* *
* *
* *
* *
if num=5
*
* *
* *
if num=3
*
* *
(Only odd inputs)
num = int(input())
for row in range(num):
for col in range((num*2)-1):
if row==0 and col==((num*2)-1)//2 or row==1 and (col==2 or col==6) or row==2 and (col==0 or col==8):
print('*', end='')
else:
print(end=" ")
print()
This is what I managed to write but the code is hardcoded to draw a pyramid of 5 stars, so giving it any other input would mess the shape
I got column and row from a quick sketch
based on this image
I would like to automate the code so any input I feed it, it would draw this specific pyramid shape. I need help, thank you.
Start thinking about how different properties relate to the input number, and make a variable for each one. Start with how many rows, and how many columns. Then think of an equation that can give you the star location based on the current column and row. This should be easy to determine from the diagram you posted.
num = int(input())
num_rows = (num // 2) + 1
num_cols = (num * 2) - 1
middle_col = num - 1
for row_index in range(num_rows):
left_star_col = middle_col - (2 * row_index)
right_star_col = middle_col + (2 * row_index)
for col_index in range(num_cols):
if col_index == left_star_col or col_index == right_star_col:
print("*", end="")
else:
print(" ", end="")
print() # newline
Here's a way with a helper list. For each row, place a star i steps left of the middle and i steps right of the middle:
half = num // 2
for i in range(half + 1):
row = [' '] * num
row[half-i] = row[half+i] = '*'
print(*row)
Output for num = 9 (Try it online!):
*
* *
* *
* *
* *
It prints a few spaces at the end of the upper lines. If that's troublesome, make the row just as long as needed:
half = num // 2
for i in range(half + 1):
row = [' '] * (half + i + 1)
row[half-i] = row[half+i] = '*'
print(*row)
If you replace the ' ' with '-', you can see more what's happening:
- - - - *
- - - * - *
- - * - - - *
- * - - - - - *
* - - - - - - - *
This should give you the output very close what you desire. When you run you may see the first '*' little bit off to the left, but you can adjust for that.
def pyramid(n):
ll = []
ct = 0
for row in range(n//2, -1, -1):
l = [''] * n
l[row] = '*'
l[row + ct] = '*'
ct += 2
ll.append(l)
print('\n'.join(' '.join(row) for row in ll))
With minor adjustment, below should give you exactly what you need.
def pyramid(n):
ll = []
ct = 0
for row in range(n//2, -1, -1):
l = [''] * n
l[row] = '*'
l[row + ct] = '*'
ct += 2
ll.append(l)
l.insert(n//2, '')
print('\n'.join(' '.join(row) for row in ll))
One option is to define the pyramid shape as a graph: of the form y = abs(x - offset) (interactive demo here)
This can be done in python like so:
num = int(input())
for row in range(num // 2 + 1):
for col in range(num * 2 - 1):
if 2 * row == abs(num - 1 - col):
print('*', end='')
else:
print(end=" ")
print()
Your row counter is too high, since num is the number of columns.
It's simpler if you treat row 0 specially, since it only has one * rather than 2.
Rather than looping over columns, calculate the number of spaces you need and print that many spaces using " " * count
for row in range(num//2 + 1):
if row == 0:
print((" " * (num//2)) + "*")
else:
print((" " * (num//2 - row)) + "*" + (" " * (row*4 - 1)) + "*")
I was trying to solve Leetcode#279.Perfect-Squares
When I tried i ** 2 in loops, I got Time Limit Exceed. But once I change it to i * i, the code was accepted, that means i * i is faster than i ** 2 in python
What principles in python3 caused this difference?
Code and result for reference:
Use j * j, AC, beats 23%
class Solution:
def numSquares(self, n: int):
if n < 2:
return n
dp = [n] * (n + 1)
dp[0] = 0
dp[1] = 1
for i in range(2, n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1)
j += 1
return dp[-1]
If change all j * j to j ** 2, TLE.
I want to get a number 'n' and produce Pythagorean triple that total of them is equal with 'n'.
for example for n=12 my output is 3, 4, 5 (12 = 3 + 4 + 5).
I write below code but it take a lot of time for big numbers. please help me to improve it.
a = int(input())
done = False
for i in range(int(a/4)+1,2,-1):
if done:
break
for j in range(i+1,int(a/2)+1):
k = a-(i+j)
if k <= j:
break
if i**2 + j**2 == k**2:
print(i,j,k)
done = True
break
if done == False:
print('Impossible')
This code may help you
limits = int(input())
c, m = 0, 2
# Limiting c would limit
# all a, b and c
while c < limits :
# Now loop on n from 1 to m-1
for n in range(1, m) :
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
# if c is greater than
# limit then break it
if c > limits :
break
if a+b+c == limits:
print(a, b, c)
m = m + 1
>> 12
>> 3 4 5
I've used the joblib module to parallelize your code, though I haven't tested if there is a speedup for very large n; let me know:
from joblib import Parallel, delayed
done = False
def triple(a):
global done
for i in range(int(a/4)+1,2,-1):
if done:
break
for j in range(i+1,int(a/2)+1):
k = a-(i+j)
if k <= j:
break
if i**2 + j**2 == k**2:
print(i,j,k)
done = True
break
if done == False:
print('Impossible')
if __name__ == '__main__':
a = int(input("n:"))
Parallel(n_jobs=-1, backend="threading")(map(delayed(triple), [a]))
To generate a Pythagorean triplet of a given sum, you can run two loops, where the first loop runs from i = 1 to n/3, the second loop runs from j = i+1 to n/2. In second loop, we check if (n – i – j) is equal to i * i + j * j.
n = int(input()
for i in range(1, int(n / 3) + 1):
for j in range(i + 1, int(n / 2) + 1):
k = n - i - j
if (i * i + j * j == k * k):
print(i, j, k)
This question already has answers here:
How to recreate pyramid triangle?
(3 answers)
Closed 5 years ago.
I am trying to print a triangle made of asterisk (*) separated by spaces.
If n = 4, it should look like:
*
* *
* * *
* * * *
This is the code I have:
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*")
This is the result I get:
*
*
*
*
*
*
*
*
*
*
I would very appreciate what is wrong with my code...
print() adds a newline to your string each time.
It is easier to multiply the * with the number of times you would like to see it:
n = 4
for i in range(1, n + 1):
print("* " * i)
Output:
*
* *
* * *
* * * *
You could use the built-in "end" parameter:
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
n = 4
for i in range(1, n + 1):
lvl = ""
for j in range(i):
lvl += "* "
print(lvl)
You need to aggregate the level of the triangle to print.
edit :
if you don't want spaces at the end of the line :-/
n = 4
for i in range(1, n+1):
print( " ".join([c for c in '*' * i]))