早教吧 育儿知识 作业答案 考试题库 百科 知识分享

python3问题1.WriteafunctionthatcheckswhethertwowordsareanagramsandreturnTrueiftheyareandFalsetheyarenot.Twowordsareanagramsiftheycontainthesameletters.Forexample,“silent”and“listen”areanagrams.Usethefollo

题目详情
python3问题
1.Write a function that checks whether two words are anagrams and return True if they are and False they are not.Two words are anagrams if they contain the same letters.For example,“silent” and “listen” are anagrams.Use the following function header:
def is_anagram(word1,word2):
Write a main function that prompts the user to enter two strings,calls the is_anagram function and then reports whether the strings are anagrams or not.
Sample Output:
Enter the first string:listen
Enter the second string:silent
listen and silent are anagrams.
Another sample output:
Enter the first string:science
Enter the second string:biology
science and biology are not anagrams.
The template for the program is as follows:
def is_anagram(word1,word2):
# Write the function code here
def main():
# Write the main function
# Call the main function
main()
2.
Write a function called copy_list that takes in a list of lists of integers,and returns a copy of the list.The list that is returned should contain the same values as the original list,but changes made to one should not be made to the other.See the Expected Output of the Template Code.
For this question,use the main function included in the template code for testing.You do not have to write the main function yourself.However,you should test your function with input values other than the one provided to ensure it works correctly.You can assume that the function parameter will always be a list that contains only lists of 1 or more integers.
The template code is as follows:
def copy_list(number_list):
# Write your function code here
def main():
number_list = [[1,2,3],[4,5,6],[8,9],[10]]
new_list = copy_list(number_list)
print(number_list)
print(new_list)
number_list.pop()
new_list[0].append([11,12])
print(number_list)
print(new_list)
main()
Expected Output of Template Code
[[1,2,3],[4,5,6],[8,9],[10]]
[[1,2,3],[4,5,6],[8,9],[10]]
[[1,2,3],[4,5,6],[8,9]]
[[1,2,3,[11,12]],[4,5,6],[8,9],[10]]
▼优质解答
答案和解析
1:
def is_anagram(word1,word2):
return not set(word1) ^ set(word2)
def main():
word1 = input("Enter the first string:")
word2 = input("Enter the second string:")
print("listen and silent are %s anagrams." % (
"" if is_anagram(word1,word2) else "not"))
if __name__ == "__main__":
main()
2:
def copy_list(number_list):
# Write your function code here
return [x[:] for x in number_list[:]]
def main():
number_list = [[1,2,3],[4,5,6],[8,9],[10]]
new_list = copy_list(number_list)
print(number_list)
print(new_list)
number_list.pop()
new_list[0].append([11,12])
print(number_list)
print(new_list)