【python】习题 6-10周(中)

简介: 【python】习题 6-10周(中)

【python】习题 6-10周(上)https://developer.aliyun.com/article/1507470?spm=a2c6h.13148508.setting.22.1b484f0eD2AqhJ

7-06 Dictionary

输入样例:

在这里给出一组输入。例如:

2
like love
love like
2
like
love
3
beauty pure
king queen
season summer
3
base
king
season

输出样例:

在这里给出相应的输出。例如:

love
like
base
queen
summer

代码:

dict1 = {}
while True:
    try:
        n = int(input())
        for i in range(n):
            s = input().split()
            dict1[s[0]] = s[1]
        m = int(input())
        for j in range(m):
            t = input()
            if t in dict1.keys():
                print(dict1[t])
            else:
                print(t)
    except:
        break

7-07 通过两个列表构建字典

输入样例:

学校 城市 邮编
集美大学 厦门 361021

输出样例:

[('城市', '厦门'), ('学校', '集美大学'), ('邮编', '361021')]

代码:

# str1 = input().split()
# str2 = input().split()
# dirs = dict(zip(str1, str2))
# ans = list(dirs.items())
# ans.sort()
# print(ans)
keys = list(input().split())
values = list(input().split())
dict1 = dict(zip(keys, values))
ans = sorted(dict1.items())
print(ans)

7-08 两数之和

输入样例1:

在这里给出一组输入。例如:

2,7,11,15
9

输出样例1:

在这里给出相应的输出。例如:

0 1

输入样例2:

在这里给出一组输入。例如:

3,6,9
10

输出样例2:

在这里给出相应的输出。例如:

no answer

代码:

line = list(map(int, input().split(",")))
num = int(input())
flag = 0
for i in range(len(line) - 2):
    for j in range(i + 1, len(line) - 2):
        if num == line[i] + line[j]:
            flag = 1
            print("%d %d" % (i, j))
            break
    if flag == 1:
        break
if flag == 0:
    print("no answer")

7-10 词典

输入样例:

5 3
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
atcay
ittenkay
oopslay

输出样例:

cat
eh
loops

代码:

dict1 = {}
n, m = map(int, input().split())
# N行字典条目
for i in range(n):
    d = input().split()
    dict1.update({d[1]: d[0]})
# M行要翻译的外语单词
for i in range(m):
    a = input()
    if a in dict1:
        print(dict1[a])
    else:
        print("eh")

7-10 图的字典表示

输入样例:

在这里给出一组输入。例如:

4
{'a':{'b':10,'c':6}}
{'b':{'c':2,'d':7}}
{'c':{'d':10}}
{'d':{}}

输出样例:

在这里给出相应的输出。例如:

4 5 35

代码:

方法一

n = int(input())
num = 0
sum = 0
for i in range(n):
    dic = eval(input())
    # eval函数在这里就是说明dic接收的是一个字典
    # print(dic)
    for j in dic:
        temp = dic[j]
        for key in temp:
            # 计算边数和边总长度
            num += 1
            sum += temp[key]
print(n, num, sum)

方法二

import ast
a = set()  # 顶点数
s = []  # 边数
sum = 0
n = int(input())
dict1 = {}
for i in range(n):
    d1 = input()
    dict2 = ast.literal_eval(d1)
    for key, value in dict2.items():
        a.add(key)
        if type(value) == dict:
            for key1, value1 in value.items():
                a.add(key1)
                s.append(key1)
                sum += value1
print(len(a), len(s), sum)

7-11 电话聊天狂人

输入样例:

4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832

输出样例:

13588625832 3

代码:

dict1 = {}
a = []
n = int(input())
for i in range(n):
    line = input().split()
    if line[0] not in dict1:
        dict1[line[0]] = 1
    elif line[0] in dict1:
        dict1[line[0]] += 1
    if line[1] not in dict1:
        dict1[line[1]] = 1
    elif line[1] in dict1:
        dict1[line[1]] += 1
        
m = max(dict1.values())
for key, value in dict1.items():
    if value == m:
        a.append(key)
if len(a) == 1:
    print(min(a), m)
else:
    print(min(a), m, len(a))

对比别人写的代码:

n=int(input())
call={}
while n:
    lst=list(map(int,input().split()))
    n-=1
    for i in lst:
        if i not in call:
            call[i]=1
        else:
            call[i]+=1
cnt,frq=1,0
rst=[]
for k in sorted(call.items(),key=lambda call:call[1],reverse=True):
    if frq==0:
        min_num=k[0]        
        frq=k[1]
    if k[1]==frq:
        rst.append(k)
        if min_num>k[0]:
            min_num=k[0]
    else:
        break
if len(rst)==1:
    print(min_num,frq)
else:
    print(min_num,frq,len(rst))
# sample小数据,狂人唯一
# 小数据,多个狂人并列
# 最大n,随机

