修复包含字典的Python代码。

huangapple go评论55阅读模式
英文:

Fixing Python code which includes dictionaries

问题

使用字典来统计给定的“text”字符串中数字的频率。只应计算数字,不计算空格、字母或标点符号。完成该函数,以便像“1001000111101”这样的输入将返回一个包含字符串中每个数字出现次数的字典 { '1': 7, '0': 6 }。此函数应该:

  1. 通过函数的参数接受一个名为“text”的字符串变量。
  2. 初始化一个新的字典。
  3. 迭代每个文本字符,检查字符是否是数字。
  4. 计算输入字符串中数字的频率,忽略所有其他字符。
  5. 用数字作为键填充新的字典,确保每个键都是唯一的,并为每个键分配该数字的计数值。
  6. 返回新的字典。
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:

  1. accept a string “text” variable through the function’s parameters;
  2. initialize a new dictionary;
  3. iterate over each text character to check if the character is a number;
  4. count the frequency of numbers in the input string, ignoring all other characters;
  5. 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;
  6. 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 &quot;text&quot; 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(&quot;1001000111101&quot;))
# Should be {&#39;1&#39;: 7, &#39;0&#39;: 6}

print(count_numbers(&quot;Math is fun! 2+2=4&quot;))
# Should be {&#39;2&#39;: 2, &#39;4&#39;: 1}

print(count_numbers(&quot;This is a sentence.&quot;))
# Should be {}

print(count_numbers(&quot;55 North Center Drive&quot;))
# Should be {&#39;5&#39;: 2}

<!-- end snippet -->

答案1

得分: 1

  1. 你正在向 count_numbers() 函数传递一个字符串(str),当你遍历一个字符串时,你总是得到字符串而不是你期望的整数(int)。
  2. 即使你以某种方式获得了一个整数(int),你的 if 语句也不会工作,因为 i 不会等于 "int",它会等于某个整数类型的值。在这种情况下,你可能希望将条件更改为类似于 if isinstance(i, int)
  3. 但由于在遍历字符串的内容时总是获得字符串,你可以使用字符串方法 isdigit() 来检查字符串的内容是否是数字(i.isdigit())。
  4. 然后还有一个与字典处理有关的问题...你有几个选项...

字典处理

  1. 检查 i 是否在字典中(正如你所做的),如果是,检索其值并增加 - 如果不在字典中,将其设置为0。
  2. 使用字典的 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:

  1. You are passing a string (str) to the count_numbers() function, and when you iterate over a string, you always get strings back, and not ints, as you are expecting
  2. Even if you did somehow get an int, your if statement would not work, because i 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 like if isinstance(i, int)
  3. 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())
  4. Then there's an issue with your dictionary handling...you have a few options...

Dictionary Handling

  1. 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
  2. Use the dict's get() method instead of subscripts (dictionary[i]), because get() 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

huangapple
  • 本文由 发表于 2023年2月26日 22:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定