【问题标题】:How do you read whitespaces in a string?如何读取字符串中的空格?
【发布时间】:2020-11-23 03:01:09
【问题描述】:

问题是计算机械手在移动键盘(在屏幕触控发明之前手机曾经拥有的旧键盘)中键入消息所需的时间。手的初始位置在键 1。

例如:如果它应该键入“hack”,则从键 1 移动到键 4 需要 1 秒,然后键入“h”需要 2 秒。 现在再用 1 秒从键 4 移动到键 2,然后再用 1 秒输入“a”。 由于“c”出现在与“a”相同的键上,因此移动时间为 0。因此只需 3 秒即可键入“c”。 最后它在 1 秒内从键 2 移动到键 5,然后在 2 秒内输入“k”。所以输入“hack”总共需要 1+2+1+1+3+1+2= 11 秒。

这是我解决上述问题的代码:

testcases=int(input())
position=1
seconds=0
dictionary={1:".,;?", 2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 
               7:"pqrs", 8:"tuv", 9:"wxyz", 0:" " }
numbers=['1','2','3','4','5','6','7','8','9','0']


for test in range(testcases):
    string=input()
    for character in string:
        if character in numbers:
            if position==character:
                seconds+=1
            else:
                position=character
                seconds+=2
        else:
            for keys in dictionary.keys():
                if character in dictionary[keys]:
                    if int(position)==keys:
                        seconds+=dictionary[keys].index(character)+1
                    else:
                        position=keys
                        seconds+=dictionary[keys].index(character)+2
                    break
    print(seconds)
    position,seconds=1,0
    
        

它工作正常,但现在的问题是我如何读取字符串中的空格?

【问题讨论】:

  • 我找不到代码有什么问题。据我所知,它确实可以正确处理空间。
  • 空格是什么意思。是按空格键还是别的什么。
  • 假设字符串是"hacker earth",那么输入之间的空格大约需要 2 秒(按两次 0 会留出空格)
  • 这能回答你的问题吗? Reading Space separated input in python

标签: python dictionary


【解决方案1】:

你可以使用字符串模块。

import string
dictionary={1:".,;?", 2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 
               7:"pqrs", 8:"tuv", 9:"wxyz", 0:string.whitespace}

然后检查输入的键是否为空格。

if key in dictionary.get(0):
    print('Whitespace is entered.')

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多