Skip to content

Instantly share code, notes, and snippets.

@Soben
Created August 2, 2023 23:53
Show Gist options
  • Save Soben/a08957e05eb777420dc5c9b1ea8bc72d to your computer and use it in GitHub Desktop.
Save Soben/a08957e05eb777420dc5c9b1ea8bc72d to your computer and use it in GitHub Desktop.
Cassidoo | isAnagram

Solution to Cassidoo's Week of July 31, 2023 Challenge

Given two strings s and t, return true if t is an anagram of s, and false otherwise. Try this in a language you're not comfortable with!

Realized there were a couple edge cases, like with anagrams involving differences in several words, but are still valid. Adjusted accordingly.

Never wrote anything in Python before, but besides being able to look up equivalent php functions in python, it was thankfully pretty one-to-one conversion.

<?php
function isAnagram($string1, $string2) {
$string1 = strtolower(str_replace(' ', '', $string1));
$string2 = strtolower(str_replace(' ', '', $string2));
if (strlen($string1) != strlen($string2)) return false;
if ($string1 == $string2) return false;
$arr1 = str_split($string1);
$arr1 = asort($arr1);
$arr2 = str_split($string2);
$arr2 = asort($arr2);
return ($arr1 == $arr2);
}
var_dump(isAnagram('race', 'care'));
var_dump(isAnagram('race', 'race'));
var_dump(isAnagram('barbie', 'care'));
var_dump(isAnagram('I am Lord Voldemort', 'Tom Marvolo Riddle'));
def isAnagram(string1, string2):
string1 = string1.lower().replace(' ', '')
string2 = string2.lower().replace(' ', '')
if len(string1) != len(string2):
return False
if string1 == string2:
return False
string1 = sorted(string1)
string2 = sorted(string2)
if string1 == string2:
return True
return False
print(isAnagram('race', 'care'))
print(isAnagram('race', 'race'))
print(isAnagram('barbie', 'care'))
print(isAnagram('I am lord Voldemort', 'Tom Marvolo Riddle'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment