Python program with letters pyramid - python

I need help with python. I have to do this and I don't know how can I add letters to * pyramid. Thank you first program second program

This will help you:
length = 7 # length of the string
word = "Python" # string to print
# first program
string = '.' * (length - 1) + word
for i in range(length - 1):
print(string[i:i + length])
# second program
for i in range(1, length):
_str = word[:i] + '.' * (length - i)
print(_str[::-1] + _str)
The output is:
......P
.....Py
....Pyt
...Pyth
..Pytho
.Python
......PP......
.....yPPy.....
....tyPPyt....
...htyPPyth...
..ohtyPPytho..
.nohtyPPython.

Related

taking argument from comprehensions list

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))

Returning original string with symbols between each character

I'm trying to make my program return the exact same string but with ** between each character. Here's my code.
def separate(st):
total = " "
n = len(st + st[-1])
for i in range(n):
total = str(total) + str(i) + str("**")
return total
x = separate("12abc3")
print(x)
This should return:
1**2**a**b**c**3**
However, I'm getting 0**1**2**3**4**5**6**.
You can join the characters in the string together with "**" as the separator (this works because strings are basically lists in Python). To get the additional "**" at the end, just concatenate.
Here's an example:
def separate(st):
return "**".join(st) + "**"
Sample:
x = separate("12abc3")
print(x) # "1**2**a**b**c**3**"
A note on your posted code:
The reason you get the output you do is because you loop using for i in range(n): so the iteration variable i will be each index in st. Then when you call str(total) + str(i) + str("**"), you cast i to a string, and i was just each index (from 0 to n-1) in st.
To fix that you could iterate over the characters in st directly, like this:
for c in st:
or use the index i to get the character at each position in st, like this:
for i in range(len(st)):
total = total + st[i] + "**"
welcome to StackOverflow!
I will explain part of your code line by line.
for i in range(n) since you are only providing 1 parameter (which is for the stopping point), this will loop starting from n = 0, 1, 2, ... , n-1
total = str(total) + str(i) + str("**") this add i (which is the current number of iteration - 1) and ** to the current total string. Hence, which it is adding those numbers sequentially to the result.
What you should do instead is total = str(total) + st[i] + str("**") so that it will add each character of st one by one
In addition, you could initialize n as n = len(st)

Shortening a string

I have a string:
a = babababbaaaaababbbab
And it needs to be shortened so it looks like this:
(ba)3(b)2(a)5ba(b)3ab
So basically it needs to take all repeating characters and write how many times they are repeating instead of printing them.
I managed to do half of this:
from itertools import groupby
a = 'babababbaaaaababbbab'
grouped = ["".join(grp) for patt,grp in groupby(a)]
solved = [str(len(i)) + i[0] for i in grouped if len(i) >= 2]
but this only does this for characters that are repeating but not patterns. I get it that I could do this by finding 'ab' pattern in string but this needs to be viable for every possible string. Has anyone encountered something similar?
You can easily do this with regex:
>>> repl= lambda match:'({}){}'.format(match.group(1), len(match.group())//len(match.group(1)))
>>> re.sub(r'(.+?)\1+', repl, 'babababbaaaaababbbab')
'(ba)3(b)2(a)5ba(b)3ab'
Not much to explain here. The pattern (.+?)\1+ matches repeating character sequences, and the lambda function rewrites them to the form (sequence)number.
This is what I came up with, the code is a mess, but I just wanted to have a quick fun, so I let it be like this
a = 'babababbaaaaababbbab'
def compress(text):
for i in range(1, len(text) // 2):
for j, c in enumerate(text[:-i if i > 0 else len(text)]):
pattern = text[j:i+j]
new_text = pattern_repeats_processor(pattern, text, j)
if new_text != text:
return compress(new_text)
return text
def pattern_repeats_processor(pattern, text, i):
chunk = pattern
count = 1
while chunk == pattern and i + (count + 1) * len(pattern) < len(text):
chunk = text[i + count * len(pattern): i + (count + 1) * len(pattern)]
if chunk == pattern:
count = count + 1
else:
break
if count > 1:
return text[:i] + '(' + pattern + ')' + str(count) + text[i + (count + 0) * len(pattern):]
return text
print(compress(a))
print(a)
It makes
babababbaaaaababbbab =>
(ba)3(b)2(a)5ba(b)3ab
P.S. Of course answer of Rowing is miles better, pretty impressive even
I'm not sure what exactly you're looking for but here hope this helps.
A=a.count('a')
B=a.count('b')
AB=a.count('ab')
BAB=a.count('bab')
BA=a.count('ba')
print(A,'(a)',B,'(b)',AB,'(ab)',BAB,'(bab)',BA,'(ba)')

Explanation of `ch[:prefix_len%len(ch)]` in python program

I am looking at this python program and almost understood its flow but I am unable to understand ch[:prefix_len%len(ch)] in the following part:
else:
prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
Here is the context:
def banner(text, ch='=', length=78):
if text is None:
return ch * length
elif len(text) + 2 + len(ch)*2 > length:
# Not enough space for even one line char (plus space) around text.
return text
else:
remain = length - (len(text) + 2)
prefix_len = remain / 2
suffix_len = remain - prefix_len
if len(ch) == 1:
prefix = ch * prefix_len
suffix = ch * suffix_len
else:
prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
return prefix + ' ' + text + ' ' + suffix
Could somebody please help me to understand this. Thank you.
Sure!
ch[:prefix_len % len(ch)] is accessing a slice of the ch sequence starting from the beginning (since there's no value before the : and going to one character before the index defined by prefix_len % len(ch).
This value is prefix_len (defined earlier as the length of the prefix, not surprisingly) modulus the length of ch. (Think of it as the remainder left over after integer division of prefix_len / len(ch).
I ran the function like: print(banner("Hello everyone!", "1234")) and got:
123412341234123412341234123412 Hello everyone! 1234123412341234123412341234123
so you can see it's fitting the ch value (1234 in my case) in the space it has.
They're adding the remainder.
Say prefix = 10, and ch = '#&+'
If you just multiply ch by prefix_len / len(ch), you'll get 9, but you know you need 10.
So ch[:prefix_len % len(ch)] is just indexing into ch string for the remainder.
Make sense?

Mirroring something to another side in Python

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

Categories