minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 1. Strings #2

Closed minimanimoh closed 3 years ago

minimanimoh commented 3 years ago

reverse the input string method 1

def string_reverser(our_string):
    new_string = ""

    for i in range(len(our_string)):
        new_string += our_string[(len(our_string)-1)-i]
    return new_string
minimanimoh commented 3 years ago

** remember the way to assign each index to reverse

minimanimoh commented 3 years ago

Anagrams The goal of this exercise is to write some code to determine if two strings are anagrams of each other.

An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).

For example:

"rat" is an anagram of "art" "alert" is an anagram of "alter" "Slot machines" is an anagram of "Cash lost in me" Your function should take two strings as input and return True if the two words are anagrams and False if they are not.

You can assume the following about the input strings:

No punctuation No numbers No special characters

def anagram_checker(str1, str2):

    if len(str1) != len(str2):
        new_str1 = str1.replace(" ","").lower()
        new_str2 = str2.replace(" ","").lower()

        if sorted(new_str1) == sorted(new_str2):
            return True

        return False
minimanimoh commented 3 years ago

Reverse the words in sentence


def word_flipper(our_string):

    word_list = our_string.split(" ")

    for idx in range(len(word_list)):
        word_list[idx] = word_list[idx][::-1]

    return " ".join(word_list)
minimanimoh commented 3 years ago
  1. to make string to list: use the split function
  2. remember "[::-1]" to reverse the order. [index][::-1] to reverse the order within the word of each sentence
minimanimoh commented 3 years ago

Hamming Distance In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Calculate the Hamming distace for the following test cases.

def hamming_distance(str1, str2):

    if len(str1) == len(str2):
        count = 0
        for char in range(len(str2)):
            if str1[char] != str2[char]:
                count += 1
        return count
    return None
minimanimoh commented 3 years ago
  1. to check the difference of the character in strings.. use for loop above!
    for **char** in range(len(str2))):
    **if str1[char] != str2[char]:**
  2. starting point is comparing the length which is reflected to "count = 0"
  3. return None position
minimanimoh commented 3 years ago

solved;

def hamming_distance(str1, str2):

    if len(str1) == len(str2):
        count = 0       
        for index in range(len(str1)):
            if str1[index] != str2[index]:
                count += 1
        return count
    return None