7-12 求整数序列中出现次数最多的数

输入样例:

10 3 2 -1 5 3 4 3 0 3 2

输出样例:

3 4

代码:

方法一

s = input().split()
num = list(set(s[1:]))
num.sort()
dict1 = {}
for i in num:
    if i not in dict1.keys():
        dict1[i] = s.count(i)
max_key = max(dict1, key=dict1.get)
print("%s %d" % (max_key, dict1[max_key]))

方法二

a = input().split() #在一行中输入多个数
i = int(a[0]) + 1   #确定第一个数字大小即是列表应有的长度
del a[i:]     #删除多余输入的数字
del a[0]      #删除第一个数字
                    #现在a中存储的即为要求序列
ans = 0
count = 0
for i in a:         #从第一个数字开始遍历(第一个循环)
    num = 0
    for j in a:   #从第一个数字开始遍历(第二个循环)
        if j == i:  #如果两个数字相等,那么这个数字的数量加一
            num += 1
    if count < num: #判断数量最多的数字并存储
        count = num
        ans = i
print(ans, end = ' ')
print(count)

7-13 jmu-Java&Python-统计文字中的单词数量并按出现次数排序

输入样例1

failure is probably the fortification in your pole
it is like a peek your wallet as the thief when you
are thinking how to spend several hard-won lepta
          
when you are wondering whether new money it has laid
background because of you then at the heart of the
     
most lax alert and most low awareness and left it
godsend failed
!!!!!

输出样例1

46
the=4
it=3
you=3
and=2
are=2
is=2
most=2
of=2
when=2
your=2

输入样例2

Failure is probably The fortification in your pole!
It is like a peek your wallet as the thief when You
are thinking how to. spend several hard-won lepta.
when yoU are? wondering whether new money it has laid
background Because of: yOu?, then at the heart of the
Tom say: Who is the best? No one dare to say yes.
most lax alert and! most low awareness and* left it
godsend failed
!!!!!

输出样例2

54
the=5
is=3
it=3
you=3
and=2
are=2
most=2
of=2
say=2
to=2

代码:

(这题的try except有点多余,我没改)

import ast
t=""
dict1={}
sum=0
while True:
    try:
        t=input()
        if t=="!!!!!":
            break
        t = str(t).replace('!',' ').replace(".",' ').replace(",",' ').replace(":",' ').replace("*",' ').replace("?",' ')
        t=t.split(" ")
    except:
        pass
    for i in t:
        if i.lower() in dict1 :
            dict1[i.lower()] += 1
        elif i.lower() not in dict1 and i!="":
            dict1[i.lower()] = 1
dict1 = list(dict1.items())
dict1.sort(key=lambda dict1 : dict1[0])
dict1.sort(key=lambda dict1 : dict1[1],reverse=True)
print(len(dict1))
dict1=dict1[0:10]
for key2 ,values2 in dict1:
    print("%s=%s"%(key2,values2))

看看别人写的代码,学习一下更好的方法。

本题需要注意的要点:

需要对字符串的这些 ! . , : * ? 标点符号进行处理,需要用到字符串自带的replace()函数.

在处理字典的键值对的问题的时候,我们往往需要结合元组和列表的相关操作来进行。

使用sorted()函数对元素是元组的列表进行排序的时候,排序的参考变量只会是每个元组中的第一个元素。以及sorted()默认升序排列,要求降序的话,需要加上reverse=True。

zip()函数能灵活按 (键:值) 或者 (值:键) 的循序来整合处理字典,方便分别依照键或依照值为标准来进行排序。

本题最大的难点在于需要进行二次排序:

需要优先进行按值排序后,还要对值相同的切片进行按键排序,其中出现了控制切片排序的方法。

在更新切片序列的时候,别忘记要带上当前的元组所包含的值!

由于切片融入新列表的触发条件是值发生改变,而最后一块值的切片无法在循环中融入新列表,所以需要在循环外额外加入!

1

# 处理多个空格间隔的函数:
def HandleBlock(list):
    new_list = []
    for item in list:
        if item != "":
            new_list.append(item)
    return new_list
removechars = "!.,:*?"
total_list = []
line = ""
while line != "!!!!!":
    line = input()
    if len(line) == 0:
        pass
    elif line != "!!!!!":
        # 去除 "!.,:*?"
        for char in removechars:
            line = line.replace(char, ' ')
        # 去除空格及做列表拆分
        line = line.split(" ")
        line = HandleBlock(line)
        # 统一以小写状态输入
        for item in line:
            total_list.append(item.lower())
    else:
        pass
# 登记出现的个数
# 初始化统计表
statistical_table = {}
for item in total_list:
    statistical_table[item] = 0
# 统计
for item in total_list:
    statistical_table[item] += 1
# 第一层按次数排序
temp_table = list(zip(statistical_table.values(), statistical_table.keys()))
ordered_table = sorted(temp_table, reverse=True)
# 第二层次数相同按键的字母序排序
final_ordered_table = []
cut_list = []
cur_times = ordered_table[0][0]
for item in ordered_table:
    if item[0] == cur_times:
        cut_list.append((item[1], item[0]))
    else:
        ordered_cut_list = sorted(cut_list)
        final_ordered_table += ordered_cut_list
        # 更新当前的值
        cur_times = item[0]
        cut_list = []
        cut_list.append((item[1], item[0]))
ordered_cut_list = sorted(cut_list)
final_ordered_table += ordered_cut_list
# 输出
numb = len(final_ordered_table)
print(numb)
for i in range(10):
    print(f"{final_ordered_table[i][0]}={final_ordered_table[i][1]}")

2

from functools import cmp_to_key
def cmpkey2(x, y):
    if x[1] > y[1]:
        return 1
    elif x[1] < y[1]:
        return -1
    elif x[0] > y[0]:
        return -1
    elif x[0] < y[0]:
        return 1
    return 0
text = ""
while True:
    s = input()
    if s == '!!!!!':
        break
    text += ' '
    text += s
text = text.lower()
for ch in '!.,:*?':
    text = text.replace(ch, ' ')
cnt = {}
for word in text.split():
    cnt[word] = cnt.get(word, 0) + 1
items = list(cnt.items())
items.sort(key=cmp_to_key(cmpkey2), reverse=True)
print(len(items))
for i in range(10):
    if i >= len(items):
        break
    key, val = items[i]
    print("{}={}".format(key, val))

7-14 jmu-Java&Python-统计一段文字中的单词个数并按单词的字母顺序排序后输出

输入样例

Failure is probably the fortification in your pole
It is like a peek your wallet as the thief when you
are thinking how to spend several hard-won lepta
when you Are wondering whether new money it has laid
background Because of you, then at the heart of the
most lax alert and most low awareness and left it
godsend failed
!!!!!

输出样例

49
Are
Because
Failure
It
a
alert
and
are
as
at

代码:

t = ""
dict1 = {}
sum = 0
while True:
    t = input()
    if t == "!!!!!":
        break
    t = t.split(" ")
    for i in t:
        if i in dict1:
            dict1[i] += 1
        elif i not in dict1 and i != "":
            dict1[i] = 1
dict1 = list(dict1.items())
dict1.sort(key=lambda dict1: dict1[0])
print(len(dict1))
dict1 = dict1[0:10]
for key2, values2 in dict1:
    print(key2)

7-15 查单词所在页码

输入样例:

4
cungneh
19
wyd
17
aqkj
2
olckomm
15
4
wyd
aqkj
cungneh
olckomm

输出样例:

17
2
19
15

代码:

方法1

N = int(input())
dict1 = {}
for i in range(N):
    danci = input()
    num = input()
    dict1[danci] = num
M = int(input())
for i in range(M):
    x = input()
    print(dict1[x])

方法2

n=int(input())
p=[]
for i in range(n):
    m=input().split()
    s=input().split()
    m.extend(s)
    p.append(m)
x=int(input())
for j in range(x):
    l=input()
    for k in range(len(p)):
        if p[k][0]==l:
            print(p[k][1])

22秋季Python第8周作业(函数)

函数题

6-1 jmu-python-函数-圆形生成器

函数接口定义:

getCircleArea(r) #r代表整数半径
get_rList(n) #n代表在函数中输入n个值放入列表。

裁判测试程序样例:

/* 请在这里填写答案 */
n = int(input())
rList = get_rList(n)
for e in rList:
    print('{:10.3f}'.format(getCircleArea(e)))
print(type(rList))``

输入样例:

3
1
2
3

输出样例:

3.142
    12.566
    28.274
<class 'list'>

代码:

import math
# 功能:可对指定r计算圆面积。
def getCircleArea(r):
    return math.pi * r * r
# 功能:输入n个值放入列表并将列表return。
def get_rList(n):
    list1 = []
    for i in range(n):
        x = eval(input())
        list1.append(x)
    return list1

6-2 jmu-python-判断质数

函数接口定义:

def isPrime(num)

裁判测试程序样例:

/* 请在这里填写答案 */
num=input()
if isPrime(num):
    print('yes')
else:
    print('no')

输入样例1:

ab

输出样例1:

no

输入样例2:

1.1

输出样例2:

no

输入样例3:

11

输出样例3:

yes

代码:

def isPrime(num):
    try:
        num = int(num)
    except:
        return False
    
    if num <= 1:
        return False
    else:
        for i in range(2, int(pow(num, 0.5)) + 1):
            if num % i == 0:
                return False
                break
        return True

6-3 jmu-python-函数-找钱

函数接口定义:

giveChange(money) #money为要找的钱。经过计算,应按格式"要找的钱 = x*10 + y*5 + z*1"输出。

