Python How to make a number triangle - python

So I've recently started learning python and my friend gave me a changllege. How to make a number triangle. So basically, I need to make python let me input a number, for example 5. After I do that, I want python to print
54321
4321
321
21
1
But because I am new to python, I don't know how to do it.
So far, I've got this:
x = int(input('Enter a Number: '))
for i in range(x,0,-1):
print(i,end='')
if i != 0:
continue
else:
break
And the output is:
Enter a Number: 5
54321
Any ideas how to make it print
54321
4321
321
21
1
?
Thanks for any advice

Here is a sample code for you.
Short version (suggest learning about list comprehension and join functions):
x = int(input('Enter a Number: '))
for i in range(x, 0, -1):
print(''.join([str(j) for j in range(i, 0, -1)]))
Longer version which is easier to understand:
for i in range(x, 0, -1):
s = ''
for j in range(i, 0, -1):
s += str(j)
print(s)
Output:
54321
4321
321
21
1

rows = int(input("Inverted Right Triangle Numbers = "))
print("Inverted")
for i in range(rows, 0, -1):
for j in range(i, 0, -1):
print(j, end = ' ')
print()
Output
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

def trig_print(number):
if number > 0:
for i in range(number):
print(number - i,end='')
print('')
number = number - 1
trig_print(number)
else:
return 0
trig_print(5)

I used to solve it by while loop.
3 step
input initial number.
make list one to initial number.
reverse list and print it.
>>> x = int(input('Enter a Number: '))
Enter a Number: 5
>>> while x >0 :
l=list(range(1,x+1)) # range function
l.reverse() # list.reverse function
print(' '.join(map(str,l))) # join and map function
# I recomanded input space between number for readability.
x -= 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

Related

I need to put an on going "Row #x:" in a part of my code

So I'm pretty new to python and it's our first language in college. I am having a hard time putting the "Row #x:" in my code:
x = int(input("Enter the number of rows: "))
y = int(input("Enter the number of columns: "))
n=1
for i in range(x):
for j in range(y):
print(n, end=" ")
n = n+1
print()
Output:
Enter the number of rows: 3
Enter the number of columns: 3
1 2 3
4 5 6
7 8 9
So this is how it's supposed to look like if the "Row #x:" if its included:
Enter the number of rows: 3
Enter the number of columns: 3
Row #1: 1 2 3
Row #2: 4 5 6
Row #3: 7 8 9
The number of rows depends on how many rows the user has inputted. Anything to share with me on how am I supposed to do it?
you could do something like this:
for i in range(x):
print(f'Row #{i + 1}:', end=' ') # what you were missing to print the row numbers
for j in range(y):
print(n, end=' ')
n = n+1
print()
This is using f-strings, the i variable is +1 because you are starting at a 0 index
Below is the code
row = int(input("Enter number of row: "))
column = int(input("Enter number of column: "))
count = 1
for num in range(1, row*column+1):
print(num, end=" ")
if num == count*column:
print()
count += 1

How to write a python program for the Fibonacci series and need to show series in Pyramid?

I want to write a Program for the Fibonacci series and need to show series in Pyramid.
Enter (through command line) the number of times the Fibonacci has to iterate.
Ex:
Enter the number of times
6
Fibonacci Series of the number is: 0 1 1 2 3
Below is the expected output -
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
I have tried this code as below -
n= int(input("enter the number of rows: "))
a=0
b=1
for i in range(a,n):
a=0
b=1
print(b,end="")
for j in range(a,i-1):
c=a+b
print(c,end="")
a=b
b=c
print()
But this is giving below output
1
1
11
112
1123
11235
the above output starting from "1" but the expected output should start from "0"
Please help me with correct python code as expected
Thanks
Try:
n = int(input("Enter the number of rows: "))
fib = []
for i in range(n):
fib.append(fib[-2] + fib[-1] if i > 1 else i)
print(' '.join(str(x) for x in fib))
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
In your code, you are computing the Fibonacci sequence from zero again and again for each row, which is redundant. Instead, you can make a list and add one item at each iteration.
I've used join to insert a blank between entries, which I believe is more "pythonic."
It often makes for simpler code if you separate computation from doing pretty output. So construct your series first:
>>> series = [0,1]
>>> n = 6
>>> while len(series) < n:
series.append(series[-1]+series[-2])
>>> series
[0, 1, 1, 2, 3, 5]
Then do the output:
>>> sseries = [str(s) for s in series]
>>> sseries
['0', '1', '1', '2', '3', '5']
>>> for row in range(len(sseries)+1):
print (" ".join(sseries[:row]))
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
There is some small change that your code will require. You have to make end=" ", so that it will print space there.
n= int(input("enter the number of rows: "))
a=0
b=1
for i in range(a,n):
a=0
b=1
print(a, b,end=" ")
for j in range(a,i-1):
c=a+b
print(c,end=" ")
a=b
b=c
print()

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

