Alternative solution for printing pattern using python - python

I want to print pattern using python and i have done it but i want to
know other solutions possible for the same:-
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
......
....
A A
and here is my code:-
n=0
for i in range(71,64,-1):
for j in range(65,i+1):
a=chr(j)
print(a, end=" ")
if n>0:
for l in range(1,3+(n-1)*4):
print(end=" ")
if i<71:
j=j+1
for k in range(j-1,64,-1):
b=chr(k)
print(b, end=" ")
n=n+1
print()

Here's an alternative method using 3rd party library numpy. I use this library specifically because it allows vectorised assignment, which I use instead of an inner loop.
from string import ascii_uppercase
import numpy as np
n = 7
# extract first n letters from alphabet
letters = ascii_uppercase[:n]
res = np.array([list(letters + letters[-2::-1])] * (n-1))
# generate indices that are removed per line
idx = (range(n-i-1, n+i) for i in range(n-1))
# printing logic
print(' '.join(res[0]))
for i, j in enumerate(idx):
# vectorised assignment
res[i, j] = ' '
print(' '.join(res[i]))
Result:
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Related

Find row number for specific change in python numpy

I have a file like this:
C
C
C
C
C
C
C
C
B
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
B
B
B
B
B
I like to print the row number where there is a change from C to B. Like here in row 9 and 27. I need to row number only. How to do that in numpy python.
Thank you
This is one possible solution, but it's not using Numpy
f = open('yourfile.txt', 'r')
x = 0
for i in f:
x = x + 1
if i == 'B':
print('row' + str(x))
If working in pure numpy (this is C-level), I advise you to use np.flatnonzero for comparison of neighbour items:
import numpy as np
x = np.loadtxt(r'your_file.txt', dtype='O')
marker_idx = np.flatnonzero((x[1:]=='B') & (x[:-1]=='C')) + 1 #default way
print(marker_idx + 1) #since you are counting from 1 for some reason
Output
[ 9 27]

Printing the inverse pyramid using alphabets

I need to print a pattern like this:
C E G I K
D F H J
E G I
F H
G
Here is my code:
Someone please correct this code for me.
alpha=ord('C')
for i in range(5,0,-1):
for j in range(i):
print(chr(alpha+2),end="")
print('')
My current output is:
E E E E E
E E E E
E E E
E E
E
You can add an offset to the ordinal number of C based on the the line number and character number:
for i in range(5):
print(*(chr(ord('C') + i + j * 2) for j in range(5 - i)), sep=' ')

How to leave only one defined sub-string in a string in Python

