I have begun programming with Python and I made this simple program drawing stars in the shape of the pyramid:
print("Put in the number of stars")
row = int(input())
letters = "python"
for i in range(row):
stars = i*2-1
spaces = row - i
print(" "* spaces + "*"* stars)
How can I make this pyramid out of the word python instead of stars? I mean this:
p
pyt
python
pythonpyt
pythonpytho
and so on?
Thanks for help guys.
You can use itertools.cycle and itertools.islice to build the rows:
from itertools import islice, cycle
n = 5
for i in range(n):
print((n-i)*' ' + ''.join(islice(cycle('python'), 2*i+1)))
prints:
p
pyt
pytho
pythonp
pythonpyt
Modification to the original post:
print("Put in the number of stars")
row = int(input())
letters = "python"
l = letters * row
for i in range(1, row + 1):
stars = i*2-1
p = l[0:stars]
spaces = row - i
print(" "* spaces + p)
output:
Put in the number of stars
10
p
pyt
pytho
pythonp
pythonpyt
pythonpytho
pythonpythonp
pythonpythonpyt
pythonpythonpytho
pythonpythonpythonp
Related
How the loop should iterate. I'm a beginner trying to create a Python program to print a word backwards based on old knowledge from a few years ago. It does a few other things but they are just printed statements are don't pose a problem. Here is my code:
count = 0
while count < 100:
word_var = input("Enter ONE word with NO spaces:")
def split(word_var):
return list(word_var)
word_array = split(word_var)
m = 0
i = len(word_array)-1-m
print("The number of letters in your word is:", i)
while m < len(word_array):
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
print(''.join(word_array))
count = count + 1
print("You've typed:",count,"word(s).")
Here is the problem section:
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
My main problem is that it seems like the second while loop is not iterating when the word is more than five letters long. For example, if I input the word "should" into the program I get back out dhouls. It seems as if only one interchange of letters is being performed. I figure this is a problem with the if statement in that nested while loop, but I can't seem to find what is wrong with it. I carefully sketched out how I think the if statement works in the photo attached.
Your if condition is wrong. You want to compare the two indices that you will use in the list, but the second one is not i, but i-m. So change it to:
if m < i - m:
This corrects your issue. It should be noted that in Python you can reverse string just like this:
print(word_var[::-1])
There are two issues:
The counting of the letters isn't correct. You should just output the length of word_array.
You're iterating the while loop too many times. You should terminate it when m equals or exceeds len(word_array) // 2. Otherwise, you'll unreverse the letters and get the original word back.
i = len(word_array)-1
print("The number of letters in your word is:", len(word_array))
while m < len(word_array) // 2:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
This outputs:
Enter ONE word with NO spaces:should
The number of letters in your word is: 6
dluohs
You've typed: 1 word(s).
I like your project and appreciate your efforts.
This a another way to reverse a string using a list variable and the insert() method.
word_array = []
word_var = input('Your word : ')
word_array = []
for c in word_var:
word_array.insert(0, c)
word_reversed = ''.join(word_array)
print(word_var, '->', word_reversed)
output :
should -> dluohs
How to print the pattern like this:
(need to print n-1 lines)
input=3
----#
--#-#-#
input=6
----------#
--------#-#-#
------#---#---#
----#-----#-----#
--#-------#-------#
My code:
row = int(input())
for i in range(1, row):
for j in range(1,row-i+1):
print("-", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
print("#", end="")
else:
print("-", end="")
print()
MY OUTPUT:
input=5
----#
---#-#
--#---#
-#-----#
Please explain how to do??
There are a few things missing and to be improved in your code:
There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"
They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "#" in between.
You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.
Personally, since the first line is going to have one "#" and not three, I prefer to calculate it and print it separately.
With these improvements, a solution to your problem could be:
row = int(input())
print("-" * (row - 1) * 2 + "#")
for i in range(row - 2, 0, -1):
left_hyphens = "-" * i * 2
mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
print(left_hyphens + "#" + mid_hyphens + "#" + mid_hyphens + "#")
row = int(input())
for i in range(1, row):
for j in range(1,2*(row-i)+1):
print("-", end="")
for j in range(1, 4*i):
if j==1 or j==2*i-1 or j==4*i-3:
print("#", end="")
elif j<=4*i-3:
print("-", end="")
print()
I have a 2d list [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] and I want to print it out to match the following format.
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
It should not be hard coded and the length of the list = n so this list n=4 but if list n=5 there would be 5 digits per row and the number on the sides would go 0,1,2,3,4.
So far all I have is:
for row in board:
for column in row:
print(column, end="")
print("")
Which only outputs the list as:
1234
4331
3211
2221
please help me add all the special stuff.
so I find a solution for what you want to do however I think it can be improved a lot (not program quite a lot in python), but I'll leave it here anyways :)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
Well for the first line you pretty much print 2 spaces, followed by all the digits between 0 and the number of columns in your board. You can use the "range" function for this. Then you must print the correct amount of 'X'. The correct amount is number of columns + 4, I think you can see why.
You should keep a counter starting from 0. For each row you print, you must print the string value of the counter, followed by an asterisk(*), followed by your row, followed by an asterisk(*) and finally followed by the same counter value. You must increment the counter by one for each row.
The last 2 rows are the same as top 2.
I do not want to share my code because this is such a simple problem, I think solving it on your own will help you in the long run.
Probably an unpopular opinion, but I think these kinds of problems are really fun.
This solution formats the contents correctly, even if you change the number of rows, and even the number of items in each row.
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
Edited to remove my own tests and to reflect given problem.
I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh
My desired output is two half pyramids separated by two spaces.
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print("", end=" "*spaces)
print("#", end=" "*hashes)
print(" ", end="")
print("#" * hashes)
However, this ends up printing only the first hashes of each row on the left pyramid. If I get rid of the end= in line 7, the pyramids are both printed correctly, but with newlines after each row. Here are the outputs:
With end=:
# ##
# ###
# ####
# #####
Without end=:
##
##
###
###
####
####
#####
#####
All I want now is to have the second output, but without the newlines.
The most straightforward way to print any output you want without newlines is to uses sys.stdout.write. This writes a string to the stdout without appending a new line.
>>> import sys
>>> sys.stdout.write("foo")
foo>>> sys.stdout.flush()
>>>
As you can see above, "foo" is written with no newline.
You're multiplying the end parameter by the number of hashes, instead of multiplying the main text portion.
Try this modification:
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print(" " * spaces, end="")
print("#" * hashes, end="")
print(" ", end="")
print("#" * hashes)
Try this algorithm:
length = int(input("Enter size of pyramid."))
# Build left side, then rotate and print all in one line
for i in range(0, length):
spaces = [" "] * (length - i - 1)
hashes = ["#"] * (1 + i)
builder = spaces + hashes + [" "]
line = ''.join(builder) + ''.join(builder[::-1])
print(line)