I need help making a mirrored right triangle like below
1
21
321
4321
54321
654321
I can print a regular right triangle with the code below
print("Pattern A")
for i in range(8):
for j in range(1,i):
print(j, end="")
print("")
Which prints
1
12
123
1234
12345
123456
But I can't seem to find a way to mirror it. I tried to look online on how to do it but I can't seem to find any results for python and only examples for Java.
Here is one using the new f-string formatting system:
def test(x):
s = ""
for i in range(1,x+1):
s = str(i) + s
print(f'{s:>{x}}')
test(6)
Something like this works. I loop over the amount of lines, add the whitespace needed for that line and print the numbers.
def test(x):
for i in range(1,x+1):
print((x-i)*(" ") + "".join(str(j+1) for j in range(i)))
test(6)
Related
I am having trouble with my assignment.
Print out a 3x3 matrix of “-”s using for loops.
It should look like this:
- - -
- - -
- - -
This is the closest I have come but it's not working
x = "-"
for i in range(3):
for n in range(3):
for x in range(3):
print x,
You will need nested for loops to accomplish this.
I have been trying this for an hour with no luck, can someone please point me in the right direction?
for i in range(21/7):
print ' '.join(['-' for _ in range(264/88)])
In your code, x is defined to be -, so you shouldn't enumerate over it.
I edited your code to produce a working version.
Note that in the internal loop you need to put spaces between the -, while in the external loop you want to move to the next line.
Here is the code for python 3:
x = "-"
for i in range(3):
for n in range(3):
print(x, end=' ')
print('\n')
Here is the code for python 2:
x = "-"
for i in range(3):
for n in range(3):
print x,
print('\n')
Very good start!
Let's think through, what were you trying to achieve with your 3rd loop.
(Hint: you don't need a third loop).
If you talk out what you need to happen it becomes:
1) print a "- " three times. (inner loop)
2) print a new line
3) now go back and repeat steps 1) and 2) three times (outer loop)
That would only be 2 loops, not 3.
Try This:
x = "- "
for i in range(3):
for n in range(3):
print x,
print "\n"
You could even shorten this to
for i in range(3): # print the following line 3 times
for n in range(3): # print 3 dashes, separated by a space
print "- ",
print "\n" # begin a new line
BTW, print x, is proper if using Python 2, but for Python 3, it will need to be changed to print(x, end='').
construct a matrix using nested loop:
matrix = [[],[],[]]
for x in range(0,3):
for y in range(0,3):
matrix[x].append("-")
then print it:
for i in range(3):
print(matrix[i])
I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:
for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
The output looks like:
0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
Instead I'd like it to be:
0 1 2 3 4
| | | | |
1 2 3 4 5
But I can't get how to do it. Thanks for the help.
Try with list concaternation:
x = 5
print (" ".join(str(i) for i in range(x)))
print ('| '*x)
print (" ".join(str(i) for i in range(1,x+1)))
import sys
myRange = range(5)
for i in myRange:
sys.stdout.write(str(i))
print()
for i in myRange:
sys.stdout.write('|')
print()
for i in myRange:
sys.stdout.write(str(i+1))
print()
You need sys.stdout.write to write without \n. And this code will not work if you have range more than 9 (10+ has 2+ chars, so you need special rules for spaces before |).
Just to throw in a fun (but bad, don't do this) answer:
for i in range(5):
print('{}\033[1B\033[1D|\033[1B\033[1D{}\033[2A'.format(i, i+1), end='')
print('\033[2B')
This uses terminal control codes to print column by column rather than row by row. Not useful here but something that's good to know about for when you want to do weirder terminal manipulation.
You can only print one line at a time. So first you'll have to print the line with all the a elements, then the line with all the bars, and finally the line with all the b elements.
This can be made easier by first preparing every line before printing it:
line_1 = ""
line_2 = ""
line_3 = ""
for i in range(5):
line_1 += str(i)
line_2 += "|"
line_3 += str(i+1)
print(line_1)
print(line_2)
print(line_3)
There are of course many ways with the same basic idea. I picked the one that is (IMHO) easiest to understand for a beginner.
I didn't take spacing into account and once you do, it gets beneficial to use lists:
line_1_elements = []
line_2_elements = []
line_3_elements = []
for i in range(5):
line_1_elements.append(str(i))
line_2_elements.append("|")
line_3_elements.append(str(i+1))
print(" ".join(line_1_elements))
print(" ".join(line_2_elements))
print(" ".join(line_3_elements))
Similar to Tim's solution, just using map instead of the genrators, which I think is even more readable in this case:
print(" ".join(map(str, range(i))))
print("| " * i)
print(" ".join(map(str, range(1, i+1))))
or alternatively, less readable and trickier, a heavily zip-based approach:
def multi(obj):
print("\n".join(" ".join(item) for item in obj))
r = range(6)
multi(zip(*("{}|{}".format(a, b) for a, b in zip(r, r[1:]))))
What's your goal here? If, for example, you print up to n>9, your formatting will be messed up because of double digit numbers.
Regardless, I'd do it like this. You only want to iterate once, and this is pretty flexible, so you can easily change your formatting.
lines = ['', '', '']
for i in range (5):
lines[0] += '%d ' % i
lines[1] += '| '
lines[2] += '%d ' % (i+1)
for line in lines:
print line
I've done this in python. When I insert a word, it'll repeated with after a digit
For Example if I insert stack, it-ll print:
stack 1
stack 2
stack 3
stack 4
stack 5
stack 6
stack 7
stack 8
stack 9
I want that python to print the name and the digit in a file text. I searches but didn't find anything.
Code:
pwd=raw_input("Enter a word:")
n=0
n=str(n)
print (pwd,n)
while n<9:
out_file=open("tesxt.txt","w")
n+=1
out_file.write(pwd)
out_file.write(n)
out_file.close()
I want that python to write the words that are generated from the loop.
Thx for the help
First in Python 2.7 print is used without the bracket:
>>> print "hello world"
hello world
Then you should open the file outside the while loop.
out_file = open("test.txt", "w")
i = 0
while n < 9:
# do something here
out_file.close()
Your issue is in redefining n. You start with n as an integer (n = 0), then turned it into a string (n = str(n)).
Try this:
pwd = raw_input("Enter a word: ")
n = 0
print("{} {}".format(pwd, n))
with open("test.txt", "w") as out:
while n < 9:
out.write("{} {}\n".format(pwd, n))
n += 1
That should give you the output you expect, because you never redefine n.
If you want to be both python 2 and 3 compliant, add from __future__ import print_statement to the top of the script, which will allow your print() call to work properly.
You have a few errors:
You try to += 1 on a str object. That's a no-no.
You open a file several times without closing it.
Try taking advantage of the context manager that open uses with a while loop inside. Something like this:
pwd = raw_input("Enter a word: ")
with open("tesxt.txt", "w") as fout:
n = 0
while n <= 9: # this will print 0-9. without the =, it will print 0-8
data = "{} {}".format(pwd, n)
print(data)
fout.write("{}\n".format(data))
pwd = raw_input('Enter a word:')
n = 0
print pwd, n
with open('tesxt.txt','w') as out_file:
while n < 9 :
n += 1
out_file.write('{} {}\n'.format(pwd, n))
I'm beginner in Python.
I am having difficulty resolving my problem:
Using nested for loops, print a right triangle of the character T on
the screen where the triangle is one character wide at its narrowest point and seven characters wide at its widest point:
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
and
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Any idea?
I won't write a code for you but I can give you some hints:
nested loops means a loop inside another loop, in this case one loop is for iterating through consecutive lines, the second is to print characters in each line
the second example needs the same as the first, but you also need to check index of the inner loop and decide whether print space or 'T' character
I hope you already have got the answer :)
Pattern # 1
def triangle(n):
for i in range(1, n +1):
print ('T' * i).rjust(n, ' ')
triangle(7)
##Results >>>
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern # 2
def triangle1(n):
for i in range(1, n +1):
print ('T' * i)
triangle1(7)
# Results >>>>
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern generation by using only for loops
Here I have tried to generate the with the help of only for loops and will very generalized way. Purposefully I have not used any readily available functions so you can always optimize it further.
Pattern # 1
def triangle(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
s += "T"
print s
triangle(7)
Pattern # 2
def triangle1(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
blank = ""
# Generate 'blank spaces'
for k in (range(n - i)):
blank += " "
# Generate 'T'
s += "T"
print blank + s
triangle1(7)
I'm finishing up an assignment for my 1035 computer science lab and the last thing I need to do is arrange inputted numbers in a diagonal line.
I've tried things like:
print (\tnum2)
and like this:
print ('\t'num2)
but I can't figure out how to do it. I've looked through my programming book, but have been unable to find an explanation on how to do it.
strings in python can be concatenated using the + sign. For example
print(' ' + str(a))
will give the following output for a=1
1
Notice the single blank space before 1. The function str(a) returns the integer a in string format. This is because print statement can only print strings, not integers.
Also
print(' ' * i)
prints i blank spaces. If i = 10, then 10 blank spaces will be printed.
So, the solution to the question can be:
a = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
print((' ' * i) + str(a[i]))
Here's a simple example that prints items in a list on a diagonal line:
>>> l = [1,2,3,4,5]
>>> for i in range(len(l)):
... print("\t" * i + str(l[i]))
...
1
2
3
4
5
You can also do it using .format
nome = input("nome:")
a = " "
b = len(nome)
for i in range(b):
print ("{0} {1}".format(a * i, nome[i]))
print ("\n next \n")
c=b
for i in range(b):
print ("{0} {1}".format(a * c, nome[i]))
c = c-1
this give diagonal increasing or decreasing