英文:
Fixing Python code which includes dictionaries
问题
使用字典来统计给定的“text”字符串中数字的频率。只应计算数字,不计算空格、字母或标点符号。完成该函数,以便像“1001000111101”这样的输入将返回一个包含字符串中每个数字出现次数的字典 { '1': 7, '0': 6 }。此函数应该:
- 通过函数的参数接受一个名为“text”的字符串变量。
- 初始化一个新的字典。
- 迭代每个文本字符,检查字符是否是数字。
- 计算输入字符串中数字的频率,忽略所有其他字符。
- 用数字作为键填充新的字典,确保每个键都是唯一的,并为每个键分配该数字的计数值。
- 返回新的字典。
def count_numbers(text):
# 初始化一个新的字典。
dictionary = {}
# 完成for循环,迭代每个"text"字符。
for i in text:
# 使用字符串方法完成if语句,检查字符是否是数字。
if i.isdigit():
# 使用逻辑运算符完成if语句,检查数字是否尚未在字典中。
if i in dictionary:
# 使用字典操作将数字添加为键,并将初始计数值设置为零。
dictionary[i] = 0
# 使用字典操作增加现有键的数字计数值。
dictionary[i] += 1
return dictionary
print(count_numbers("1001000111101"))
# 应返回 {'1': 7, '0': 6}
print(count_numbers("Math is fun! 2+2=4"))
# 应返回 {'2': 2, '4': 1}
print(count_numbers("This is a sentence."))
# 应返回 {}
print(count_numbers("55 North Center Drive"))
# 应返回 {'5': 2}
英文:
Use a dictionary to count the frequency of numbers in the given “text” string. Only numbers should be counted. Do not count blank spaces, letters, or punctuation. Complete the function so that input like "1001000111101" will return a dictionary that holds the count of each number that occurs in the string {'1': 7, '0': 6}. This function should:
- accept a string “text” variable through the function’s parameters;
- initialize a new dictionary;
- iterate over each text character to check if the character is a number;
- count the frequency of numbers in the input string, ignoring all other characters;
- populate the new dictionary with the numbers as keys, ensuring each key is unique, and assign the value for each key with the count of that number;
- return the new dictionary.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
def count_numbers(text):
# Initialize a new dictionary.
dictionary = {}
# Complete the for loop to iterate through each "text" character.
for i in text:
# Complete the if-statement using a string method to check if the
# character is a number.
if i == int:
# Complete the if-statement using a logical operator to check if
# the number is not already in the dictionary.
if i in dictionary:
# Use a dictionary operation to add the number as a key
# and set the initial count value to zero.
dictionary.update({text, i})
# Use a dictionary operation to increment the number count value
# for the existing key.
i += i
return dictionary
print(count_numbers("1001000111101"))
# Should be {'1': 7, '0': 6}
print(count_numbers("Math is fun! 2+2=4"))
# Should be {'2': 2, '4': 1}
print(count_numbers("This is a sentence."))
# Should be {}
print(count_numbers("55 North Center Drive"))
# Should be {'5': 2}
<!-- end snippet -->
答案1
得分: 1
- 你正在向
count_numbers()
函数传递一个字符串(str),当你遍历一个字符串时,你总是得到字符串而不是你期望的整数(int
)。 - 即使你以某种方式获得了一个整数(
int
),你的if
语句也不会工作,因为i
不会等于 "int
",它会等于某个整数类型的值。在这种情况下,你可能希望将条件更改为类似于if isinstance(i, int)
。 - 但由于在遍历字符串的内容时总是获得字符串,你可以使用字符串方法
isdigit()
来检查字符串的内容是否是数字(i.isdigit()
)。 - 然后还有一个与字典处理有关的问题...你有几个选项...
字典处理
- 检查
i
是否在字典中(正如你所做的),如果是,检索其值并增加 - 如果不在字典中,将其设置为0。 - 使用字典的
get()
方法而不是下标(dictionary[i]
),因为get()
不会在项不存在时引发异常,而且它允许你传递一个可选的第二个参数,即在项不存在时返回的默认值(0
) - 然后只需增加并将其放回:dictionary[i] = dictionary.get(i, 0) + 1
(为了清晰和可读性,你可能想将这句分为三行 - 获取、增加、设置)。
英文:
I won't complete your assignment for you (because then you won't learn anything), but I'll offer some tips:
- You are passing a string (str) to the
count_numbers()
function, and when you iterate over a string, you always get strings back, and notint
s, as you are expecting - Even if you did somehow get an
int
, yourif
statement would not work, becausei
would not be equal to "int
", it would be equal to some value of type int. In that case, you would probably want to change the condition to something likeif isinstance(i, int)
- But since you always get strings when you iterate over the contents of a string, you can instead use the str method
isdigit()
to check if the contents of the string is a digit (i.isdigit()
) - Then there's an issue with your dictionary handling...you have a few options...
Dictionary Handling
- Check if
i
is in the dictionary (as you are doing), and if so, retrieve its value and increment - if it isn't in the dictionary, set to 0 - Use the dict's
get()
method instead of subscripts (dictionary[i]
), becauseget()
doesn't throw an exception if the item does not exist and it lets you pass an optional second parameter which is the default value to return if it doesn't exist (0
) - then just increment and put it back:dictionary[i] = dictionary.get(i, 0) + 1
(for clarity/readability, you may want to break this into three lines - get, increment, set)
答案2
得分: 0
def count_numbers(text):
# 初始化一个新字典。
dictionary = {}
for i in text:
if i.isnumeric():
if i in dictionary:
dictionary[i] = dictionary[i] + 1
else:
dictionary[i] = 1
return dictionary
英文:
def count_numbers(text):
# Initialize a new dictionary.
dictionary = {}
for i in text:
if i.isnumeric():
if i in dictionary:
dictionary[i] = dictionary[i]+1
else:
dictionary[i] = 1
return dictionary
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论