py刷题



# 1-2 *****
#  在同一行依次输入三个值a,b,c,用空格分开,输出b*b-4*a*c的值

a,b,c = input().split()
a,b,c = eval(a),eval(b),eval(c) # eval代替int float
d = b*b-4*a*c
print(d)

# 1-1
# 本题目要求读入2个整数A和B,然后输出它们的和。
""" 这是回车分隔
a=int(input())
b=int(input())
print(a+b)
"""

# 1-3
s = "你好,python"
print(s .encode("utf-8"))


# 2 - 1
m = int(input())
sum = 0
for i in range(11,m+1):
    sum += i
    i = i + 1
print("sum = {}".format(sum))




# 2 - 2
x = float(input())
if (a == 0):
    print("f(0.0) = 0.0")
else :
    print("f({:.1f}) = {:.1f}".format(a,1/a))

2 - 3
n = eval(input())
if (n <= 50 and n >= 0):
    cost = 0.53 * n
    print("cost = {:.2f}".format(cost))
elif(n > 50):
    over = n - 50
    cost = 0.53 * 50 + over * 0.58
    print("cost = {:.2f}".format(cost))
else :
    print("Invalid Value!")




# 2 - 4
a,n = input().split()
a,n = eval(a),eval(n)
tem = a
sum = 0
for i in range(n):
    sum += tem
    tem = tem * 10 + a
print("s = {}".format(sum))




# 2 - 5
n = int(input())
sum = 0
for i in range(1,n*2+1,2):
    sum += 1/i
print("sum = {:.6f}".format(sum))

"""
法二:
a=int(input())
sum=0
x=-1
for i in range(1,a+1):
    x=x+2
    sum=sum+1/x
print("sum = {:.6f}".format(sum))
"""




# 2 - 6
n = int(input())
sum = 0
x = 1
for i in range(1,n+1):
    down = i *2 - 1
    term = i / down
    sum += term * x
    x *= -1
print("{:.3f}".format(sum))

"""
改进:
python中的循环i主要是为了循环 尽量不加入运算
所以:另设一个x 每次加1
a=int(input())
sum=0
x=0
y=-1
flag=1
for i in range(1,a+1):
    x=x+1
    y=y+2
    sum=sum+x/y*flag
    flag=-flag
print("{:.3f}".format(sum))

"""




# 2 - 7
"""
读入2个正整数A和B,1<=A<=9, 1<=B<=10,产生数字AA...A,一共B个A
输入eg :1.        ​3  ,4(带空格)
        2.  ​1,  5

"""

a,b=input().split(",")  # 这几步主要是为了除去空格和复合题目要求输入
c,d=a.strip(),b.strip()
f=int(d)
n=int(c[0]*f)  # 巧妙利用python特性
print(n)

# 改进:
a,b=input().split(",")  # 这几步主要是为了除去空格和复合题目要求输入
c,d=a.strip(),int(b)  # int()本身就会去除空格
n=int(c[0]*d)  # 巧妙利用python特性
print(n)






# 2 - 8
a,b = input().split(",",1)
# Python split() 通过指定分隔符对字符串进行切片,
# 如果参数 num 有指定值,则分隔 num+1 个子字符串
# num -- 分割次数。默认为 -1, 即分隔所有
b = eval(b)
c = int(a,b)
print(c)








# 2 - 9
"""
本题要求将输入的任意3个整数从小到大输出。
输入在一行中给出3个整数,其间以空格分隔。
在一行中将3个整数从小到大输出,其间以“->”相连。
"""
# 输入2 5 4
print(*sorted(map(int, input().split())), sep="->")  # 2->4->5
print(sorted(map(int, input().split())), sep="->")  # [2,5,4]


"""
 注:星号是用来拆包的,sep改变输出的方式(默认为空格)
 
 python3中,map函数返回的是一个map对象,要想得到列表时,需要list(map(fun,itor))来将映射之后的map对象转换成列表

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,
得到一个新的 迭代器对象 并返回。(可用list()修改为列表)


sort 与 sorted 区别:

1. sort 是应用在" list "上的方法," sorted "可以对所有可迭代的对象进行排序操作。
a.sort() --> print(a) 
b = sorted(a) --> print(b)        

2. list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

3. sorted(iterable, key=None, reverse=False)  
 key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序
 常常是lambda函数 要是使其逆序就加个“-”
 
 eg:先按照成绩降序排序,相同成绩的按照名字升序排序:
d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print(l)


"""



# 2 - 10
"""
接着每行输出一个华氏温度fahr(整型)与一个摄氏温度celsius(占据6个字符宽度,靠右对齐,保留1位小数)
"""
a,b=input().split()
a,b=eval(a),eval(b)
if(a>b):
    print("Invalid.")
else:
    print("fahr celsius")
    i = a
    while i <= b:
        print("{:d}{:>6.1f}".format(i,5*(i-32)/9))  # (">"是右对齐)
        i += 2





# 2 - 11
m,n = input().split()
m,n = int(m),int(n)
sum = 0
for i in range(m,n+1):
    sum += i**2 + 1/i
print('sum = {:.6f}'.format(sum))

