I am trying to implement a function in python that given two strings it checks if the first string is smaller than the second string in the lexicographic order. This is what I managed to write, I do not claim that it is elegant code
import string
#first make a dictionary that gives the value of a letter, eg "C":3
d = dict.fromkeys(string.ascii_uppercase, 0)
i=1
for c in d.keys():
d[c] = i
i+=1
def lexico(str1,str2):#returns true if str1<=str2 in lexicographic order
print(str1,str2) #printing for debugging purpose
if str1 == '' and str2 == '':
return True
elif str1 != '' and str2 == '':
return False
elif str1 == '' and str2 != '':
return True
elif d[str1[0]] > d[str2[0]]:
return False
elif d[str1[0]] < d[str2[0]]:
return True
elif str1 == str2:
return True
else:
print(str1,str2) #printing for debugging purpose
lexico(str1[1:],str2[1:])
str1 = 'ANGELA'
str2 = 'AMY'
print(lexico(str1,str2))
I have really no idea what goes wrong here, but the output is as follows
ANGELA AMY
ANGELA AMY
NGELA MY
None
The function does not return anything, and I dont know why.
You are missing a return on this line: lexico(str1[1:],str2[1:]). It should be return lexico(str1[1:],str2[1:]).
Related
I wrote a regex code which compares two strings. It recognises a special character '?' that allows zero or more instances of previous character. It works fine until there are two or more occasions of '?' in the string. And I can't make out why.
def single_character_string(a, b) -> "return True if characters match":
"""check if two characters match"""
if len(a) == 0:
return True
elif len(b) == 0:
return False
else:
if a == '.':
return True
else:
if a == b:
return True
else:
return False
def meta_question_result(temp):
if len(temp) >= 2:
if temp[1] == '?':
k_1 = temp.replace(temp[0: 2], '') # no char
k_2 = temp.replace(temp[1], '') # char
return k_1, k_2
def check_pair_by_pair(template, check_string) -> "Strings are of Equal length! " \
"return True if lines are identical":
"""check if two strings match symbol by symbol. template may be less than string, the opposite
is False"""
if not template: # exit from recursion
return True
if not check_string: # exit from recursion
return False
if meta_question_result(template):
t_1, t_2 = meta_question_result(template)
if single_character_string(t_1[0], check_string[0]):
return check_pair_by_pair(t_1[1:], check_string[1:])
if single_character_string(t_2[0], check_string[0]):
return check_pair_by_pair(t_2[1:], check_string[1:])
else:
return False
elif single_character_string(template[0], check_string[0]):
return check_pair_by_pair(template[1:], check_string[1:])
else:
return False
reg, st = input().split("|")
print(check_pair_by_pair(reg, st))
reg = "co?lou?r"
st = "colour"
gives True as expected,
reg = "co?lou?r"
st = "clor"
gives True as expected,
but...
reg = "co?lou?r"
st = "color"
gives False. I expected True.
Found the bag.
Replace method replaces all instances of '?'. So the second '?' was replaced also and program didn't see it.
I should add an argument 'count' to replace method that is equal to 1.
k_1 = temp.replace(temp[0: 2], '', 1) # no char
Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence.
Examples:
Input : S = "{(X[X])}"
Output : Balanced
Input : S = "[{X}(X)]"
Output : Not balanced
I tried to work it out like this, and it works for examples above. But it doesn't work for all examples eg. (it should be balanced but it says it's not)
Input: S = "([X}])"
Output: Not balanced
I tried to work it out but i can't find a solution. Please help.
class Stack:
def __init__(self):
self.data = []
def insert(self, x):
self.data.append(x)
def empty(self):
return len(self.data) == 0
def remove(self):
if self.empty():
raise ValueError('Stack is empty.')
self.data.pop()
def top_element(self):
if self.empty():
raise ValueError('Stack is empty.')
return self.data[-1]
def is_matching(a, b):
if a == "(" and b == ")":
return True
elif a == "[" and b == "]":
return True
elif a == "{" and b == "}":
return True
elif a == "X":
return True
return False
def is_balanced(expression,elements=Stack(),ind=0):
if ind == len(expression):
return elements.empty()
pre_brackets = "([{"
post_brackets = ")]}"
char = expression[ind]
if char in pre_brackets:
elements.insert(char)
return is_balanced(expression,elements,ind+1)
elif char in post_brackets:
if elements.empty() :
return False
if not is_matching(elements.top_element(), char):
return False
elements.remove()
return is_balanced(expression,elements,ind+1)
elif char == "X":
temp = Stack()
temp.insert(char)
result = (is_balanced(expression,temp,ind+1))
if result:
return True
if elements.empty():
return False
elements.remove()
return is_balanced(expression,elements,ind+1)
expression = "([X}])"
if expression == "":
print("No brackets in expression!")
elif len(expression) % 2 != 0:
print("Not balanced")
elif is_balanced(expression):
print("Balanced")
else:
print("Not Balanced")
You can do it by recursively testing all possible replacements for an X:
def can_be_balanced(expr):
pairs = "{}[]()"
opening_brackets = pairs[::2]
closing_brackets = pairs[1::2]
closer = {o:c for o, c in zip(opening_brackets, closing_brackets)}
opener = {c:o for o, c in zip(opening_brackets, closing_brackets)}
stack = []
for item in expr:
if item in opening_brackets:
# we append opening brackets to the stack
stack.append(item)
elif item in closing_brackets:
if not stack or stack[-1] != opener[item]:
# the closing bracket doesn't match the top of the stack
return False
else:
# if it does, we remove the matching opening bracket
stack.pop()
elif item == 'X':
# X could be any of the opening brackets,
possible = list(opening_brackets)
if stack and stack[-1] in opening_brackets:
# or the closing bracket matching the top of the stack
possible.append(closer[stack[-1]])
for pos in possible:
# we replace this X, the first one remaining in expr
test_expr = expr.replace('X', pos, 1)
if can_be_balanced(test_expr):
# This is just in order to print the working solution we just found,
# you may remove these two lines
if not 'X' in test_expr:
print(test_expr)
return True
# None of the replacements for X gave a balanced expression
return False
else:
raise ValueError(f'Invalid item {item} in {expr}')
# The expression is balanced if and only if the stack ends up empty
return not stack
Testing on your sample data:
tests = [("[{X}(X)]", False),
("{(X[X])}", True),
("([X}])", True),
]
for test in tests:
print(test[0], ': should be', test[1])
print(can_be_balanced(test[0]))
print('-'*20)
correctly outputs (with the balanced expression in case it can be done):
[{X}(X)] : should be False
False
--------------------
{(X[X])} : should be True
{([[]])}
True
--------------------
([X}]) : should be True
([{}])
True
--------------------
Note that a major problem in your code is that you only test the end of the expression, starting at the position of the X. Beware also of the mutable default argument elements=Stack() that would leave you with the remnants of the previous call to the function instead of a fresh, empty Stack object.
I have this linear search where there is a list of words and a single word. the search checks whether the word is in the list or not. I keep on trying to pass my parameters to test the function but when i run the program nothing comes up. it would be great if you could look at this code and tell me where im going wrong.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found == True
else:
pos = pos + 1
return found
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You are doing a lot extra works. Do it like this:
def isin(alist, word):
if word in alist:
return True
else:
return False
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You have a problem with line found == True. It should be found = True.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found = True
else:
pos = pos + 1
return found
You could simplify the method to do the same task in one line as:
def isin(alist, word):
return True if word in alist else False
I'm trying to write a function in similar manner as started, so that I will get what it's doing. I'm assuming this can be done with one line of code, with some fancy functions, but for the sake of practice and understanding I'm trying to come up with similar solution.
The task is the following: the function takes a text once it encounters enclosed square brackets [ word ] It should print out or return all words which are between square brackets. For example, if the text string would be "[a]n example[ string]", you are expected to print out "a string".
def string():
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
for j in range(len(text)):
if text[j] == '[':
new = text.find(']')
return(text[j+1:new])
print(string())
Try this:
def extract(text, skip_chars=("\n", )):
output = ""
flag = False
for c in text:
if c == "]":
flag = False
if flag and not c in skip_chars:
output += c
if c == "[":
flag = True
return output
print(extract("""[a]n example[
stri
ng]"""))
# -> "a string"
def string():
result = []
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
if i == '[':
new = text.find(']')
result.append(text[text.index(i) + 1:new])
return " ".join(result)
print(string())
def parse(source):
i = source.index("[") # throw an exception
result = ""
while i < len(source):
if s[i] == "[":
i += 1
while i < len(source):
temp = ""
if source[i] == "]":
result += temp
break;
temp += source[i]
i += 1
i += 1
return result
I have this code that should break once it fulfills a certain condition, ie when the isuniquestring(listofchar) function returns True, but sometimes it doesn't do that and it goes into an infinite loop. I tried printing the condition to check if there's something wrong with the condition, but even when the condition is printed true the function still continues running, I have no idea why.
one of the strings that throws up an infinite loop is 'thisisazoothisisapanda', so when I do getunrepeatedlist('thisisazoothisisapanda'), it goes into an infinite loop.
would be really grateful if someone could help
thanks!
Here's my code:
def getunrepeatedlist(listofchar):
for ch in listofchar:
if isrepeatedcharacter(ch,listofchar):
listofindex = checkrepeatedcharacters(ch,listofchar)
listofchar = stripclosertoends(listofindex,listofchar)
print (listofchar)
print (isuniquestring(listofchar))
if isuniquestring(listofchar):
return listofchar
#print (listofchar)
else:
getunrepeatedlist(listofchar)
return listofchar
just for reference, these are the functions I called
def isrepeatedcharacter(ch,list):
if list.count(ch) == 1 or list.count(ch) == 0:
return False
else:
return True
def checkrepeatedcharacters(ch,list):
listofindex=[]
for indexofchar in range(len(list)):
if list[indexofchar] == ch:
listofindex.append(indexofchar)
return listofindex
def stripclosertoends(listofindices,listofchar):
stringlength = len(listofchar)-1
if listofindices[0] > (stringlength-listofindices[-1]):
newstring = listofchar[:listofindices[-1]]
elif listofindices[0] < (stringlength-listofindices[-1]):
newstring = listofchar[listofindices[0]+1:]
elif listofindices[0] == (stringlength-listofindices[-1]):
beginningcount = 0
endcount = 0
for index in range(listofindices[0]):
if isrepeatedcharacter(listofchar[index],listofchar):
beginningcount += 1
for index in range(listofindices[-1]+1,len(listofchar)):
if isrepeatedcharacter(listofchar[index],listofchar):
endcount += 1
if beginningcount < endcount:
newstring = listofchar[:listofindices[-1]]
else:
#print (listofindices[0])
newstring = listofchar[listofindices[0]+1:]
#print (newstring)
return newstring
def isuniquestring(list):
if len(list) == len(set(list)):
return True
else:
return False
It may be due to the fact that you are changing listofchar in your for loop. Try cloning that variable to a new name and use that variable for manipulations and return the new variable.