For loop a square pattern of numbers

In this question I had to create a program that prompts the user for a number and then prompt again for how many rows to create. Something like:
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
This is what I came up with and I have tried many different ways to get the same result but it didn't work.
num=int(input("Enter a number between 1 and 10: "))
rows=int(input("Enter how many rows to of numbers: "))
for i in range(num):
print(i,end=" ")
for x in range(rows):
print (x)
This is the output I came up with:
Enter a number between 1 and 10: 6
Enter how many rows to of numbers: 4
0 1 2 3 4 5 0
1
2
3
You may simply do it like:
num = 5
rows = 4
for i in range(1, num+1):
print('{} '.format(i) * rows)
Output:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
Explanation: When you multiply a str with some number say n, new string is returned with original string repeated n times. Doing this you will eliminate your nested loop
Simple solution: Just use nested for loops:
num = int(input("Enter a number between 1 and 10: "))
rows = int(input("Enter how many rows to of numbers: "))
for i in range(num):
print ('\n')
for x in range(rows):
print (i + 1)
The code above will go through the range 0 to num, printing first a new line and then printing the current number rows times.
rows = 5
side = int(input("Please Enter any Side of a Square : "))
for i in range(side):
for j in range(side):
if(i == 0 or i == side - 1 or j == 0 or j == side - 1):
print(i, end = ' ')
else:
print(i, end = ' ')
print()

Reverse Multiplication Table

I'm having troubling reversing my multiplication table.
This is what I have so far:
def reverseTable(n):
for row in range(1, n+1):
print(*("{:3}".format(row*col) for col in range(1, n+1)))
But I want to reverse it to:
25 20 15 10 5
20 16 12 8 4
15 12 9 6 3
10 8 6 4 2
You need to reverse your range so it counts backwards. The range() function accepts 3 parameters, range(start, stop, step) so to count from 10 to 1 you would use range(10, 0, -1)
Try this:
def reverseTable(n):
for row in range(n, 0, -1):
print(*("{:3}".format(row*col) for col in range(n, 0, -1)))
for row in range(9,0,-1):
print(end="\t")
for column in range(9,0,-1):
print(row*column,end="\t ")
print()
reverse multiplication table in python taking value from user
num = int(input("enter the number= "))
i=10
while i>=1:
print(num,"X",i,"=",num*i)
i= i-1
output
enter the number= 3
3 X 10 = 30
3 X 9 = 27
3 X 8 = 24
3 X 7 = 21
3 X 6 = 18
3 X 5 = 15
3 X 4 = 12
3 X 3 = 9
3 X 2 = 6
3 X 1 = 3
num=int(input("enter your table number: "))
for i in range(10,0,-1):
print(str(num) + "x" + str(i) + "=" + str(num*i))
Here's your answer
num=int(input("Enter the number"))
for i in range (10,0,-1):
print(f"{num}*{i}={num*i}")
num = int(input("enter a no."))
count = 10
while count >= 1:
X = num*count
print(num, "x", count, "=", X)
count = count - 1
i used this i dont know if it is of any help to you since I am a beginner and have just started learning python
num= int(input("please enter the number: "))
n= 11
for i in range(0,10):
n -= 1
print(f"{num} x {n} = {num*n} ")

Categories

Resources