how do i use a while loop to print numbers on the same line of output? - python-3.x

n = 10
while n > 0:
print(n)
n=n-1
so far i have this which gives me
10
9
8 7 6 5 4321
but I want 10 9 8 7 6 5 4 3 2 1

You should use the 'end' parameter of print. By default, end="\n" in print, a newline character
n = 10
while n > 0:
print(n, end=" ")
n=n-1

There are several ways you could do that.
Firstly, and probably the simplest, you can use the end argument of print().
For instance, you could do something like this:
n = 10
while n > 0:
print(n, end=" ") # note the 'end' argument
n=n-1
Which gives : 10 9 8 7 6 5 4 3 2 1 (with a trailing space and without carriage return).
Another way I can think of, but involves a bit more complexity in my opinion, is using join().
Example:
print(" ".join(str(i) for i in range(10, 0, -1)))
Which gives : 10 9 8 7 6 5 4 3 2 1 (with a carriage return and without trailing space).

Related

Program to produce the following pattern

I am trying to print
2
1 3
2 4 6
1 3 5 7
2 4 6 8 10
I am not sure how to do it ,I could use print (...) And write everything but that is just stupid.
Is there a better way to do this?
for i in range(0, 5):
for j in range(0, i+1):
if i % 2 == 0:
print((j+1)*2, end=' ')
else:
print((j*2)+1, end=' ')
print()
maybe you can try this:
>>> def pattern_gen(layer):
... for i in range(layer):
... pattern=''
... start=(i+1)%2+1
... end=(i+(i+1)%2+1)*2
... for j in range(start,end,2):
... pattern+=f'{j} '
... print(pattern)
...
>>> pattern_gen(5)
2
1 3
2 4 6
1 3 5 7
2 4 6 8 10

Printing Pattern in Python

1. The Problem
Given a positive integer n. Print the pattern as shown in sample outputs.
A code has already been provided. You have to understand the logic of the code on your own and try and make changes to the code so that it gives correct output.
1.1 The Specifics
Input: A positive integer n, 1<= n <=9
Output: Pattern as shown in examples below
Sample input:
4
Sample output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Sample input:
5
Sample output:
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
2. My Answer
2.1 My Code
n=int(input())
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t)
for a in answer:
a.insert(0,i)
a.append(i)
print(answer)
outlst = [' '.join([str(c) for c in lst]) for lst in answer]
for a in outlst:
print(a)
2.2 My Output
Input: 4
4 4 4 4 4 4 4 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 3 2 1 2 3 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 4 4 4 4 4 4 4
2.3 Desired Output
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Your answer isn't as expected because you add the same object t to the answer list twice:
answer.insert(0, t)
answer.append(t)
More specifically, when you assign t = [i]*(2*i - 3), a new data structure is created, [i, ..., i], and t just points to that data structure. Then you put the pointer t in the answer list twice.
In the for a in answer loop, when you use a.insert(0, i) and a.append(i), you update the data structure a is pointing to. Since you call insert(0, i) and append(i) on both pointers that point to the same data structure, you effectively insert and append i to that data structure twice. That's why you end up with more digits than you need.
Instead, you could run the loop for a in answer for only the top half of the rows in the answer list (and the middle row that has was created without a pair). E.g. for a in answer[:(len(answer)+1)/2].
Other things you could do:
using literals as the arguments instead of reusing the reference, e.g. append([i]*(2*i-3)). The literal expression will create a new data structure every time.
using a copy in one of the calls, e.g. append(t.copy()). The copy method creates a new list object with a "shallow" copy of the data structure.
Also, your output digits are space-separated, because you used a non-empty string in ' '.join(...). You should use the empty string: ''.join(...).
n=5
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t.copy())
for a in answer:
a.insert(0,i)
a.append(i)
answerfinal=[]
for a in answer:
answerfinal.append(str(a).replace(' ','').replace(',','').replace(']','').replace('[',''))
for a in answerfinal:
print(a)
n = int(input())
for i in range(1,n*2):
for j in range(1,n*2):
if i <= j<=n*2-i: print(n-i+1,end='')
elif i>n and i>=j >= n*2 -i : print(i-n+1,end='')
elif j<=n: print(n-j+1,end="")
else: print(j-n+1,end='')
print()
n = int(input())
k = 2*n - 1
for i in range(k):
for j in range(k):
a = i if i<j else j
a = a if a<k-i else k-i-1
a = a if a<k-j else k-j-1
print(n-a, end = '')
print()

To print a pattern in Python using 'for' loop

I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
Input:
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
Output:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Required Output:
1
2 3
4 5 6
7 8 9 10
Can I get some hint to get the required output?
Note- A newbie to python.
Store the printed value outside of the loop, then increment after its printed
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, triangle numbers:
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t = triangle(line)
print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10

Python how to print 1D list as 2D

I want to print a list [1,2,3,4,5,6,7,8,9] as
1 2 3
4 5 6
7 8 9
Here is my code
for i,j in enumerate(list):
if i is not 0 and i % 3==0:
print()
else:
print(j,end=" ")
My result is
1 2 3
5 6
8 9
Can someone help explain why this happen and give me some advise?
You should print the list item j unconditionally instead of doing it only when you are not printing a newline:
l = [1,2,3,4,5,6,7,8,9]
for i,j in enumerate(l):
if i is not 0 and i % 3==0:
print()
print(j,end=" ")
You can do:
tgt=[1,2,3,4,5,6,7,8,9]
n=3
print('\n'.join([' '.join(map(str, sl)) for sl in [tgt[i:i+n] for i in range(0,len(tgt),n)]]))
Prints:
1 2 3
4 5 6
7 8 9

Align two strings perfectly (python)

Is it possible to align the spaces and characters of two strings perfectly?
I have two functions, resulting in two strings.
One just adds a " " between a list of digits:
digits = 34567
new_digits = 3 4 5 6 7
The second function takes the string and prints out the index of the string, such that:
digits = 34567
index_of_digits = 1 2 3 4 5
Now the issue that I am having is when the length of the string is greater than 10, the alignment is off:
I am supposed to get something like this:
Please advice.
If your digits are in a list, you can use format to space them uniformly:
L = [3,4,2,5,6,3,6,2,5,1,4,1]
print(''.join([format(n,'3') for n in range(1,len(L)+1)]))
print(''.join([format(n,'3') for n in L]))
Or with f-string formatting (Python 3.6+):
L = [3,4,2,5,6,3,6,2,5,1,4,1]
print(''.join([f'{n+1:3}' for n in range(len(L))]))
print(''.join([f'{n:3}' for n in L]))
Output:
1 2 3 4 5 6 7 8 9 10 11 12
3 4 2 5 6 3 6 2 5 1 4 1
Ref: join, format, range, list comprehensions

Resources