Python—ex06—列表、元组和字典
2019.12.23日
求最大值及其最小下标
描述
找出给定的n个数中的最大值及其对应的最小下标(下标从0开始)
输入格式:
输入在第一行中给出一个正整数n(1<n≤10)。第二行输入n个整数,用空格分开。
输出格式:
在一行中输出最大值及最大值的最小下标,中间用一个空格分开。
输入输出示例
输入 输出
示例 1
6
2 8 10 1 9 10
10 2
n = input()
lis = list(map(int,input().split())) #map的用法,比如此处:list(map(int,input().split()))
max = lis[0]
k = 0
for i in range(1,int(n)):
if max<lis[i]: #现设一个数,再进行比较,这也是一种常见的方法
max = lis[i]
k = i
print(max,k)
Python map() 函数 | 菜鸟教程
https://www.runoob.com/python/python-func-map.html
删除重复字符
描述
将给定字符串去掉重复的字符后,按照字符ASCII码顺序从小到大排序后输出。忽略原字符串中的空格。
输入格式:
输入是一个以回车结束的非空字符串(少于80个字符)。
输出格式:
输出去重排序后的结果字符串。
输入输出示例
输入 输出
示例 1
ad2f3adjfeainzzzv
23adefijnvz
n = input()
s = set(n) #创建一个无重复的列表
for i in s:
if i is " ": #排除空格
s.remove(i) #移除空格
break #停止循环
n = "".join(sorted(s)) #排序拼接
print(n)
输出斐波那契数列中小于n的所有值
描述
斐波那契数列,又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)在现代物理、准晶体结构、化学等领域,斐波纳契数列都有直接的应用。
写一个函数名为Fibonacci,带一个参数n,函数打印斐波那契数列中所有小于n的值。函数没有返回值。
输入输出示例
输入 输出
示例 1
50
0 1 1 2 3 5 8 13 21 34
def Fibonacci(n):
"""accept an integer n.
return the numbers less than n in Fibonacci sequence."""
n = int(n)
def f(k):
if k == 1:
return k
elif k == 0:
return k
else:
return f(k - 1) + f(k - 2) #递归
for i in range(0,100):
if f(i) >= n:
break
print(f(i),end=" ")
n = input()
Fibonacci(n)
统计单词出现次数
描述
写程序统计下面字符串中每个单词出现的次数,不区分大小写。
myString = "This is the string whose words we would like to count. "
"This string contains some repeated words, "
"as well as some unique words. "
"It contains punctuation, "
“and it contains words that are capitalized in different ways.”
"If the method we write runs correctly, "
"it will count 4 instances of the word ‘it’, "
"3 instances of the word ‘this’, "
“and 3 instances of the word ‘count’.”
输入输出示例
此程序输出为一个字典,字典的键是字符串中每个单词,值是单词的个数。
所有单词一律按照小写对待,去除字符串中的标点符号。
myString = "This is the string whose words we would like to count. " \
"This string contains some repeated words, " \
"as well as some unique words. " \
"It contains punctuation, " \
"and it contains words that are capitalized in different ways. " \
"If the method we write runs correctly, " \
"it will count 4 instances of the word 'it', " \
"3 instances of the word 'this', " \
"and 3 instances of the word 'count'."
import string
for i in myString:
if i.isupper:
myString = myString.replace(i,i.lower()) #先大小写替换
if i in string.punctuation: #判断是否是标点,替换为‘’(无)
myString = myString.replace(i,"")
lst = myString.split(" ")
wordDictionary = {}
for i in lst:
if i in wordDictionary:
wordDictionary[i] += 1
else:
wordDictionary[i] = 1
key = input()
print(wordDictionary[key]) #分清楚键和值