"""
改进代码:
m, n = map(int,input().split())
print("sum = %.6f"% sum([m*m+1/m for m in range(m,n+1)]))

"""






# 2 - 12
a, b, c = input().split()
a, b, c = eval(a),eval(b),eval(c)
if (a+b>c and a+c>b and b+c>a):
    s = (a+b+c)/2
    area = (s*(s-a)*(s-b)*(s-c))**0.5
    print('area = {:.2f}; perimeter = {:.2f}'.format(area,s))
else :
    print('These sides do not correspond to a valid triangle')







# 2 - 13
a, b = input().split()
a, b = eval(a),eval(b)
sum = 0
cnt = 0
for i in range (a,b+1):
    cnt = cnt + 1
    sum += i
    print('{:>5d}'.format(i),end='')
    if ( cnt % 5 == 0 and i != a and i != b):
        print('\n',end = '')  # 这里也要 "end ="
        # 或者写print()
print('\nSum = {}'.format(sum))
"""
另一种写法:
a,b=input().split()
a,b=eval(a),eval(b)
cnt=0
sum=0
for i in range(a,b+1):
    print("{:>5d}".format(i),end="")
    cnt=cnt+1
    sum=sum+i
    if(cnt==5):
        print("\n",end="")
        cnt=0
    elif(i==b):
        print("\n",end="")
print("Sum = {:d}".format(sum))

"""




# 3-1 :
lst = list(map(eval,input().split())) #这种写法可以读入一组按相同方式的数字
sum=0
for i in range(0,len(lst)):
    sum=sum+lst[i]
aver=sum/len(lst)
for i in range(0,len(lst)):
    if(lst[i]>aver):
        print('{:d} '.format(lst[i]),end="") # 数字后自带一个空格







# 3 - 2:

def judge(mlist, jlist, flist):
    sum = 0
    x = 0
    lnum = mlist[-1]
    mlist = mlist[:17] # 剩下最后一位lnum,只取前17位

    for i in mlist:
        if i >= '0' and i <= '9':
            sum += int(i) * flist[x]
            x += 1
        else:
            return False
    re = sum % 11
    if jlist[re] == lnum:
        return True
    else:
        return False

num = int(input())
cnt = 0
jlist = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
flist = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
for i in range(num):
    mlist = input()
    if judge(mlist, jlist, flist) == False:
        print(mlist)
    else:
        cnt = cnt + 1
if cnt == num:
    print("All passed")

# 3 - 3:
str = input()
str = str[::-1]
a, b = input().split()
x = len(str)-1
for i in str:
    if (i == a or i == b):
        print('{} {}'.format(x,i))
    x = x - 1

"""
法二:索引
s = input()
m, n=input().split()
s=s[::-1]
for i in range(0,len(s)):
    if(n==s[i]):
        print("{:d} {:s}".format(len(s)-i-1,n))
for i in range(0, len(s)):
    if (m == s[i]):
        print("{:d} {:s}".format(len(s) - i - 1, m))

"""

# 3 - 4  直接find函数
a = input()
b = input()
if b.find(a) != -1:
    b = b[::-1]
    print('index = {:d}'.format(len(b) - b.find(a) - 1))
else:
    print('Not Found')






# 3 - 5

a = input()
b = []
for n in a :
   if n.isdigit() :
      b.append(n)
print(int("".join(b)))


"""   自己的方法 字符串拼接
a = input()
b = ""
for n in a :
   if n.isdigit() :
      b += n
print(int(b))
"""







# 3 - 6
"""
Python 字典(Dictionary) get()方法:
dict.get(key, default=None)
返回对应键的值
default -- 如果指定键的值不存在时,返回该默认值
"""
res = []
counts = {}
lst = list(map(int,input().split()))
t = lst[1: lst[0]+1] # lst【0】+1可以不写
for word in t:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
# 用和
# 7 2 5 3 0 2 5 2
# dict_items([(2, 3), (5, 2), (3, 1), (0, 1)])
# [(2, 3), (5, 2), (3, 1), (0, 1)]
items.sort(key=lambda x:x[1], reverse=True)
word, count = items[0]
print ("{:d} {:d}".format(word, count))

"""
 法二:
arr = list(map(int, input().split()))
list1 = arr[1 : arr[0] + 1]
counts = {}
for word in list1:
    if word not in counts:
        counts.update({word : list1.count(word)})
max = max(counts.values())  # Python 字典(Dictionary) values() 函数以列表返回字典中的所有值。
for key, value in counts.items():
    if value == max:
        print(key, value)
"""

"""
c语言版:
//满意请采纳
#include<stdio.h>
int main(){
    int a[10010]={0},i,j,k,kind,max;
    while(~scanf("%d",&k)){
        for(i=0;i<k;i++){
            scanf("%d",&kind);
            a[kind]++;
        }
        max=0;
        for(i=1,j=0;i<=10000;i++){
            if(a[i]>max){
                max=a[i];
                j=i;
            }
            else if(a[i]==max){
                if(i<j)
                    j=i;
            }
        }
        printf("%d\n",j);
    }
    return 0; 
}
"""




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值