Say I have one of the strings:
"a b c d e f f g" || "a b c f d e f g"
And I want there to be only one occurrence of a substring (f in this instance) throughout the string so that it is somewhat sanitized.
The result of each string would be:
"a b c d e f g" || "a b c d e f g"
An example of the use would be:
str = "a b c d e f g g g g g h i j k l"
str.leaveOne("g")
#// a b c d e f g h i j k l
If it doesn't matter which instance you leave, you can use str.replace, which takes a parameter signifying the number of replacements you want to perform:
def leave_one_last(source, to_remove):
return source.replace(to_remove, '', source.count(to_remove) - 1)
This will leave the last occurrence.
We can modify it to leave the first occurrence by reversing the string twice:
def leave_one_first(source, to_remove):
return source[::-1].replace(to_remove, '', source.count(to_remove) - 1)[::-1]
However, that is ugly, not to mention inefficient. A more elegant way might be to take the substring that ends with the first occurrence of the character to find, replace occurrences of it in the rest, and finally concatenate them together:
def leave_one_first_v2(source, to_remove):
first_index = source.index(to_remove) + 1
return source[:first_index] + source[first_index:].replace(to_remove, '')
If we try this:
string = "a b c d e f g g g g g h i j k l g"
print(leave_one_last(string, 'g'))
print(leave_one_first(string, 'g'))
print(leave_one_first_v2(string, 'g'))
Output:
a b c d e f h i j k l g
a b c d e f g h i j k l
a b c d e f g h i j k l
If you don't want to keep spaces, then you should use a version based on split:
def leave_one_split(source, to_remove):
chars = source.split()
first_index = chars.index(to_remove) + 1
return ' '.join(chars[:first_index] + [char for char in chars[first_index:] if char != to_remove])
string = "a b c d e f g g g g g h i j k l g"
print(leave_one_split(string, 'g'))
Output:
'a b c d e f g h i j k l'
If I understand correctly, you can just use a regex and re.sub to look for groups of two or more of your letter with or without a space and replace it by a single instance:
import re
def leaveOne(s, char):
return re.sub(r'((%s\s?)){2,}' % char, r'\1' , s)
leaveOne("a b c d e f g g g h i j k l", 'g')
# 'a b c d e f g h i j k l'
leaveOne("a b c d e f ggg h i j k l", 'g')
# 'a b c d e f g h i j k l'
leaveOne("a b c d e f g h i j k l", 'g')
# 'a b c d e f g h i j k l'
EDIT
If the goal is to get rid of all occurrences of the letter except one, you can still use a regex with a lookahead to select all letters followed by the same:
import re
def leaveOne(s, char):
return re.sub(r'(%s)\s?(?=.*?\1)' % char, '' , s)
print(leaveOne("a b c d e f g g g h i j k l g", 'g'))
# 'a b c d e f h i j k l g'
print(leaveOne("a b c d e f ggg h i j k l gg g", 'g'))
# 'a b c d e f h i j k l g'
print(leaveOne("a b c d e f g h i j k l", 'g'))
# 'a b c d e f g h i j k l'
This should even work with more complicated patterns like:
leaveOne("a b c ffff d e ff g", 'ff')
# 'a b c d e ff g'
Given String
mystr = 'defghhabbbczasdvakfafj'
cache = {}
seq = 0
for i in mystr:
if i not in cache:
cache[i] = seq
print (cache[i])
seq+=1
mylist = []
Here I have ordered the dictionary with values
for key,value in sorted(cache.items(),key=lambda x : x[1]):
mylist.append(key)
print ("".join(mylist))

print reverse pattern of alphabets using functions in python

I have written following code:
def contalpha(n):
num = 65
for i in range(0, n):
for j in range(0, i+1):
ch = chr(num)
print(ch, end=" ")
num = num +1
print("\r")
n = 7
contalpha(n)
The output is:
A
B C
D E F
G H I J
K L M N O
P Q R S T U
V W X Y Z [ \
but what I want is:
A B C D E
A B C D
A B C
A B
A
How can I make it?
I'd advise against using chr. Ascii can be confusing, instead just use a string of all capital ascii characters (which is a sequence of characters, and can be handily found in the string module).
import string
def contalpha(n):
for i in range(n, 0, -1):
print(*string.ascii_uppercase[:i], sep=' ')
contalpha(5)
outputs:
A B C D E
A B C D
A B C
A B
A
You need to reverse the range in order to start from the bigger row range(0, n)[::-1]. Then you need to set num = 65 every time you start a new row for it to always start from A.
There you go:
def contalpha(n):
num = 65
for i in range(0, n)[::-1]:
for j in range(0, i+1):
ch = chr(num)
print(ch, end=" ")
num = num +1
num = 65
print("\r")
n = 7
contalpha(n)
Output
A B C D E F G
A B C D E F
A B C D E
A B C D
A B C
A B
A
Try this:
def contalpha(n):
for i in range(n, 0, -1):
num = 65
for j in range(0, i):
ch = chr(num)
print(ch, end=" ")
num = num +1
print("\r")
n = 7
contalpha(n)
First you need to set num to 65 every outer loop to get alphabets from A again and second you should reverse outer loop range to print from max size to min size.
output:
A B C D E F G
A B C D E F
A B C D E
A B C D
A B C
A B
A

Program to output letter pyramid

To print the output
A
A B
A B C
A B C D
A B C D E
I used the following code, but it does not work correctly.
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+1]
print "\n"
i = i + 1
For this code the obtained output is:
A
A
A B
A B
A B C
A B C
A B C D
A B C D
A B C D E
A B C D E
A B C D E F
Why does each line get printed twice?
Whitespace. You need to increment i by 2 instead of 1. Try:
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+2]
print "\n"
i = i+2
This will allow you to skip over the whitespace as "indices" of the string
A little more pythonic:
>>> strg = "ABCDEF"
>>> for index,_ in enumerate(strg):
print " ".join(strg[:index+1])
A
A B
A B C
A B C D
A B C D E
A B C D E F

Categories

Resources