#🔒 Compare 2 strings recursively and return * if match and . if not matched

64 messages · Page 1 of 1 (latest)

tame dagger
#

I have the following recursion ... but i need help to return " * " if the first char of both lists are the same, and ' . ' if they are not

def compare_str(str1,str2):
if str1 == "":
return 0
print(str1,str2)
return compare_str(str1[1:],str2[1:])

print(compare_str("AABBBBAAB","AABBBBAAB"))
" ********* "

daring grailBOT
#

@tame dagger

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

cobalt steppe
#

iterate over the strings and do a match for match for each?

tame dagger
#

this time round i am doing it recursively

#

both strings get smaller by [-1] each call

cobalt steppe
#

so you only want the very 1st char to match?

tame dagger
#

and i want to compare the first char of both strings, if they match or don't return a string value

#

so comparing 1st char each time and shortening the string each time by [1:]

#

i have trouble creating the leaf case in this instnace

cobalt steppe
#

your basically saying what you want.. just need to construct the if statements to say it

autumn breach
#

You know how to check the first index of a string or no

tame dagger
#

this is how i did it

if str1[0] == str2[0]:
    return '*'
#
    if str1 == "":
        return 0
    if str1[0] == str2[0]:
        return '*'
    if str1[0] != str2[0]:
        print(str1[0])
        return '.'
    return compare_str(str1[1:],str2[1:])```
autumn breach
#

Well you only want to return * or . When you’ve checked the entire string right?

tame dagger
#

i want a ******** or as many * or . for every match or no-match

autumn breach
#

Oh I see

cobalt steppe
#

1st if str == ' ' .. acutally means.. if str == None .. so easier to put as, if not str1

#

and your 2nd ifs.. should be forloops done as if and elif

tame dagger
#

i think i need to store the result somewhere and return it all in the end

autumn breach
#

An empty string is False not None

cobalt steppe
#

meh false, none.. none is false.. but for clarity yes

autumn breach
#

No it’s not the same

#

But since it’s false you can do not str

tame dagger
#

let say im given

  str2: 'ACTCATGTAA'
 output: '*.****.**.'
autumn breach
#

So you want to start with an empty string

#

And add either * or . To it every time you call the function

tame dagger
#

yes sir

autumn breach
#

What’s your current code?

tame dagger
#

the question is where do i do a res = "", and how do it return res + " * "

#
    if not str1:
        return 0
    elif str1[0] == str2[0]:
        return '*'
    elif str1[0] != str2[0]:
        print(str1[0])
        return '.'
    return compare_str(str1[1:],str2[1:])

print(compare_str("AABBBBAAB","AABBBBAAB"))```
autumn breach
#

Do you see how you have return “*”

#

And return “.”

tame dagger
#

yes - my output was only 1 *

tough pike
autumn breach
#

I think you want those to be return “*” + compare_str(str1[1:0], str2[1:0]

cobalt steppe
tame dagger
tough pike
#

this is recursion, in the case where strings are not empty, compare compares the first characters of them, and adds that with the result of comparing the rest of the string
i just wrote it in uhh, something inbetween python and haskell

tame dagger
#
    if not str1:
        return 0
    return ("*" if str1[0]==str2[0] else ".") + compare_str(str1[1:],str2[1:])```
#

i think it doesnt work because i concat a str with function..

#

int to str because it returns 0

tough pike
#

no, it is because in the end, you add a string with 0, like, "." + 0
return an empty string in the base case

autumn breach
#

Oh you did that nevermind

#

Instead of zero you just want an empty string

tame dagger
#

return ''

#

ahhhhhhhhh

#
    if not str1:
        return ''
    return ("*" if str1[0]==str2[0] else ".") + compare_str(str1[1:],str2[1:])

print(compare_str("AABBBBAAB","AABBBBAAB"))```
#

("*" if str1[0]==str2[0] else ".") this part is really helpful guys

#

over here i am assuming both strings are equal length, hence if not str1 or 2 is fine

tough pike
#

!e

def f(xs: str, ys: str) -> str:
  n = len(xs)
  m = len(ys)
  if n != m:
    raise ValueError
  return g(n, bytearray(b'.'*n), xs, ys, 0).decode()

def g(n: int, b: bytearray, xs: str, ys: str, i: int) -> bytearray:
  if i >= n:
    return b
  if xs[i] == ys[i]:
    b[i] = 42
  return g(n, b, xs, ys, i+1)

xs = ("A"*500)+("B"*500)
ys = ("A"*250)+("B"*250)+("A"*250)+("B"*250)
print(f(xs, ys))
daring grailBOT
# tough pike !e ```py def f(xs: str, ys: str) -> str: n = len(xs) m = len(ys) if n != m...

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 17, in <module>
003 |     print(f(xs, ys))
004 |           ^^^^^^^^^
005 |   File "/home/main.py", line 6, in f
006 |     return g(n, bytearray(b'.'*n), xs, ys, 0).decode()
007 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 |   File "/home/main.py", line 13, in g
009 |     return g(n, b, xs, ys, i+1)
010 |            ^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/XYL63YDVNZ4I7Q76XMYASNDCIQ

tough pike
#

oops it has too small of a stack size

#

!e

import sys
sys.setrecursionlimit(1100)

def f(xs: str, ys: str) -> str:
  n = len(xs)
  m = len(ys)
  if n != m:
    raise ValueError
  return g(n, bytearray(b'.'*n), xs, ys, 0).decode()

def g(n: int, b: bytearray, xs: str, ys: str, i: int) -> bytearray:
  if i >= n:
    return b
  if xs[i] == ys[i]:
    b[i] = 42
  return g(n, b, xs, ys, i+1)

xs = ("A"*500)+("B"*500)
ys = ("A"*250)+("B"*250)+("A"*250)+("B"*250)
print(f(xs, ys))
daring grailBOT
# tough pike !e ```py import sys sys.setrecursionlimit(1100) def f(xs: str, ys: str) -> str:...

:white_check_mark: Your 3.12 eval job has completed with return code 0.

**********************************************************************************************************************************************************************************************************************************************************....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................**********************************************************************************************************************************************************************************************************************************************************
... (truncated - too long)

Full output: https://paste.pythondiscord.com/PCLOBWMQVJ4CTD4YWBXVTNM654

tough pike
#

if only python had tail call optimization

tame dagger
#

!e ```def compare_str(str1,str2):
if not str1:
return ''
return ("*" if str1[0]==str2[0] else ".") + compare_str(str1[1:],str2[1:])

print(compare_str("AABBBBAAB","AABBBBAAB"))```

daring grailBOT
tame dagger
tough pike
#

basically, it is an optimization, that lets avoid allocating a new stack frame when you have a recursive function with a return that is like return function(but, with, new, arguments) - you can kinda just replace the arguments in the current frame, and start from the body again
python doesnt have it, and as you can see, trying to use our recursive function on a string the length of which was greater than the stack size resulted in an error
it is a pretty essential thing for tail recursive functions that end up reaching a lot of depth

tame dagger
#

thank you !

daring grailBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.