Files
PyClasses/StringAlgorithms.py

62 lines
2.3 KiB
Python

#Python/pyClasses/StringAlgorithms.py
#Matthew Ellison
# Created: 07-21-21
#Modified: 07-21-21
#This file contains my library of string functions
"""
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
#This is a function that creates all permutations of a string and returns a vector of those permutations.
def getPermutations(master: str, num: int = 0) -> list:
perms = []
#Check if the number is out of bounds
if((num >= len(master)) or (num < 0)):
#Do nothing and return and empty list
perms
#If this is the last possible recurse just return the current string
elif(num == (len(master) - 1)):
perms.append(master)
#If there are more possible recurses, recurse with the current permutations
else:
temp = getPermutations(master, num + 1)
perms += temp
#You need to swap the current letter with every possible letter after it
#The ones needed to swap before will happen automatically when the function recurses
for cnt in range(1, len(master) - num):
#Swap two elements
master = master[0:num] + master[num + cnt] + master[num + 1 : num + cnt] + master[num] + master[num + cnt + 1:]
#Get the permutations after swapping two elements
temp = getPermutations(master, num + 1)
perms += temp
#Swap the elements back
master = master[0:num] + master[num + cnt] + master[num + 1 : num + cnt] + master[num] + master[num + cnt + 1:]
#The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
if(num == 0):
perms.sort()
#Return the list
return perms
#Returns true if the string passed in is a palindrome
def isPalindrome(str: str) -> bool:
rev = str[::-1]
if(str == rev):
return True
else:
return False