【问题标题】:How to retrieve a unique character from a string using while loop如何使用while循环从字符串中检索唯一字符
【发布时间】:2021-04-25 04:01:36
【问题描述】:

我的任务是创建一个函数,该函数在字符串中查找唯一字符,然后将其值加到 10。对于这种特定情况,dice_str 的 len 始终为 3,并且始终存在唯一的该字符串内的字符。到目前为止,这是我的代码:

def get_point_score(dice_str):
    unique = ""
    i = 0
    
    while len(unique) != 1:
        if dice_str[i] not in dice_str[i+1:]:
            unique += dice_str[i]
            sum = 10 + int(unique)
        else:
            i += 1
            unique += unique
        
        
    return sum

预期输出:

dice_str = "141"
value = 14

Got:
value = 11

我们被要求使用 while 循环、索引和 find() 来解决这个问题。

我正在考虑遍历字符串中的每个元素并使用索引来查看它是否重复,以及是否重复将 i 增加 1 并继续检查直到不再是这种情况。从输出看来我未能正确实现这一点,所以我正在考虑使用 find() 并且一旦 find() 返回 -1,将元素添加到空字符串,但我也不确定如何实现正确的。任何帮助将不胜感激

【问题讨论】:

  • 它为我输出正确的值。
  • 我也是这么想的。它适用于“141”,但通常不正确。
  • 我没有得到这个语句,“将其值加到 10” -> 将 10 加到每个唯一值或最后?
  • @HenryEcker 啊,你是对的。有一些极端情况,比如没有唯一元素或者唯一元素是最后一个怎么办?
  • 另外,我看到每次sum 被一个新值覆盖,这是预期的吗?

标签: python


【解决方案1】:

你的问题是你的支票if dice_str[i] not in dice_str[i + 1:]:

注意这个例子"116"

在您第一次通过时,您将检查 1 是否在 16 中。它是什么。

然后您检查1 是否在6 中,但不是。但是你执行这个操作:

unique += dice_str[i]

但是在这种情况下,您的唯一值是6(索引i + 1)而不是1(索引i)。


您在实施过程中非常接近。您可以构建一个排除当前索引的列表,而不是测试一个值是否为not in,而是针对它进行测试:

def get_point_score(dice_str):
    i = 0
    unique = None
    while not unique:
        if dice_str[i] not in (dice_str[:i] + dice_str[i + 1:]):
            unique = dice_str[i]
        i += 1
    return 10 + int(unique)

*警告如果您的列表不包含至少一个唯一值,这将引发错误。


鉴于保证长度为 3 的字符串具有单个唯一字符,您可以只进行左/右比较。

def get_point_score(dice_str):
    left_match = dice_str[0] == dice_str[1]  # Do 0 and 1 Match?
    right_match = dice_str[1] == dice_str[2]  # Do 1 and 2 Match?

    if not left_match and not right_match:
        # Neither Match (Middle Unique)
        unique = dice_str[1]
    elif left_match:
        # 0 and 1 Match, but 1 and 2 don't (Right Unique)
        unique = dice_str[2]
    else:
        # 0 and 1 Don't Match, but 1 and 2 do (Left Unique)
        unique = dice_str[0]
    return 10 + int(unique)


print(get_point_score("116"))
print(get_point_score("141"))
print(get_point_score("722"))

输出:

16
14
17

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2012-03-09
    • 2020-01-10
    • 2017-04-16
    • 2018-03-08
    相关资源
    最近更新 更多