裁判测试程序样例:

/* 请在这里填写答案 */
n =  int(input())
for i in range(n):
    giveChange(int(input()))

输入样例:

5
109
17
10
3
0

输出样例:

109 = 10*10 + 1*5 + 4*1
17 = 1*10 + 1*5 + 2*1
10 = 1*10 + 0*5 + 0*1
3 = 0*10 + 0*5 + 3*1
0 = 0*10 + 0*5 + 0*1

代码:

def giveChange(money):  # money为要找的钱。经过计算,应按格式"要找的钱 = x*10 + y*5 + z*1"输出。
    x = money // 10
    y = (money - (x * 10)) // 5
    z = money - (x * 10) - (y * 5)
    print('{} = {}*10 + {}*5 + {}*1'.format(money, x, y, z))

6-4 使用函数求素数和

函数接口定义:

prime(p),返回True表示p是素数,返回False表示p不是素数
PrimeSum(m,n),函数返回素数和

裁判测试程序样例:

/* 请在这里填写答案 */
m,n=input().split()
m=int(m)
n=int(n)
print(PrimeSum(m,n))

输入样例:

1 10

输出样例:

17

代码:

def Prime(num):
    try:
        num = int(num)
    except:
        return False
    
    if num <= 1:
        return False
    else:
        for i in range(2, int(pow(num, 0.5)) + 1):
            if num % i == 0:
                return False
                break
        return True
def PrimeSum(m,n):
    sum = 0
    for num in range(m,n+1):
        if Prime(num):
            sum += num;
    return sum

6-5 使用函数统计指定数字的个数

函数接口定义:

在这里描述函数接口。例如:
CountDigit(number,digit ),返回digit出现的次数

裁判测试程序样例:

/* 请在这里填写答案 */
number,digit=input().split()
number=int(number)
digit=int(digit)
count=CountDigit(number,digit )
print("Number of digit 2 in "+str(number)+":",count)

输入样例:

在这里给出一组输入。例如:

-21252 2

输出样例:

在这里给出相应的输出。例如:

Number of digit 2 in -21252: 3

代码:

def CountDigit(number, digit):
    ans = 0
    if number < 0:
        number = abs(number)
    x = 0
    while number > 0:
        x = number % 10
        if digit == x:
            ans += 1
        number = number // 10
    return ans

6-6 使用函数输出指定范围内Fibonacci数的个数

函数接口定义:

在这里描述函数接口。例如:
fib(n),返回fib(n)的值
PrintFN(m,n),用列表返回[m, n]中的所有Fibonacci数。

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:
/* 请在这里填写答案 */
m,n,i=input().split()
n=int(n)
m=int(m)
i=int(i)
b=fib(i)
print("fib({0}) = {1}".format(i,b))
fiblist=PrintFN(m,n)
print(len(fiblist))

输入样例:

在这里给出一组输入。例如:

20 100 6

输出样例:

在这里给出相应的输出。例如:

fib(6) = 13
4

代码:

def fib(n):  # 返回fib(n)的值
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)
def PrintFN(m, n):  # 用列表返回[m, n]中的所有Fibonacci数。
    list1 = []
    for num in range(25):
        if m <= fib(num) <= n:
            list1.append(fib(num))
    return list1

6-7 缩写词

函数接口定义:

acronym(phrase);
phrase是短语参数,返回短语的缩写词

裁判测试程序样例:

/* 请在这里填写答案 */
phrase=input()
print(acronym(phrase))

输入样例:

central  processing  unit

输出样例:

CPU

代码:

def acronym(phrase):
    data = phrase.split()
    # print(data)
    # ['central', 'processing', 'unit']
    ans = ''
    for i in range(len(data)):
        ans += data[i][0].upper()  # upper 小写变大写
    return ans

6-8 jmu-python-发牌

裁判测试程序样例:

import random
/* 请在这里填写答案 */
suit=['♥','♠','♦','♣']
d=['A','2','3','4','5','6','7','8','9','10','J','Q','K']
n=int(input())
random.seed(n)
poker=create()
poker=shufflecard(poker)
for i in range(52):
    print('%-4s'%poker[i],end='  ')
    if i%13==12:
        print()
for i in range(1,5):
    deal(poker,i)

输入样例:

7

输出样例:

♠5    ♣A    ♦6    ♥J    ♣2    ♥Q    ♥A    ♠7    ♠2    ♣Q    ♠4    ♥9    ♦K    
♣6    ♦8    ♣7    ♠Q    ♦4    ♠10   ♥K    ♠9    ♣5    ♦5    ♦3    ♣J    ♣K    
♥8    ♣10   ♠6    ♦10   ♥2    ♦J    ♣4    ♠3    ♣8    ♦A    ♦2    ♥6    ♥3    
♠A    ♦7    ♣9    ♦Q    ♠J    ♥7    ♦9    ♥5    ♥4    ♣3    ♠K    ♥10   ♠8    
第1个玩家拿到的牌是:♠5,♣2,♠2,♦K,♠Q
第2个玩家拿到的牌是:♣A,♥Q,♣Q,♣6,♦4
第3个玩家拿到的牌是:♦6,♥A,♠4,♦8,♠10
第4个玩家拿到的牌是:♥J,♠7,♥9,♣7,♥K

