Online Course Discussion Forum

Intro to algorithm Lesson 1 python HW question #4

 
 
WangJialin的头像
Intro to algorithm Lesson 1 python HW question #4
WangJialin - 2022年06月1日 Wednesday 21:38
 

in this question I am asked to define a function repeatedLetters to determine if the input(a string) has repeated letters in it. I figured out that a double loop would work, and it worked out as expected, however one thing that confused me is that "A" and "a" have to be considered as the same letter. I am not sure how to replace capital letters in a string with lower case ones. 


Here's my code, it works perfectly fine with lower case letters, but doesn't work with capital letters.


def repeatedLetters(x):

  for i in range(1,len(x)):

    for j in range(0,i):

      if x[i]==x[j]:

        return True;

        Break;

      else:

        pass;

  return False;


print(repeatedLetters("alphabet"));    # --->True

print(repeatedLetters("snake"));   # ---->False

print(repeatedLetters("Alphabet"));     #---->False

 
LensmireJohn的头像
Re: Intro to algorithm Lesson 1 python HW question #4
LensmireJohn - 2022年06月9日 Thursday 14:06
 

Let me give a short answer first.

Given a string S, there's a built in Python function .lower to convert all the letters to lowercase. So for a string S, S.lower() will have all the letters lowercase. For example "CAPITAL LETTERS".lower() will return "capital letters".

So the easiest way to accomplish what you want is to just convert the whole string into lowercase letters and go from there. (I'll let you guess what the function .upper() does as an alternate way to solve.)

More advanced / longer answer that may be helpful for dealing with characters (one letter strings) as well. It probably doesn't surprise you that inside a computer everything is represented as (binary) numbers, and Python has some ways to deal with characters as these numbers too.

Two functions worth mentioning: ord( c ) (for c a character) and chr( n ) for a number n.

ord(c) converts the character c into a number, while chr( n ) converts that number back into the corresponding character.

For example ord("A") gives 65 so chr(65) gives "A". There's not a super clear ordering of the symbols (and this also works for other symbols like "[" or "2", etc.), but at least there are some patterns. The characters "A", "B", "C", etc. all appear in order, so ord("A") is 65, ord("B") is 66, ord("C") is 67 up to ord("Z") is 90.  There's a few other characters mixed in, but then ord("a") is 97 up to ord("z") is 122.

This gives us an idea how something like the function lower() could work. Given a character, we know it is an uppercase letter if it's ord() value is in the range 65 to 90, and then we could convert it to lowercase by adding 32 to this value.

Hope this helps!

WangJialin的头像
Re: Intro to algorithm Lesson 1 python HW question #4
WangJialin - 2022年06月10日 Friday 22:10
 

Thank you so much! it works now