Python字典与递归编程实践

1、计算机如何知道要请求什么输入?它如何知道针对输入应采取什么行动?它如何知道要生成什么输出,以及应以何种形式呈现?

The answer to all of these questions is “a person gave the computer instructions and the computer carried them out”.

2、编写一个名为reverseLookup的函数,该函数能找出字典中所有映射到特定值的键。该函数将字典和要搜索的值作为仅有的参数。它将返回一个(可能为空的)列表,其中包含字典中映射到给定值的键。在你的解决方案中包含一个主程序来演示reverseLookup函数。你的程序应该创建一个字典,然后展示reverseLookup函数在返回多个键、单个键和不返回键的情况下都能正常工作。确保只有当包含此练习解决方案的文件未被导入到其他程序中时,主程序才会运行。

# Conduct a reverse lookup on a dictionary
# @param data the dictionary on which the reverse lookup is performed
# @param value the value to search for in the dictionary
# @return a list (possibly empty) of keys from data that map to value

def reverseLookup(data, value):
    # Construct a list of the keys that map to value
    keys = []
    # Check each key and add it to keys if the values match
    for key in data:
        if data[key] == value:
            keys.append(key)
    # Return the list of keys
    return keys

# Demonstrate the reverseLookup function

def main():
    # A dictionary mapping 4 French words to their English equivalents
    frEn = {"le": "the", "la": "the", "livre": "book", "pomme": "apple"}
    # Demonstrate the reverseLookup function with 3 cases: One that returns multiple keys,
    # one that returns one key, and one that returns no keys
    print("The french words for ’the’ are: ", reverseLookup(frEn, "the"))
    print("Expected: [’le’, ’la’]")
    print()
    print("The french word for ’book’ is: ", reverseLookup(frEn, "book"))
    print("Expected: [’livre’]")
    print()
    print("The french word for ’banana’ is: ", reverseLookup(frEn, "banana"))
    print("Expected: []")

if __name__ == "__main__":
    main()

3、在一些基本的手机上,可以使用数字键盘发送短信。由于每个按键都关联着多个字母,大多数字母需要多次按键。按一次数字会生成该按键对应的第一个字符,按2、3、4或5次会分别生成第二个、第三个、第四个或第五个字符。编写一个程序,显示用户输入的消息所需的按键组合。构建一个字典,将每个字母或符号映射到生成它所需的按键组合。然后使用该字典创建并显示用户消息所需的按键组合。确保程序能处理大写和小写字母,忽略不在字典中的字符,如分号和括号。

以下是一个Python程序来解决这个问题:

# 构建字典,将每个字母或符号映射到生成它所需的按键组合
keypad = { 
    '.': '1', ',': '11', '?': '111', '!': '1111', ':': '11111', 
    'A': '2', 'B': '22', 'C': '222', 'D': '3', 'E': '33', 'F': '333', 
    'G': '4', 'H': '44', 'I': '444', 'J': '5', 'K': '55', 'L': '555', 
    'M': '6', 'N': '66', 'O': '666', 'P': '7', 'Q': '77', 'R': '777', 
    'S': '7777', 'T': '8', 'U': '88', 'V': '888', 'W': '9', 'X': '99', 
    'Y': '999', 'Z': '9999', ' ': '0'
}

# 获取用户输入的消息
message = input('请输入消息: ')

# 初始化一个空字符串,用于存储按键组合
ke
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值