代码:

def create():
    global suit
    global d
    list1 = []
    for su in suit:
        for itd in d:
            list1.append(str(su + itd))
    return list1
def shufflecard(poker):
    random.shuffle(poker)
    return poker
def deal(poker, i):
    print("第{}个玩家拿到的牌是:".format(i), end='')
    temp = i
    for it in range(1, 6):
        if it <= 4:
            print('%s' % poker[temp - 1], end=',')
        else:
            print('%s' % poker[temp - 1], end='\n')
        temp += 4

编程题

7-1 哥德巴赫猜想

输入样例:

24

输出样例:

24 = 5 + 19

代码:

def isPrime(num):
    try:
        num = int(num)
    except:
        return False
    if num <= 1:
        return False
    else:
        for i in range(2, int(pow(num, 0.5)) + 1):
            if num % i == 0:
                return False
                break
        return True
n = int(input())
for i in range(2, n):
    if isPrime(i) and isPrime(n - i):
        break
print("{} = {} + {}".format(n, i, n - i))

7-2 数字金字塔

代码:

print("""    1 
   2 2 
  3 3 3 
 4 4 4 4 
5 5 5 5 5 """)

7-3 jmu-python-凯撒密码加密算法

输入样例:

在这里给出一组输入。例如:

Hello World!
3

输出样例:

在这里给出相应的输出。例如:

Khoor Zruog!

代码:

text = input()
k = int(input())
ans = ''
for i in text:
    if i.isalpha():
        x = ord(i)+k
        if chr(x).isalpha():
            ans += chr(x)
        else:
            ans += chr(x-26)
    else:
        ans += i
print(ans)

7-4 最小公倍数

输入样例:

1 3
15 20

输出样例:

3
60

代码:

import math
while True:
    try:
        a, b = map(int, input().split())
        # print("{:} {:}".format(math.gcd(a, b), int(a * b / math.gcd(a, b))))
        print("{:}".format(int(a * b / math.gcd(a, b))))
    except:
        break

7-5 特立独行的幸福

输入样例 1:

10 40

输出样例 1:

19 8
23 6
28 3
31 4
32 3

注意:样例中,10、13 也都是幸福数,但它们分别依附于其他数字(如 23、31

等等),所以不输出。其它数字虽然其实也依附于其它幸福数,但因为那些数字不在给定区间 [10, 40]

内,所以它们在给定区间内是特立独行的幸福数。

输入样例 2:

110 120

输出样例 2:

SAD

代码:

l,r=input().split()
l,r=int(l),int(r)
list,ans,child=[],[],{} #list存所有的幸福树;ans存独立的幸福树,即不依赖于区间内的其他数字;child存区间内依赖该幸福数(key)的幸福数的个数(value)
for num in range(l,r+1):#枚举区间所有数字
    sum = 0
    tnum = num
    vis={}
    while sum!=1 or vis[sum]<2:
        sum = 0
        for digit in str(tnum):#对一个十进制的各位数字做一次平方和
            sum += int(digit)**2
        vis.setdefault(sum,0)#字典初始化
        vis[sum]+=1 #一次迭代结束 该数字在迭代过程中出现次数+1 
        if(vis[sum]==2):#该数字在迭代过程中出现次数==2 即首次出现死循环 当前枚举的数字num是不幸福数
            break
        tnum = sum
    if(sum==1):#数字num是幸福数 若干次迭代结束时平方和sum==1
        ans.append(num)#存进幸福数数组
        tnum = num
        sum = 0
        child.setdefault(num,0) #计算这个幸福数的独立性 即数依赖于这个数num的幸福数的个数
        while(sum!=1):
            sum = 0
            for digit in str(tnum):
                sum += int(digit) ** 2
            list.append(sum) #对幸福数迭代 迭代过程中出现的数都是幸福数 全部加进list中 但对num进行迭代 幸福数num本身没有进入list,即如果一个幸福数是独立的,在有限区间[l,r]内不依附于其他数字,则不会出现在list中
            tnum = sum
            child[num]+=1 #依赖于幸福数num的幸福数的个数+1 
        #一个幸福数num的child值为num迭代到1的过程中产生的全部sum值的个数 因为迭代到1就结束循环 过程显然是没有产生重复sum值的
