About new line and space after last row and last column respectively - python

What I must get as output, exactly like this :
Example-1:
Input:
3
Output:
1\n
1 2\n
1 2 3
Example-2:
Input:
4
Output:
1\n
1 2\n
1 2 3\n
1 2 3 4
In the first example the input was 3. Hence there are 3 rows. The first row has element 1. The second row contains two elements 1 and 2 and the third row contains 1, 2 and 3 separated by a space.
What I actually get to: Example 1- 1 \n Example 2 - 1 \n
the below code and I don't 1 2 \n 1 2 \n
want this as an output 1 2 3 \n 1 2 3 \n
1 2 3 4 \n
There should not be any space after the each element of the last column and no new line after the last row.
My code:
n = int(input())
i=1
j=1
for i in range(1,n+1):
for j in range(1,i+1):
if i>=j:
print(j, end=" ")
if(i!=j):
print(end="")
print()

You can use:
N = 5
result = '\n'.join(
# space delimited numbers from 1 to current loop
' '.join(str(i) for i in range(1, j))
# for everything for 1..2, 1..3, 1..4 etc...
# since range(1,1) is empty and we're starting from 2,
# we use N+2 to ensure all loops are counted
for j in range(2, N + 2)
)
Which'll give you:
'1\n1 2\n1 2 3\n1 2 3 4\n1 2 3 4 5'
​

lst_number= []
my_input = int(input("Enter Number:: "))
for i in range(0,my_input):
for j in range(i+1):
lst_number.append(j)
print(''.join([str(val) for val in lst_number]))

In case you are wondering, this is how I want my pattern output to be:
Example-1:
Input:
3
Output:
1\n
1 2\n
1 2 3
Example-2:
Input:
4
Output:
1\n
1 2\n
1 2 3\n
1 2 3 4

You're going to want to have a start state and an adding state. The adding state is pre-pended with a space. Each adding state is appended to the start state in turn. When you're done with the row, append a new line character.
start state: "1"
adding state: " " + n
roll over an array from 2 to n, append the changed adding state to the current answer
append end of line character
In Javascript...
var start = 1
var limit = 4
for(var i = 1; i <= limit; i++){
let retval = start;
for (var j = 2; j <= i; j++){
retval = retval + ' ' + j;
}
if (i < limit)
retval = retval + '\\n';
$('<div>' + retval + '</div>').appendTo('#out');
}
https://jsfiddle.net/etLms32o/6/

Try this.It worked for me.
n = int(input())
for i in range(1,n+1):
count = 1
for j in range(1,i+1):
if j == i:
print(count,end = "\n")
count+=1
else:
print(count,end = " ")
count+=1

a,b=map(int,input().split())
n=0
for i in range(a):
for j in range(b):
n=n+1
if(j<(b-1)):
print(n,end =' ')
elif(n==a*b):
print(n,end ='')
else:
print(n)

Related

Python How to make a number triangle

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

User input matrix but wrong output using phython

so basically, I want to make an automatic matrix input and generate the output but the second part of the input shows up with the same output as the first one. is there any wrong logic behind my code? here's my code (im sorry for bad english):
#input menu 2 :
def prgmatriks2() :
ct = 2
for a in range(ct):
m = int (input("input row "+str (a)+": "))
n = int (input("input column"+str (a)+": "))
# initialization matriks
matrix = []
print("Matriks input: ")
#Input :
for x in range(ct) :
for i in range(m): #rows loop
a =[]
for j in range(n): #column loop
a.append(int(input()))
matrix.append(a)
# Print Matriks
for x in range(ct) :
for i in range(m):
for j in range(n):
print(matrix[i][j], end = " ")
print()
and for the output:
output
text version:
Pilihan menu(1-2):
2
input row 0: 2
input column0: 2
input row 1: 2
input column1: 2
Matriks input:
3
2
4
1
6
5
2
1
3 2
4 1
3 2
4 1
instead generate :
3 2
4 1
6 5
2 1
the program repeat the first output :
3 2
4 1
3 2
4 1
print(matrix[i][j], end=" ") replace here i with i+x*n.
So logic for printing Matrices will be like this code :
# Print Matrices
for x in range(ct):
for i in range(m):
for j in range(n):
print(matrix[x*n+i][j], end=" ")
print()
print()
print(matrix)
OUTPUT :
3 2
4 1
6 5
2 1

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

Number half Pyramid Python

I'm trying to print a half pyramid that stars on the left side in python.
So far, this is my code
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in range(1, i):
print(j, end = " " )
print("\n")
and my output is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
However, my output is meant to be in the opposite order:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How can I make this change?
Just reverse the second loop -- the one that prints that actual numbers:
for j in range(i-1, 0, -1):
The last parameter controls the "step", or how much the variable changes on each loop iteration. Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
...
Reverse the range by adding the third argument (-1). Also format your numbers to use 2 places, so 10 is not pushing the last line to the right. Finally, the last print should probably not have \n, since that is already the default ending character of print:
for i in range(1,12):
for j in range(12 - i):
print(" ", end = "")
for j in range(i-1, 0,-1):
print(str(j).rjust(2), end = "" )
print()
You could just reverse the range that you print out as numbers
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in reversed(range(1, i)):
print(j, end = " " )
print("\n")
The problem is in your second for loop, as you are looping from 1 to i, meaning you start off with 1 being printed first, and every following number until (not including) i.
Fortunately, for loops are able to go in reverse. So, instead of:
for j in range(1, i)
You could write:
for j in range((i-1), 0, -1)
Where the first parameter is signifies where the loop starts, the second is where the loop finishes, and the third signifies how large our jumps are going to be, in this case negative. The reason we are starting at i-1 and finishing at 0 is because loops start at exactly the first given number, and loop until just before the second given number, so in your given code the loop stops just before i, and so this one starts just before i as well, although you could remove the -1 if you wish to include 12 in the pyramid.

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()

Categories

Resources