Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Pattern and String

The document contains various Python code snippets for generating different patterns using loops, including pyramids, inverted pyramids, and star patterns. It also includes programs for string handling, such as checking for palindromes, counting vowels, and removing vowels from strings. Additionally, it covers functions for converting strings to lowercase and checking string symmetry.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Pattern and String

The document contains various Python code snippets for generating different patterns using loops, including pyramids, inverted pyramids, and star patterns. It also includes programs for string handling, such as checking for palindromes, counting vowels, and removing vowels from strings. Additionally, it covers functions for converting strings to lowercase and checking string symmetry.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

rows = 6 rows = 5

for num in range(rows): b=0


for i in range(num): for i in range(rows, 0, -1):
print(num, end=” “) # print number b += 1
# line after each row to display pattern for j in range(1, i + 1):
correctly print(b, end=’ ‘)
print(” “) print(‘\r’)
Pattern #4: Inverted Pyramid of Descending Numbers
rows = 5 rows = 5
for row in range(1, rows+1): for i in range(rows, 0, -1):
for column in range(1, row + 1): num = i
print(column, end=’ ‘) for j in range(0, i):
print(“”) print(num, end=’ ‘)
print(“\r”)
Pattern #5: Inverted Pyramid of the Pattern #6: Reverse Pyramid of Numbers
Same Digit rows = 6
rows = 5 for row in range(1, rows):
num = rows for column in range(row, 0, -1):
for i in range(rows, 0, -1): print(column, end=’ ‘)
for j in range(0, i): print(“”)
print(num, end=’ ‘)
print(“\r”)
Pattern #7: Inverted Half Pyramid Pattern #8: Pyramid of Natural Numbers Less
Number Pattern Than 10
rows = 5 currentNumber = 1
for i in range(rows, 0, -1): stop = 2
for j in range(0, i + 1): rows = 3 # Rows you want in your
print(j, end=’ ‘) pattern
print(“\r”) for i in range(rows):
for column in range(1, stop):
print(currentNumber, end=’ ‘)
currentNumber += 1
print(“”)
stop += 2
Pattern #9: Reverse Pattern of Digits from 10 Pattern #10: Unique Pyramid Pattern of Digits
start = 1 rows = 6
stop = 2 for i in range(1, rows + 1):
currentNumber = stop for j in range(1, i – 1):
for row in range(2, 6): print(j, end=” “)
for col in range(start, stop): for j in range(i – 1, 0, -1):
currentNumber -= 1 print(j, end=” “)
print(currentNumber, end=’ ‘) print()
print(“”)
start = stop
stop += row
currentNumber = stop

Pattern #11: Connected Inverted Pyramid Pattern Pattern #12: Even Number Pyramid Pattern
of Numbers rows = 5
rows = 6 LastEvenNumber = 2 * rows
for i in range(0, rows): evenNumber = LastEvenNumber
for j in range(rows – 1, i, -1): for i in range(1, rows+1):
print(j, ”, end=”) evenNumber = LastEvenNumber
for l in range(i): for j in range(i):
print(‘ ‘, end=”) print(evenNumber, end=’ ‘)
for k in range(i + 1, rows): evenNumber -= 2
print(k, ”, end=”) print(“\r”)
print(‘\n’)

Pattern #13: Pyramid of Horizontal Tables Pattern #14: Pyramid Pattern of Alternate Numbers
rows = 7 rows = 5
for i in range(0, rows): i=1
for j in range(0, i + 1): while i <= rows:
print(i * j, end=’ ‘) j=1
print() while j <= i:
print((i * 2 – 1), end=” “)
j=j+1
i=i+1
print()

Pattern #15: Mirrored Pyramid (Right-angled Pattern #16: Equilateral Triangle with Stars (Asterisk
Triangle) Pattern of Numbers Symbol)
Pattern: print(“Print equilateral triangle Pyramid using stars
rows = 6 “)
for row in range(1, rows): size = 7
num = 1 m = (2 * size) – 2
for j in range(rows, 0, -1): for i in range(0, size):
if j > row: for j in range(0, m):
print(” “, end=’ ‘) print(end=” “)
else: m = m – 1 # decrementing m after each loop
print(num, end=’ ‘) for j in range(0, i + 1):
num += 1 # printing full Triangle pyramid using stars
print(“”) print(“* “, end=’ ‘)
print(” “)

Pattern #17: Downward Triangle Pattern of Stars Pattern #18: Pyramid Pattern of Stars
rows = 5 rows = 5
k = 2 * rows – 2 for i in range(0, rows):
for i in range(rows, -1, -1): for j in range(0, i + 1):
for j in range(k, 0, -1): print(“*”, end=’ ‘)
print(end=” “) print(“\r”)
k=k+1
for j in range(0, i + 1):
print(“*”, end=” “)
print(“”)

n = int(input('Enter number of rows : ')) n = int(input('Enter number of rows : '))


