Python Forum
help comparing strings - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: help comparing strings (/thread-35911.html)



help comparing strings - xander - Dec-28-2021

Hi guys. I really got stuck with my homework assignment. Can you guys please help me to reduce the complexity of the code below?
but first, the task is:

Two strings are called similar up to addition by a constant if by simple adding of an integer Ci,iϵ{A−Z} to a character we can translate one string to another and vice versa (using another constant). For example, BOB is similar up to addition by a constant to POP, while we map B to P and O to O. Both of these are similar up to addition by a constant to PIP, where O is mapped to I and the rest of the letters - as for the previous example. BOT is not similar up to addition by a constant to any of these, since B and T can't map to the same symbol (without a proof). Write a code that checks if one string is similar up to addition by a constant to another. This might be easily checked for each string against the other sepparately at O(n^2) , here you may have an extra space of O(n) in order to solve the question at O(n) .

So far my code is:
def ascs(letter):
  sum=0
  pow=1
  for i in letter:
    sum=sum+ord(i)*(2**pow)
    pow=pow+1
  return sum

def contain_duplicates(list):
    return len(set(list)) != len(list)


def excs4(char1,char2):
  empty=[]
  temp=[]
  for i in range(0,len(char1)):
    temp.append(char1[i]+char2[i])
    empty.append(ascs(char1[i]+char2[i]))
  return contain_duplicates(empty)
excs4("BIB","ZIP")



RE: help comparing strings - Larz60+ - Dec-29-2021

show us what you wrote good or bad.


RE: help comparing strings - ibreeden - Dec-29-2021

Hi @xander ,
Welcome to the forum. It is good you added your code, but please also read how to use BBcode. You have to mark your code and press the "Insert python" button.

But what is your question? Reduce complexity? The code seems quite compact to me. But there are a few things not OK:
  • NEVER use built-in names like in def contain_duplicates(list). "list" is a built-in.
  • The names you use are not very descriptive. For example: "char1" appears to be a word, not a character. "empty=[]" does not remain empty.
Please enhance your code (using BBcode) and we will see if we can make it less complex.


RE: help comparing strings - BashBedlam - Jan-04-2022

I agree with @ibreeden with regard to the changes that should be made. That being said, your code actually works as expected. You only need to print the results.
print (excs4("BIB","ZIP"))
print (excs4("BIB","PIP"))
Output:
False True