import math
def isPrime(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True
for item in ans:
    if item not in list:#出现在list中的幸福数都是其他幸福数迭代过程中产生的
        if isPrime(item):
            child[item]*=2
        print(item,child[item])
if(len(ans)==0):
    print("SAD")

7-6 用函数求两个整数的最大公约数和最小公倍数

输入样例:

24 36
-48 128

输出样例:

12 72
16 -384

提示(公约数、公倍数)

提示:a,b里有负的则最小公倍数就为负的

注意要判断正负

代码:

方法1

import math
import sys
# while True:
#     line = sys.stdin.readline()  # 一次只读一行
for line in sys.stdin:
    line = line.strip()
    x = line.split()
    if line == '\n':
        break
    a = int(x[0])
    b = int(x[1])
    # print("{:} {:}".format(math.gcd(a, b), int(a * b / math.gcd(a, b))))
    if a < 0 or b < 0:
        a = abs(a)
        b = abs(b)
        print("{} {}".format(math.gcd(a, b), -int(a * b / math.gcd(a, b))))
    else:
        print("{} {}".format(math.gcd(a, b), int(a * b / math.gcd(a, b))))

方法2

import sys
def gys(a, b):
    for i in range(min(a, b), 0, -1):
        if a % i == 0 and b % i == 0:
            return i
def gbs(a, b):
    for i in range(min(a, b), 0, -1):
        if a % i == 0 and b % i == 0:
            return a * b // i
for i in sys.stdin:
    a, b = list(map(int, i.split()))
    if a < 0 or b < 0:
        a = abs(a)
        b = abs(b)
        print("{} {}".format(gys(a, b), -gbs(a, b)))
    else:
        print("{} {}".format(gys(a, b), gbs(a, b)))

22秋季Python第9周作业

函数题

6-1 完数统计

完数定义:一个数的所有因子(包括1)之和等于它自身,这个数就是完数。比如6=1+2+3,6是完数。

本题要求编写程序,计算所有N位完数的个数与列表显示。

函数接口定义:

def wan(n):

在这里解释接口参数。n是一个大于0的正整数。表示几位数。

裁判测试程序样例:

import math
/* 请在这里填写答案 */
n=int(input())
x,lst=wan(n)
print(x)
print(lst)

输入样例:

在这里给出一组输入。例如:

2

输出样例:

在这里给出相应的输出。例如:

1
[28]

代码:

def wan(n):
    arr = []
    count = 0
    for x in range(int(math.pow(10, n - 1)), int(math.pow(10, n))):
        sum = 1
        for i in range(2, x):
            if x % i == 0:
                sum += i
        if sum == x:
            arr.append(sum)
            count += 1
    return count, arr

6-2 偶数是两个素数的和

编写函数,接收一个正偶数为参数,输出两个素数,并且这两个素数之和等于原来的正偶数。如果存在多组符合条件的素数,则全部输出。

函数接口定义:

在这里描述函数接口。例如:

def  evenprimesum( n ):

在这里解释接口参数。n 为传递的整数,不一它是偶数,也不一定是大于0的数据。函数将所有是偶数的素数输出,输出格式为:素数 + 素数 = 偶数,数据之间分隔符为一个空格

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:

/* 请在这里填写答案 */
n = int(input())
evenprimesum(n)

输入样例:

在这里给出一组输入。例如:

100

输出样例:

在这里给出相应的输出。例如:

3 + 97 = 100
11 + 89 = 100
17 + 83 = 100
29 + 71 = 100
41 + 59 = 100
47 + 53 = 100

代码:

def Prime(n):
    flag = True
    for i in range(2, n):
        if n % i == 0:
            flag = False
            break
    return flag
def evenprimesum(n):
    if n % 2 == 0 and n > 0:
        for i in range(3, n // 2 + 1):
            if Prime(i) and Prime(n - i):
                print(i, '+', n - i, '=', n)

6-3 浮点数的十进制转二进制

函数接口定义:

def dec2bin(dec_num):

其中 dec_num 是用户传入的十进制浮点数,返回对应的二进制浮点数字符串。

裁判测试程序样例:

/* 你的代码将被嵌在这里 */
if __name__ == '__main__':
    dec_num = eval(input())
    bin_num = dec2bin(dec_num)
    print(bin_num)

输入样例:

在这里给出一组输入。例如:

0.1

输出样例:

在这里给出相应的输出。例如:

0b0.0001100110011001100110011001100110011001100110011001101

代码:

def dec2bin(dec_num):
    res = ""
    integer = int(dec_num)
    res += bin(integer)
    if integer == dec_num:
        return res
    decimal = dec_num - integer
    res += "."
    while(True):
        if decimal == 0:
            break
        else:
            x = decimal * 2
            res += str(int(x))
            decimal = x - int(x)
    return res

6-4 实现象棋中相的走法

函数接口定义:

def moves_elephant(pos):

pos是一个二元元组,为红相或黑象的位置

裁判测试程序样例:

# 返回棋子元组,比如("黑","炮");如为空返回(0,"空")
def getPiece(pos):
    return board[pos] # 返回元组
# 返回棋子的颜色
def getColor(piece):
    return piece[0]
def moves_empty_board_elephant(pos):
    return [(pos[0] - 2, pos[1] - 2), (pos[0] - 2, pos[1] + 2), (pos[0] + 2, pos[1] - 2), (pos[0] + 2, pos[1] + 2)]
# 返回象的合法位置列表
def moves_elephant(pos):
    # 请添加你的函数代码
def main():
    global board
    board =  {(0,0):(0,"空"), (0,1):(0,"空"), (0,2):(0,"空"), (0,3):(0,"空"), (0,4):("红","卒"), (0,5):(0,"空"), (0,6):(0,"空"), (0,7):(0,"空"), (0,8):(0,"空"), (0,9):("红","炮"),
    (1,0):(0,"空"), (1,1):(0,"空"), (1,2):(0,"空"), (1,3):(0,"空"), (1,4):(0,"空"), (1,5):(0,"空"), (1,6):(0,"空"), (1,7):(0,"空"), (1,8):("红","马"), (1,9):("红","马"),
    (2,0):(0,"空"), (2,1):(0,"空"), (2,2):(0,"空"), (2,3):(0,"空"), (2,4):(0,"空"), (2,5):(0,"空"), (2,6):(0,"空"), (2,7):(0,"空"), (2,8):(0,"空"), (2,9):(0,"空"),
    (3,0):(0,"空"), (3,1):(0,"空"), (3,2):(0,"空"), (3,3):(0,"空"), (3,4):(0,"空"), (3,5):(0,"空"), (3,6):(0,"空"), (3,7):("黑","士"), (3,8):(0,"空"), (3,9):("黑","炮"),
    (4,0):("红","将"), (4,1):("红","士"), (4,2):("红","象"), (4,3):(0,"空"), (4,4):(0,"空"), (4,5):("黑","车"), (4,6):(0,"空"), (4,7):("黑","象"), (4,8):("黑","士"), (4,9):("黑","将"),
    (5,0):("红","士"), (5,1):(0,"空"), (5,2):(0,"空"), (5,3):(0,"空"), (5,4):(0,"空"), (5,5):(0,"空"), (5,6):(0,"空"), (5,7):(0,"空"), (5,8):(0,"空"), (5,9):(0,"空"),
    (6,0):("红","象"), (6,1):(0,"空"), (6,2):(0,"空"), (6,3):(0,"空"), (6,4):("红","卒"), (6,5):(0,"空"), (6,6):(0,"空"), (6,7):(0,"空"), (6,8):(0,"空"), (6,9):("黑","象"), 
    (7,0):(0,"空"), (7,1):(0,"空"), (7,2):(0,"空"), (7,3):(0,"空"), (7,4):(0,"空"), (7,5):(0,"空"), (7,6):(0,"空"), (7,7):(0,"空"), (7,8):(0,"空"), (7,9):(0,"空"),
    (8,0):(0,"空"), (8,1):(0,"空"), (8,2):(0,"空"), (8,3):(0,"空"), (8,4):("红","卒"), (8,5):(0,"空"), (8,6):(0,"空"), (8,7):(0,"空"), (8,8):(0,"空"), (8,9):(0,"空"),
    }
    print(*moves_elephant((4,2)))
if __name__ == '__main__':
    main()

输入样例:

无输入

输出样例:

(2, 0) (2, 4)

代码:

# 返回象的合法位置列表
def moves_elephant(pos):
    # 请添加你的函数代码
    # print(getColor(pos))
    # print(pos[0], pos[1])
    # print(getPiece((pos[0] - 2, pos[1] - 2)))
    lis = []
    result = getPiece((pos[0] - 2, pos[1] - 2))
    # print(result[0])
    # print(result[1])
    if result[1] == "空":
        lis.append((pos[0] - 2, pos[1] - 2))
    result = getPiece((pos[0] - 2, pos[1] + 2))
    if result[1] == "空":
        lis.append((pos[0] - 2, pos[1] + 2))
    result = getPiece((pos[0] + 2, pos[1] - 2))
    if result[1] == "空":
        lis.append((pos[0] + 2, pos[1] - 2))
    result = getPiece((pos[0] + 2, pos[1] + 2))
    if result[1] == "空":
        lis.append((pos[0] + 2, pos[1] + 2))
    return lis

6-5 富翁与骗子 - 实验12 用函数实现模块化程序设计 - 《Python编程基础及应用实验教程》,高教社

在一次酒会上,富翁A遇到了骗子B。骗子对富翁说:“我成立了一个互助基金会,您可以将短期不用的资金存到我这里来,存期30天。第一天您只需要存入1分钱,第二天存入两分钱,依次类推,以后每天存入的钱是前一天的两倍,直到30天期满(含30天)。从您存入钱的第一天开始,您每天可以支取30万元,一直到30天期满(含30天)。”富翁觉得有利可图,欣然同意,两人签订了协议,约定按照上述要求存入资金,并且每天按照最大额度提取资金,合约结束后两人就互不相欠。

请完善下述程序,从键盘读入合约天数以及单日取款金额,计算并输出富翁的盈亏金额。

函数接口定义:

def deposit(n)
def withdraw(n,amount)
  • 函数deposit(n)用于求n天的存钱总额;
  • 函数withdraw(n,amount)用于求n天的提款总额,其中,参数amount为每日提款额。

注意:仅需提交两个函数的定义代码,不要提交完整程序。

裁判测试程序样例:

#请将两个函数定义在此处
days,amount=eval(input())
diff=deposit(days)-withdraw(days,amount)
if diff>0:
    print("富翁亏损: {:.2f}".format(diff))
else:
    print("富翁赢利: {:.2f}".format(0-diff))

输入样例:

在这里给出一组输入。例如:

30,300000

输出样例:

在这里给出相应的输出。例如:

富翁亏损: 1737418.23

代码:

def deposit(n):
    x = 0.01
    count = 0.0
    for i in range(0, n):
        count += x
        x = x * 2
    return count
def withdraw(n, amount):
    return n * amount

编程题

7-1 互质数

输入样例:

1
3
3 11
5 11
10 12

输出样例:

2

代码:

import math
t = int(input())
while t > 0:
    count = 0
    n = int(input())
    for i in range(0, n):
        a, b = map(int, input().split())
        if math.gcd(a, b) == 1:
            count += 1
    print(count)
    t -= 1

7-2 三七二十一

输入样例:

2
1 7
1 100

输出样例:

none
8 29 50 71 92

代码:

t = int(input())
while t > 0:
    a, b = map(int, input().split())
    yes = 0
    for n in range(a, b + 1):
        if n % 3 == 2 and n % 7 == 1 and yes == 0:
            yes = 1
            print(n, end="")
        elif n % 3 == 2 and n % 7 == 1 and yes != 0:
            print(" {}".format(n), end="")
    if yes == 0:
        print("none")
    else:
        print()
    t -= 1

7-3 学生成绩分析

输入样例:

66 78 95 63 85 94 99

输出样例:

[(85, 2.1), (78, 4.9), (94, 11.1), (95, 12.1), (99, 16.1), (66, 16.9), (63, 19.9)]

代码:

grades = list(map(str, input().split()))
num = []
for x in grades:
    num.append(eval(x))
avg = sum(num) / len(num)
lis = []
for i in range(len(num)):
    lis.append((num[i], round(abs(avg - num[i]), 1)))
print(sorted(lis, key=lambda n: n[1]))

7-4 多个数的最小公倍数

输入样例:

4
3 5 7 15
5 1 2 4 3 5
8 7 15 12 3 4 6 4 9
2 45000 50000

输出样例:

105
60
1260
450000

代码:

import math
# math.lcm(a, b)
t = int(input())
for i in range(0, t):
    grades = list(map(int, input().split()))
    # grades = sorted(grade, reverse=True)
    # print(grades)
    x = grades[1]
    for j in range(2, len(grades)):
        x = math.lcm(x, grades[j])
    print(x)

【python】习题 6-10周(下)https://developer.aliyun.com/article/1507475?spm=a2c6h.13148508.setting.20.1b484f0eD2AqhJ

目录
相关文章
|
27天前
|
物联网 Python
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
|
1月前
|
存储 Python
【python】习题第10周题解
【python】习题第10周题解
23 1
|
1月前
|
Python
【python】习题 第10周
【python】习题 第10周
24 0
|
1月前
|
Python
【python】习题第9周
【python】习题第9周
27 0
|
1月前
|
数据安全/隐私保护 Python
【python】习题第8周
【python】习题第8周
22 0
|
1月前
|
Python
【python】习题第7周(下)
【python】习题第7周(下)
18 0
|
1月前
|
自然语言处理 Python
【python】习题第7周(上)
【python】习题第7周(上)
42 1
|
1月前
|
Python
【python】习题 6-10周(下)
【python】习题 6-10周(下)
24 0
|
1月前
|
Python
【python】习题 6-10周(上)
【python】习题 6-10周(上)
17 0
|
1天前
|
Shell Python
GitHub星标破千Star!Python游戏编程的初学者指南
Python 是一种高级程序设计语言,因其简洁、易读及可扩展性日渐成为程序设计领域备受推崇的语言。 目前的编程书籍大多分为两种类型。第一种,与其说是教编程的书,倒不如说是在教“游戏制作软件”,或教授使用一种呆板的语言,使得编程“简单”到不再是编程。而第二种,它们就像是教数学课一样教编程:所有的原理和概念都以小的应用程序的方式呈现给读者。