i=1 i=1
while i <= n : while i <= n :
j=1 j=n
while j <= i: while j >= i:
print("*", end = " ") print("*", end = " ")
j += 1 j -= 1
print() print()
i += 1 i += 1
n = int(input('Enter number of rows : ')) # Python program to print left half pyramid star pattern
k = 1 def pattern(n):
i=1
i = 1 while i <= n :
while i <= n : j=1
while j <= i:
j = 1 # printing stars
while j <= i: print("*", end=" ")
print("{:3d}".format(k), j=j+1
print()
end = " ") i=i+1
j += 1 # take inputs
k += 1 n = int(input('Enter the number of rows: '))
print() # calling function
pattern(n)
i += 1
# Python program to print right def pattern(n):
half pyramid star pattern i = 1
def pattern(n): while i<=n:
i = 1 # printing stars
while i<=n: print(" "*(n-i) + "* " *
# printing stars i)
print(" "*(n-i) + "*" * i) i+=1
i+=1 # take inputs
# take inputs n = int(input('Enter the number
n = int(input('Enter the number
of rows: '))
of rows: '))
# calling function
# calling function
pattern(n)
pattern(n)
String Handling program in Python
# Python program to check if string is # Python program to check if string is Palindrome
Palindrome
# take inputs # take inputs
string = input('Enter the string: ') string = input('Enter the string: ')
# find reverse of string
i = string # find reverse of string
reverse = '' reverse = str(string)[::-1]
while(len(i) > 0):
if(len(i) > 0): # compare reverse to original string
a = i[-1] if(reverse == string):
i = i[:-1] print(string,'is a Palindrome')
reverse += a else:
# compare reverse to original string print(string,'is not a Palindrome')
if(reverse == string):
print(string,'is a Palindrome')
else:
print(string,'is not a Palindrome')
# Python program to check if string is # Python program to check if
Palindrome using recursion string starts with vowel
def isPalindrome(s): #user-defined function
s = s.lower() # take inputs
length = len(s) string = input('Enter the
if length < 2: String: ')
return True
elif s[0] == s[length-1]:
# vowel alphabet
# Call is pallindrome form
vowel = 'aeiou'
substring(1,length-1)
return isPalindrome(s[1: length-1])
else: # check string starts with vowel
or consonant
return False if string[0].lower() in vowel:
# take inputs print(string,'starts with
string = input('Enter the string: ') vowel',string[0])
# calling function and display result else:
reverse = isPalindrome(string) print(string,'starts with
if reverse: consonant',string[0])
print(string,'is a Palindrome')
else:
print(string,'is not a Palindrome')
input_str = 'Know Program' # Python program to extract the
words that start with a vowel
if input_str[0].lower() in from a list
['aeiou']:
print('YES') # take list
else: words =
print('NO') ['String','Egg','know','Open','p
rogram','animal']

# vowel alphabet
vowel =
'A','E','I','O','U','a','e','i',
'o','u'

# check words and display result


print([w for w in words if
w.startswith(vowel)])
# Python program to accept # Python program to count vowels
strings starting with a vowel in a string

# Function to check if first def countVowels(string):


character is vowel num_vowels=0
def Vowel(string): # to count the vowels
for char in string:
if (string[0] == 'A' or if char in "aeiouAEIOU":
string[0] == 'a' num_vowels =
or string[0] == 'E' or num_vowels+1
string[0] == 'e' return num_vowels
or string[0] == 'I' or
string[0] == 'i' # take input
or string[0] == 'O' or string = input('Enter any
string[0] == 'o' string: ')
or string[0] == 'U' or
string[0] == 'u'): # calling function and display
return 1 result
else: print('No of vowels
return 0 =',countVowels(string))

# Function to check
def check(string):
if (Vowel(string)):
print('Accept')
else:
print('Not Accept')

# take input
character = input('Enter the
String: ')

# calling function and display


result
check(character)
# Python program to count # Python program to count the
vowels in a string using while number of each vowel
loop def countVowels(string):
string = string.casefold()
def countVowels(string): count = {i:0 for i in
count = 0 'aeiou'}
num_vowels = 0 # to count the vowels
while count <len(string): for char in string:
if string[count] == if char in count:
"a" or string[count] == "e" or count[char] += 1
string[count] == return count
"i" or string[count] == "o" or # take input
string[count] == string = input('Enter any
"u" or string[count] == "A" or string: ')
string[count] == # calling function and display
"E" or string[count] == "I" or result
string[count] print(countVowels(string))
== "O" or string[count] ==
"U":
num_vowels =
num_vowels+1
count = count+1
return num_vowels

# take input
string = input('Enter any
string: ')

# calling function and display


result
print('No of vowels
=',countVowels(string))
# Python program to count the # Python program to remove all
number of each vowel vowels from string

def countVowels(string): def removeVowels(string):


# make it suitable for vowel = 'aeiou'
caseless comparisions #find vowel in string
string = string.casefold() for ch in string.lower():
if ch in vowel:
# to count the vowels #remove vowels
count = {x:sum([1 for char string =
in string if char == x]) for x string.replace(ch, '')
in 'aeiou'}
print(count) #print string without vowels
print(string)
# take input
string = input('Enter any string = input('String: ')
string: ') removeVowels(string)

# calling function
countVowels(string)
# Python program to remove all # Python program to remove all
vowels from string vowels from string

import re #importing regular # function for remove vowels


expression from string
def removeVowels(string):
# function for remove vowels remove_str = ''.join([x for
from string x in string if x.lower() not in
def removeVowels(string): 'aeiou'])
return #print string without vowels
(re.sub('[aeiouAEIOU]','',stri print(remove_str)
ng))
string = input('String: ')
string = input('String: ') removeVowels(string)
print(removeVowels(string))
# Python program to remove all # Python program to convert
vowels from string uppercase to lowercase

# function for remove vowels #take input


from string string = input('Enter any
def removeVowels(string): string: ')
vowels = 'AEIOUaeiou'
#remove vowels # lower() function to convert
translate = uppercase to lowercase
str.maketrans(dict.fromkeys(vo print('In Upper Case:',
wels)) string.lower())
remove_str =
string.translate(translate)
#print string without
vowels
print(remove_str)

string = input('String: ')


removeVowels(string)
# Python program to convert Python program to check whether the string is
uppercase to lowercase Symmetrical or Palindrome
# Function to check whether the
# take input # string is palindrome or not
string = input('Enter any def palindrome(a):
string: ') # finding the mid, start
# and last index of the string
# convert uppercase to mid = (len(a)-1)//2
lowercase start = 0
new_string ='' last = len(a)-1
for i in string: flag = 0
if(ord(i) >= 65 and ord(i) # A loop till the mid of the
<= 90): # string
new_string = while(start <= mid):
new_string + chr((ord(i) + if (a[start]== a[last]):
32)) start += 1
else: last -= 1
new_string = else:
new_string + i flag = 1
break;
# print lowercase string if flag == 0:
print('In Lower print("The entered string is
Case:',new_string) alindrome")
else:
print("The entered string is not
palindrome")
# string is symmetrical or not
def symmetry(a):
n = len(a)
flag = 0
# Check if the string's length
# is odd or even
if n%2:
mid = n//2 +1
else:
mid = n//2
start1 = 0
start2 = mid
while(start1 < mid and start2 < n):
if (a[start1]== a[start2]):
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
if flag == 0:
print("The entered string is
symmetrical")
else:
print("The entered string is not
symmetrical")
# Driver code
string = 'amaama'
palindrome(string)
symmetry(string)
Reverse words in a given String in Python # Python3 program to print
# Function to reverse words of # even length words in a string
string
def printWords(s):
def rev_sentence(sentence): # split the string
s = s.split(' ')
# first split the string
# iterate in words of string
into words
words = sentence.split(' for word in s:
') # if length is even
if len(word)%2==0:
# then reverse the split print(word)
string list and join using # Driver Code
space s = "i am muskan"
reverse_sentence = ' printWords(s)
'.join(reversed(words))

# finally return the


joined string
return reverse_sentence

if __name__ == "__main__":
input = 'geeks quiz
practice code'
print
(rev_sentence(input))
# Python program to capitalize # Python program to accept the strings
# first and last character of # which contains all the vowels
# each word of a String # Function for check if string
# Function to do the same # is accepted or not
def word_both_cap(str): def check(string) :
#lamda function for string = string.lower()
capitalizing the
vowels = set("aeiou")
# first and last letter of
s = set({})
words in
# the string return # looping through each
' '.join(map(lambda s: s[:- # character of the string
1]+s[-1].upper(), for char in string :
s.title().split())) if char in vowels :
# Driver's code s.add(char)
s = "welcome to eeksforgeeks" else
print("String before:", s) pass
print("String after:", # accepted otherwise not
word_both_cap(str)) if len(s) == len(vowels)
print("Accepted")
else :
print("Not Accepted")
# Driver code
if __name__ == "__main__" :
string = "SEEquoiaL"
# calling function
check(string)
def check(string): import re
string = string.replace(' sampleInput = "aeioAEiuioea"
', '') # regular expression to find the strings
string = string.lower() # which have characters other than a,e,i,o and
vowel = u
[string.count('a'), c = re.compile('[^aeiouAEIOU]')
string.count('e'), # use findall() to get the list of strings
string.count( # that have characters other than a,e,i,o and
'i'),
u.
string.count('o'),
if(len(c.findall(sampleInput))):
string.count('u')]

# If 0 is present int print("Not Accepted") # if length of list > 0


vowel count array then it is not accepted
if vowel.count(0) > 0:
return('not
accepted') else:
else: print("Accepted") # if length of list = 0
return('accepted') then it is accepted

# Driver code
if __name__ == "__main__":

string = "SEEquoiaL"

print(check(string))

You might also like