可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
The assignment is to write a program that accepts two groups of words from the user and then prints a "True" statement if the two are anagrams (or at least if all the letters of one are present in the other) and a "False" statement if not.
Being very new to programming as a whole, I don't know how to move beyond just indexing a string and comparing all of the pieces of one to another. I stress that I am a beginner; I've read many of the other posts tagged with Python and Anagram, and they are uniformly above my head and reference things I have not been taught. So the simpler the better. Here is my non-working code so far:
s1 = input("Please enter a word:")
s2 = input("Please enter another word:")
for i in range(0, len(s1), 1):
if i in range (0, len(s2), 1):
print("The letters in your first word are present in your second word.")
回答1:
You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break
out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True
and then setting that to false if you find a letter that doesn't match.
Some other tips:
for l in s1
will loop through string s1 giving you access to each letter in sequence as l
- you don't need range
or len
at all
The if .. in
statement can help test whether a letter exists in a string, e.g. if letter in mystring:
is a valid statement and this could help you a lot, again not needing range
or len
You should avoid using numbers in variable names where possible - better would be word_one
and word_two
, as an example
回答2:
Why not just sort the strings?
>>> sorted('anagram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('nagaram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('anagram') == sorted('nagaram')
True
回答3:
You can use the magic Counter from collections library.
From documentation:
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values
So, you can initialize a Counter object with a string (a iterable) and compare with another Counter from a string
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
回答4:
def is_anagram(w1, w2):
w1, w2 = list(w1.upper()), list(w2.upper())
w2.sort()
w1.sort()
return w1 == w2
回答5:
>>> s1 = 'vivid'
>>> s2 = 'dvivi'
>>> s3 = 'vivid'
>>> def is_anagram(s1, s2):
... if s1.lower() == s2.lower():
... return False
... return sorted(s1.lower()) == sorted(s2.lower())
...
>>> is_anagram(s1, s2)
True
>>> is_anagram(s1, s3)
False
>>> s2 = 'dvivii'
>>> is_anagram(s1, s2)
False
>>> s2 = 'evivi'
>>> is_anagram(s1, s2)
False
>>>
回答6:
This worked for me
str1="abcd"
str2="bcad"
word1=[]
word2=[]
for x in range(len(str1)):
word1.append(str1[x])
for x in range(len(str2)):
word2.append(str2[x])
if(len(word1)==len(word2)):
for letter in word1:
if letter in word2:
word2.remove(letter)
if len(word2)==0:
print "anagram"
else:
print "not anagram"
回答7:
To check if two strings are anagrams of each other using dictionaries:
Note : Even Number, special characters can be used as an input
def anagram(s):
string_list = []
for ch in s.lower():
string_list.append(ch)
string_dict = {}
for ch in string_list:
if ch not in string_dict:
string_dict[ch] = 1
else:
string_dict[ch] = string_dict[ch] + 1
return string_dict
s1 = "master"
s2 = "stream"
a = anagram(s1)
b = anagram(s2)
if a == b:
print "Anagram"
else:
print "Not Anagram"
回答8:
You could use the following code it will not count special characters nor it will count digits and will return "they are anagrams" if the total characters have occurred equally in both strings hence will tell the the strings are anagrams or not .
text = input('Enter a string: ')
text1 = input('Enter a string: ')
text,text1 = text.lower(),text1.lower()
count = 0
count1=0
for i in range(97,123):
if chr(i) in text and chr(i) in text1:
count1+=1
if text.count(chr(i)) == text1.count(chr(i)):
count +=1
if len(text) >= len(text1):
num1 = len(text)
else:
num1 = len(text1)
if count == count1:
print("they are anagrams")
else :
print("they are not anagrams")
回答9:
Here's a solution if you are adamant on using Python dictionary and you can't use functional programming:
Create a dictionary using comprehension and compare the dictionaries of the two word with a simple ==
operator.
def isanagram2(wrd1, wrd2):
wrd1_dict = {k: 0 for k in wrd1}
wrd2_dict = {k: 0 for k in wrd2}
for c1, c2 in zip(wrd1, wrd2):
wrd1_dict[c1] += 1
wrd2_dict[c2] += 1
if wrd1_dict == wrd2_dict:
return True
return False
回答10:
Just a thought:
def check_(arg):
mark = hash(str(set(sorted(arg))))
return mark
def ana(s1, s2):
if check_(s1) != check_(s2):
pass
elif len(s1) != len(s2):
pass
else:
print("{0} could be anagram of {1}".format(s1, s2))
回答11:
#An anagram is the result of rearranging the letters of a word to produce a new word. Anagrams are case insensitive
#Examples:
# foefet is an anagram of toffee
# Buckethead is an anagram of DeathCubeK
# The shortest my function style ***************************************
def is_anagram1(test, original):
"""Сhecks 'test' is anagram of 'original' strings based on:
1. length of the both string and length of the sets made from the strings is equivalent
2. then checks equivalents of sorted lists created from test and original strings
>>> is_anagram1('Same','same')
False
>>> is_anagram1('toffee','foeftt')
False
>>> is_anagram1('foefet','toffee')
True
>>> is_anagram1("Buuckk",'kkkcuB')
False
>>> is_anagram1('Buckethead','DeathCubeK')
True
>>> is_anagram1('DeathCubeK','Buckethead')
True
"""
# check the length of the both string
if len(test) != len(original):
return False
# check is the strings are the same
t,o = test.lower(), original.lower()
if t == o:
return False
# check the sorted lists
return sorted(t) == sorted(o)
# The final my one line code **************************************
def is_anagram(test, original):
"""Сhecks 'test' is anagram of 'original' in one line of code
>>> is_anagram('Same','same')
False
>>> is_anagram('toffee','foeftt')
False
>>> is_anagram('foefet','toffee')
True
>>> is_anagram("Buuckk",'kkkcuB')
False
>>> is_anagram('Buckethead','DeathCubeK')
True
>>> is_anagram('DeathCubeK','Buckethead')
True
"""
return False if len(test) != len(original) or test.lower() == original.lower() else sorted(test.lower()) == sorted(original.lower())
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
### 2 items passed all tests:
### 6 tests in __main__.is_anagram
### 6 tests in __main__.is_anagram1
### 12 tests in 3 items.
### 12 passed and 0 failed.
### Test passed
回答12:
Simplest shortest solution
def anagram(word1, word2):
return sorted(word1) == sorted(word2)
check
print(anagram("xyz","zyx"))
>>True
print(anagram("xyz","zyy"))
>>False
回答13:
This case we check using two containers for each sorted string.
def anagram(s1, s2):
str1 = ''
str2 = ''
for i in s1:
str1 += i
for j in s2:
str2 += j
if str1 == str2:
return True
return False
回答14:
Anagrams are the two different words formed with same characters: For eg: EAT and TEA likewise there can be numerous examples.
One good way to see if give two words or sentences are anagrams is to set a counter array of size 256, and initially set all the values to 0. (This can be a good option if the input is bigger, at least than a few words) Now start reading the first string(word or a sentence), and increment its corresponding ASCII location in the array by one. Repeat this for the complete string.
Now start reading the second string and keep decreasing the corresponding ASCII counter of each letter in the array.
Finally, parse the array; if all the values are zero then the inputs were anagrams otherwise not.
Following is the commented code for the better understanding.
#include<iostream>
#include<string>
using namespace std;
bool is_anagram(string s1, string s2)
{
//Following statement chechs the base condition; if either of the strings is empty,
//return False
if(s1.length() == 0 || s2.length() == 0)
return false;
//initializing the counter array and setting it's values to 0
int counter[256] = {0};
//Calculating the lengths of both the strings
int len1 = s1.length();
int len2 = s2.length();
//Following is also a base condition that checks whether the strings are equal in
//length, if not we return False
if(len1 != len2)
return false;
//Following for loop increments the values of the counter array for the first
//string
for(int i = 0; i < len1; i++)
{
counter[s1[i]]++;
}
//This for loop decrements the values of the counter array for the second string
for(int i = 0; i < len2; i--)
{
counter[s2[i]]--;
}
//Now we check whether the counter array is empty/(or as it was initialized); if
//yes then the two strings are anagrams
for(int i = 0; i < 256; i++)
{
if(counter[i] != 0)
return false;
}
return true;
}
回答15:
Return True answers the question "Is w2 an anagram of a subsequence of w1"
Explanation: In the code below, we can answer two questions: 1) whether or not two strings are anagrams,2) If w2 is an anagram of a sub-sequence of w1. We use O(1) space (constant) and O(n) time. The dictionary d0 can be expanded to include any characters and we remain within O(1) space bound.
def anagrams(w1,w2):
d0={chr(i):0 for i in range(ord('a'),ord('z'))}
for char in w1:
d0[char]+=1
for char in w2:
if d0[char]==0:
return False
else:
d0[char]-=1
return sum([d0[x] for x in d0])==0 #return True (for subseqence anagram)
回答16:
Just another solution without using sort:
s1 = "aaabbbccc"
s2 = "abcabcabc"
def are_anagram1(s1, s2):
return [False, True][sum([ord(x) for x in s1]) == sum([ord(x) for x in s2])]
print are_anagram1(s1,s2)
NB: this works only for alphabet not numerals