python asterisk triangle without using y* "*" - python

I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is

This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s

This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")

I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.

There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.

Related

How to Delete Strings from Strings in Python

I am currently trying out Python. I was trying to print out an upside-down pyramid. I'm making the pyramid out of *s and in each line, I have to delete a certain amount of *s from the line. This is my
space = ""
astr3 = "**********"
placeholder2 = 1
while placeholder2 < 10:
print (space, astr3, "\n")
space += " "
astr3 = "*********" #this is supposed to be subtraction
placeholder2 += 1
Please tell if there is any way to delete strings from strings.
You can use list slicing to slice Strings/Lists. Check it out. You don't need \n in the print statement as it adds a newline. To make a pyramid using your logic, you can delete two * from the string and then print. Remember, it's always better to use intuitive names for the variables. Eg: you can use, idx for index instead of placeholder2.
# Program to print an upside down pyramid
space = ""
astr3 = "**********"
num_stars = len(astr3) # len(astr3) gives number of * in the astr3 string
placeholder2 = 1
while placeholder2 < num_stars // 2:
display_str = space + astr3 # Adding strings is called concatnation.
print(display_str) # This will not add additional space between spaces and astr3
space += " "
astr3 = astr3[:-1] # deleting the last element from the list. Called list slicing
astr3 = astr3[1:] # deleting the first element from the list. Called list slicing
placeholder2 += 1
The above code outputs the following:
**********
********
******
****
**
TIP: It's better to share the expected output in the question so that the community can help.
Initialize placeholder2 with 0 to get the pyramid from the original string to 1 length string. Since your requirements were to remove the string 1 by per line. To do it set the condition astr3[:-1] and put it to the same variable.
space = ""
astr3 = "**********"
placeholder2 = 0
while placeholder2 < 10:
print(space, astr3)
space += " "
astr3 = astr3[:-1]
placeholder2 += 1
Output
**********
*********
********
*******
******
*****
****
***
**
*
Thank you guys for all the help! I took what you guys said and made the pyramid :D (although my code is very very dumbed down). Here is the code:
space1 = ""
astr4 = "**********"
placeholder3 = 1
while placeholder3 < 7:
if placeholder3 == 6:
print (space1, "*")
print(space1, astr4)
astr4 = astr4[1:]
astr4 = astr4[:-1]
space1 += " "
placeholder3 += 1

How to remove trailing spaces using rstrip from a string made from a loop

I want to write a program that prints a word 3 times. The first two iterations should have a space after them, but the 3rd line shouldn't.
Example of desired output: https://imgur.com/43pYOI9
This is the code I'm trying:
n = input("Enter a word: ")
for x in range(len(n)):
print((n[x]+" ")*3)
n.rstrip()
This is the output I'm getting - rstrip() doesn't seem to be working.
https://imgur.com/a/NM1uEQI
Any suggestions on how to fix this?
You need to rstrip() before you print and you need to rstrip() what you are actually printing, not the whole line. This would work
n = input("Enter a word: ")
for x in range(len(n)):
s = (n[x] + " ") * 3
print(s.rstrip())
A better way would be to use join()
n = input("Enter a word: ")
for x in range(len(n)):
print(" ".join(n[x] * 3))
And you can iterate over string directly, so this would also work
n = input("Enter a word: ")
for x in n:
print(" ".join(x * 3))
Or you could get clever and do something like this
n = input("Enter a word: ")
list(map(print, [" ".join(i * 3) for i in n]))
You almost had it. You're calling rstrip() after the print line which has no impact since it's already been printed.
n = input("Enter a word: ")
for x in range(len(n)):
print((n[x]+" ")*2 + n[x])

How return x character of a string WITHOUT *

my question , Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.) .
My code:
def generate_n_chars(c, n):
d = ""
c = raw_input("Give a character: ")
n = raw_input("Give a word: ")
for i in n:
if i not in c:
d += i
return d
print ("You word have " + str(generate_n_chars('c', 'n') + " character"))
so, when I write hallo a come only a x , and I will five , because hallo have five words.I will to come xxxxx but WITHOUT '5 * x' .Very Thanks for yours help!
The question is asking you to create a function(def) named generate_n_chars() that takes an integer(int) value,n and character(char) value,c as parameters. Here, c is any character input by user,lets say user inputs x and n is how many times the character(c) should be printed so lets say user wants it to print 5 times and therefore inputs 5. Then the result would be xxxxx. 5 x's.
def generate_n_chars(n, c):
result = ""
for i in range(n):
result += c
return result
inputChar = input("Enter the character:")
inputNum = int(input("Enter the number of times " + str(inputChar) + " to be printed:"))
print("Result: " + str(generate_n_chars(inputNum, inputChar)))
Output:
Enter the character:x
Enter the number of times x to be printed:5
Result: xxxxx
You can loop a while loop to count till n and break out once the number has been reached.
def generate_n_chars(n , c):
for i in range(len(c)):
while i <= n:
print(c[i])
i+=1
break
def main():
generate_n_chars(5,"this is")
main()
You can simply use function rjust....
"".rjust(10,"5")
In your example:
print ("You word have " + "".rjust(5, 'x') + " character")

Python: print specific character from string

How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word, the word will be printed with all the undiscovered letters as "-".
I am not asking for a way to make my idea/code of the whole project better, just a way to, as i said, print that one specific character of the string.
print(yourstring[characterposition])
Example
print("foobar"[3])
prints the letter b
EDIT:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(str(c) + " " + mystring[c]);
Outputs:
2 l
3 l
9 l
And more along the lines of hangman:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(mystring[c], end="")
elif mystring[c] == " ":
print(" ", end="")
else:
print("-", end="")
produces
--ll- ---l-
all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e.
text="hello"
print(text[0])
print(text[2])
print(text[1])
returns:
h
l
e
Well if you know the character you want to search you can use this approach.
i = character looking for
input1 = string
if i in input1:
print(i)
you can change the print statement according to your logic.
name = "premier league"
for x in name:
print(x)
Result shown below:-
To print specific characters of the given string. For example to print 'l' from the given string
name = "premier league"
for x in name:
if x == "l":
print("element found: "+x)

New to python (and programming) need some advice on arranging things diagonally

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

Categories

Resources