I am trying to create this pattern in python:
*
* *
* * *
* *
*
This is my program so far that I've come up with:
ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
What am I doing wrong?
Okay, first of all you can create a list of numbers which represents the number of stars in each line.
number_of_stars = 5
i_list = list(range(number_of_stars))
# extend the list by its inverse i_list[::-1]
# but exclude the first item
i_list.extend(i_list[::-1][1:])
print(i_list) # prints: [0, 1, 2, 3, 4, 3, 2, 1, 0]
Now you can go thru the list and print a multiple of *
for i in i_list:
print('* ' * i)
But this is not aligned properly. By adding multiple empty spaces to the left one can archive a solution:
for i in i_list:
print(' ' * (number_of_stars - i) + '* ' * i)
Note that in python one can repeat a string by using the multiplication symbol:
print('a'*5) # prints: aaaaa
Thank you for the help, I wrote a functional code for the problem. It was supposed to made using while loop(s).
This is what I did:
width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*width-i)
i = i + 1
Notice you have
3 spaces for 1 star
2 spaces for 2 stars
1 space for 3 stars.
For the upright triangle part of your diamond (including the large part). Then you have
2 spaces for 2 stars
3 spaces for 1 star
Without throwing out the answer, try analysing a certain pattern in what i've just pointed out. It can be achieved with 2 loops ( for or while, depending on your preference).
Related
How can I take an argument from this list so that I can put it in place of a phone?
a10 = ' ' * (2 + length)+ (' ' * length - len(str(phone))).join([str(x) for x in range(1, boardX + 1)])
The idea is that (' ' * length - len(str(phone))) determine the space between numbers depending on whether the number is one digit, two digit, etc.
In the phone place I would like to take an argument from a list to specify the number of its characters. –
example:
boardX = 14
length = 3
output:
target output:
Use a formatting operator rather than calculating spaces yourself. Yo can specify the field width indirectly using *.
a10 = " " * (2 + length) + "".join("%*d" % (length, x) for x in range(1, boardX + 1))
I am beginning in python programming and I have this exercise that requires me to put text into a box of stars.
Example :
*******
* I *
* am *
* in *
* a *
* box *
*******
I print this :
********
* I *
* am *
* in *
* a *
* box! *
********
So far I have this, I feel like I am close to the solution.
phrase = "I am in a box!"
phraseSplit = phrase.split(' ')
longuestString = max(phraseSplit, key=len)
#print(len(longuestString))
def maxStars(longuestString):
stars = (len(longuestString)+4) * "*"
print(stars)
maxStars(longuestString)
for i in range(len(phraseSplit)):
delta = len(longuestString) - len(phraseSplit[i])
space = int(delta/2 +1)
print("*" + space * " "+ phraseSplit[i] + space * " " +"*")
maxStars(longuestString)
Help me optimize or find other ways that could be more efficient.
Thank you
Here's how I would do it:
phrase = "I am in a box"
words = phrase.split(' ')
longest = max(words, key=len)
width = len(longest)
pretty = "\n".join(["*"*(width+4),*[f"* {w[::-1].center(width)[::-1]} *" for w in words],"*"*(width+4)])
print(pretty)
*******
* I *
* am *
* in *
* a *
* box *
*******
Now let's break it down!
First we do what you did, splitting the phrase into words and extracting other helpful data:
phrase = "I am in a box"
words = phrase.split(' ')
longest = max(words, key=len)
width = len(longest)
Then comes the real algorithm. Let's make a list of one string per line. Clearly the first and last lines are going to be the length of the longest plus 4 (i.e. (wall + padding)*2).
So at the start and end of the list we put:
"*"*(width+4)
Then we need to fill in the actual meat of the box. We're going to use a list iteration to make as many string as there are lines, and join each line with \n:
[line_contents for w in words]
But we need to actually have line_contents be something for each line. So let's replace that with an f-string.
At the start and end of each line there is the padding (ignoring the extra padding the small words have) and an asterisk. So our f-string is currently f"* {padded_word} *".
To actually make the padded words, we can use str.center(width). This gives the whole f-string as f"* {w.center(width)} *".
Now putting everything together we get:
"\n".join(["*"*(width+4),*[f"* {w.center(width)} *" for w in words],"*"*(width+4)]
NOTE: I used the * operator to unpack the list iteration into the larger list.
If we run the program we get:
*******
* I *
* am *
* in *
* a *
* box *
*******
Looks good! But wait one moment - it seems like str.center is making the off-center words go to the right! This is contrary to your example.
However, there's an easy solution: reverse the word, pad it, then reverse it back. This will make the off-center words go left instead. To reverse any indexable object, you can use slice notation: [start, stop, step] --> [beginning, end, -1] --> [::-1].
Now if we add this into what we have so far, we get what I presented initially.
I finally found my own answer :
phrase = "Hi I am in a box!"
phraseSplit = phrase.split(' ')
longuestString = max(phraseSplit, key=len)
#print(len(longuestString))
def maxStars(longuestString):
stars = (len(longuestString)+4) * "*"
print(stars)
maxStars(longuestString)
for i in range(len(phraseSplit)):
delta = len(longuestString) - len(phraseSplit[i])
space = int(delta/2 +1)
if (delta % 2) != 0:
print("*" + space * " "+ phraseSplit[i] + space * " " +" *")
else:
print("*" + space * " "+ phraseSplit[i] + space * " " +"*")
maxStars(longuestString)
I am aware there are optimal ways to do this and I need to figure it out.
I am trying to parse the coefficient of "a" in a quadratic equation (ax^2 + bx + c).
However, the length of the coefficient can vary.
For instance, here are some of the intended outcomes:
input: 5x^2 + 3x + 4
output: 5
input: 12x^2 + 2x - 6
output: 12
The number could also be in the middle of the equation.
input: 2x - 3x^2 + 4
output: 3
How would I get the whole text before "x^2" until their is a white space?
I have tried using the split() function:
a = equation.split("x^2")
a = a[0]
but this would not work in the third example
Here you are
[-+]?\d+(\.\d+)?(?=x\^)
Test it here
Be aware that this regex will only match simple cases, for example, it will not match 2E3.
Tip: use RegEx 101 to test your pattern:
pattern = re.compile(r'([\+\-\d.]*)x\^2')
tests = [
'5x^2 + 3x + 4',
'12x^2 + 2x - 6',
'2x - 3x^2 + 4',
'x^2 - 2x + 1',
'-x^2 + 6x - 9'
]
for t in tests:
m = pattern.search(t)
text = m.group(1)
if text == '':
coeff = 1
elif text == '-':
coeff = -1
else:
coeff = float(text)
print(coeff)
Prints:
5.0
12.0
3.0
1
-1
I saw that using split is an option too from the question. So you want to get the whole text before the numbers with the ^ operator.
This will only work for these three examples:
x = '5x^2 + 3x + 4'
y = '12x^2 + 2x - 6'
z = '2x - 3x^2 + 4'
print(x.split()[0])
print(y.split()[0])
print(z.split('+')[0])
# split default argument is space
Output
5x^2
12x^2
2x - 3x^2
And If you want to take only the numbers with the ^ operator without the whole text before, change z.split('+')[0] to:
print(z.split()[2])
# 3x^2
I'm trying to write a christmas tree in Python, and I'm trying to make it mirror to another side, so the text is mirrored to itself on the left so instead of having one side of the tree i have both sides
tree = "I"
for i in range(12):
print(tree.ljust(2-i) * i)
There are better ways to do this, in fact you don't really need to mirror, you could just adapt the padding on the left, but let's assume that you want a real mirroring, so that each line has the same number of characters.
You should first multiply the string and then justify it. Then you can use a slice operator to reverse the halves ([::-1]).
size = 12
for i in range(1, size):
half = (tree * i).rjust(size - 1)
print half + half[::-1]
output
II
IIII
IIIIII
IIIIIIII
IIIIIIIIII
IIIIIIIIIIII
IIIIIIIIIIIIII
IIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIIIII
And remember..
Merry Christmas Don!
You should use rjust instead of ljust since the spaces should be padded on the left. Also you need to double the count since 3 chars don't really align with 2 properly.
tree = "I"
for i in range(12):
print((tree*(2*i)).rjust(12 + i))
output:
II
IIII
IIIIII
IIIIIIII
IIIIIIIIII
IIIIIIIIIIII
IIIIIIIIIIIIII
IIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIIIII
it's almost christmas, adding some ornaments?
import random
tree = "I"
for i in range(12):
row = list(tree*(2*i))
if( i > 2):
index = int(random.random() * len(row))
if( index < len(row) - 1):
row[index] = "["
row[index + 1] = "]"
index2 = int(random.random() * len(row))
if( index2 != index and index2 != (index + 1)):
row[index2] = "O"
print (("".join(row)).rjust(12 + i))
tada:
II
IIII
I[]III
IIII[]IO
IIIOIIII[]
IIIIIIIIO[]I
III[]IIIIIOIII
IIIIIOIIIIIIII[]
IIIIIIIIOIIII[]III
IIIIOIIIIIIIIIIIIIII
II[]IIIIIIIIIIOIIIIIII
Here's my take on it:
l = 13
for i in range(l):
print(' ' * int((l - i)/2) + ('#' * i))
I prefer pointy trees, and (just to be different) using str.center() over str.rjust():
def tree(height, symbol='I'):
width = height*2 - 1
for i in range(height):
print((symbol * ((i*2)+1)).center(width))
>>> tree(12)
I
III
IIIII
IIIIIII
IIIIIIIII
IIIIIIIIIII
IIIIIIIIIIIII
IIIIIIIIIIIIIII
IIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIIIIIIIII
Very new to python so please excuse!
question is...to make an output look like
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I am using user input for the limit and the number of copies ( in this example 5 and 3), so I have done this;
limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
output(limit)
However the answer shows up as 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5. I know it's because of the end=" " but not sure how to get around it! Any help appreciated
Print new line explicitly for every loop:
def output(copies, limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
print() # <----
# print() # Add this if you want an empty line
output(copies, limit)
You got the part with the ranges correctly, but there's one thing you missed, you can specify a starting number:
v0 = range(1, limit + 1)
In order to convert a number to a string, use the str() function:
v1 = (str(x) for x in v0)
In order to put a space between adjacent numbers, use the string's join() memberfunction:
v2 = ' '.join(v1)
Then, you could either add the linebreaks yourself:
v3 = (v2 + '\n') * copies
print(v3, end='')
Alternatively in this form:
v3 = '\n'.join(v2 for i in range(copies))
print(v3)
Or you just print the same line multiple times in a plain loop:
for i in range(copies):
print(v2)
BTW: Note that v0 and v1 are generators, so joining them into a string v2 will change their internal state, so you can't simply repeat that and get the same results.
Just a little modification to your code:
def output(limit):
for i in range(copies):
for x in range(limit):
print(x + 1, end=' ')
print()
limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
if (i!=0):
print()
print()
for x in range(limit):
print (x + 1, end="")
output(limit)