牛客-中等及基础难度python

5进制转换

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
# coding = utf-8
 
 
def main(nums):
    # 16进制对照字典
    num_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
    n = len(nums)
    res = 0
    for i in range(2, n):
        res += num_dict[nums[i]] * (16 ** (n-i-1))
    return res
                                      
 
if __name__ == '__main__':
    while True:
        try:
            nums = input()
            print(main(nums))
        except:
            break

6质数因子

功能:输入一个正整数,按照从小到大的顺序输出它的所有质因子(重复的也要列举)(如180的质因子为2 2 3 3 5 )最后一个数后面也要有空格
# coding = utf-8
 
def main(nums):
    i = 2
    # 采用递归思想,从最小质数i=2开始不断进行整除,并更新nums的值
    while nums >=i and i * i <= nums:
        while nums % i == 0:
            nums = nums // i
            print(i, end= ' ')
        i += 1
    # 最后一个质数因子,若不是1,则输出
    if (nums - 1) != 0:
        print(nums, end = ' ')
     
 
if __name__ == '__main__':
    nums = int(input())
    main(nums)

8合并表记录

数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
# coding = utf-8
 
 
def main(index_value, kv_dict):
    k, v = int(index_value.split(' ')[0]), int(index_value.split(' ')[-1])
    if k in kv_dict:
        kv_dict[k] += v
    else:
        kv_dict[k] = v
    kv_dict = dict(sorted(kv_dict.items(),key = lambda x:x[0]))
    return kv_dict
 
 
if __name__ == '__main__':
    n = int(input())
    kv_dict = {}
    for i in range(n):
        index_value = input()
        kv_dict = main(index_value, kv_dict)
    for k, v in kv_dict.items():
        print(k, v)

9提取不重复的整数

输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。保证输入的整数最后一位不是0。
# coding = utf-8
 
 
def main(nums):
    temp = [i for i in str(nums)][::-1]
    res = []
    for i in temp:
        if i not in res:
            res.append(i)
    if res[0] == '0':
        return int(''.join(res[1:]))
    else:
        return int(''.join(res))
     
if __name__ == '__main__':
    nums = input()
    print(main(nums))

10字符个数统计

编写一个函数,计算字符串中含有的不同字符的个数。字符在ASCII码范围内(0~127,包括0和127),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次例如,对于字符串abaca而言,有a、b、c三种不同的字符,因此输出3。
# coding = utf-8
 
def main(input_string):
    string_list = list(input_string)
    return len(list(set(string_list)))
 
 
if __name__ == '__main__':
    input_string = input()
    print(main(input_string))

14-字符串排序

给定n个字符串,请对n个字符串按照字典序排列。
# coding = utf-8
 
 
def main(n):
    if n <1 or n >1000:
        return '输入有误'
     
    input_string_list = []
    for i in range(n):
        ch = input()
        if len(ch) >100:
            return '输入单词有误'
        input_string_list.append(ch)
    input_string_list.sort()
    for i in input_string_list:
        print(i)
     
 
if __name__ == '__main__':
    n = int(input())
    main(n)

16 购物单

王强今天很开心,公司发给N元的年终奖。王强决定把年终奖用于购物,他把想买的物品分为两类
n, m = map(int,input().split())
primary, annex = {}, {}
for i in range(1,m+1):
    x, y, z = map(int, input().split())
    if z==0:#主件
        primary[i] = [x, y]
    else:#附件
        if z in annex:#第二个附件
            annex[z].append([x, y])
        else:#第一个附件
            annex[z] = [[x,y]]
m = len(primary)#主件个数转化为物品个数
dp = [[0]*(n+1) for _ in range(m+1)]
w, v= [[]], [[]]
for key in primary:
    w_temp, v_temp = [], []
    w_temp.append(primary[key][0])#1、主件
    v_temp.append(primary[key][0]*primary[key][1])
    if key in annex:#存在主件
        w_temp.append(w_temp[0]+annex[key][0][0])#2、主件+附件1
        v_temp.append(v_temp[0]+annex[key][0][0]*annex[key][0][1])
        if len(annex[key])>1:#存在两主件
            w_temp.append(w_temp[0]+annex[key][1][0])#3、主件+附件2
            v_temp.append(v_temp[0]+annex[key][1][0]*annex[key][1][1])
            w_temp.append(w_temp[0]+annex[key][0][0]+annex[key][1][0])#3、主件+附件1+附件2
            v_temp.append(v_temp[0]+annex[key][0][0]*annex[key][0][1]+annex[key][1][0]*annex[key][1][1])
    w.append(w_temp)
    v.append(v_temp)
for i in range(1,m+1):
    for j in range(10,n+1,10):#物品的价格是10的整数倍
        max_i = dp[i-1][j]
        for k in range(len(w[i])):
            if j-w[i][k]>=0:
                max_i = max(max_i, dp[i-1][j-w[i][k]]+v[i][k])
        dp[i][j] = max_i
print(dp[m][n])

21简单密码

他是这么变换的,大家都知道手机上的字母: 1–1, abc–2, def–3, ghi–4, jkl–5, mno–6, pqrs–7, tuv–8 wxyz–9, 0–0,就这么简单,渊子把密码中出现的小写字母都变成对应的数字,数字和其他的符号都不做变换,
# coding = utf-8
import string
 
 
def main(input_string):
    target_dict = {'1':1, 'abc':2, 'def':3, 'ghi':4, 'jkl':5, 'mno':6, 'pqrs':7, 'tuv':8, 'wxyz':9, '0':0}
    res = ''
    all_letters = string.ascii_letters
    for i in input_string:
        # 判断是否为字母
        if i.isalpha():
            # 大写转换为后移一位小写
            if i.isupper():
                # Z的话需要直接替换为a,其他进行移位并变为小写
                if i == 'Z':
                    i = 'a'
                else:
                    i = all_letters[all_letters.index(i.lower()) + 1]
                res += i
            # 小写转换为数字
            else:
                for k in target_dict.keys():
                    if i in k:
                        res += str(target_dict[k])
        # 非字母直接拼接
        else:
            res += i
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

26字符串排序

规则 1 :英文字母从 A 到 Z 排列,不区分大小写。如,输入: Type 输出: epTy
# coding = utf-8
 
 
def alpha_sort(input_string):
    res = [0] * len(input_string)
    temp = []
    for idx,ch_ in enumerate(input_string):
        if ch_.isalpha():
            temp.append(ch_)
        else:
            res[idx] = ch_
    # 将字母进行排序
    temp.sort(key = lambda x: x.upper())
    # 将字母放入res对应位置
    for idx, ch_ in enumerate(res):
        # 如果是字符,则放入res对应位置
        if not ch_:
            res[idx] = temp[0]
            # 同时,删除temp的头元素
            temp.pop(0)
    return ''.join(res)
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(alpha_sort(input_string))
             
        except:
            break

34 图片整理

Lily上课时使用字母数字图片教小朋友们学习英语单词,每次都需要把这些图片按照大小(ASCII码值从小到大)排列收好。请大家给Lily帮忙,通过C语言解决。
def sort_pic():
    pic = input()
    pic_list = sorted(pic)
    if len(pic_list)>1024:
        return '字符串长度错误'
    return ''.join(pic_list)
 
 
if __name__ == '__main__':
    while True:
        try:
            print(sort_pic())
        except:
            break

35蛇形矩阵

蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。
# coding = utf-8
 
 
def snake_matrix(n):
    res = []
    for i in range(n):
            # 生成第一行元素
        if i == 0:
            res.append([(j+1)*(j+2)//2 for j in range(n)])
#             print(res)
        else:
            # 第二行为第一行的第二个元素开始-1
            res.append([(j-1) for j in res[i-1][1:]])
    return res
     
     
 
if __name__ =='__main__':
    while True:
        try:
            n = int(input())
            res = snake_matrix(n)
            for i in res:
                line_ = ' '.join([str(j) for j in i])
                print(line_)
        except:
            break

36字符串加密

有一种技巧可以对数据进行加密,它使用一个单词作为它的密匙。下面是它的工作原理:首先,选择一个单词作为密匙,如TRAILBLAZERS。如果单词中包含有重复的字母,只保留第1个,其余几个丢弃。
# coding = utf-8
import string
 
def main(input_string, pw_string):
    # 获取所有大写字母
    all_upper_letters = string.ascii_uppercase
    # 对输入字符串进行去重
    tmp = ''
    for i in input_string:
        if i not in tmp:
            tmp += i
    # 对去重后的字符进行拼接大写字母
    pw = tmp.upper()
    for i in all_upper_letters:
        if i not in pw:
            pw += i
    # 对pw_string 进行相应加密
    res = ''
    for i in pw_string:
        if i.isupper():
            res += pw[all_upper_letters.index(i)]
        elif i.islower():
            res += pw[all_upper_letters.index(i.upper())].lower()
        else:
            res += i
    return res
     

if __name__ =='__main__':
    while True:
        try:
            input_string = input()
            pw_string = input()
            print(main(input_string, pw_string))
        except:
            break

38 求小球落地5次后所经历的路程和第5次反弹的高度

假设一个球从任意高度自由落下,每次落地后反跳回原高度的一半; 再落下, 求它在第5次落地时,共经历多少米?第5次反弹多高?最后的误差判断是小数点6位
# coding = utf-8
 
 
def main(height):
    height_list = [i for i in range(5)]
    height_list[0] = height
    for i in range(1,5):
        height_list[i] = height / 2
        height = height_list[i]
    total_height = height_list[0] + 2*sum(height_list[1:])
    final_height = height_list[-1] / 2
    print(total_height)
    print(final_height)
 
 
if __name__ == '__main__':
    while True:
        try:
            height = int(input())
            main(height)
        except:
            break

40 统计字符

输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。本题包含多组输入。
# coding = utf-8
import re
 
def main(input_string):
    string_res = len(re.findall(r'[a-zA-Z]', input_string))
    num_res = len(re.findall(r'[0-9]', input_string))
    blank_res = input_string.count(' ')
    others = len(input_string) - string_res - num_res - blank_res
    print(string_res)
    print(blank_res)
    print(num_res)
    print(others)
      
     
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            main(input_string)
        except:
            break

43迷宫问题

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一格是可以走的路。
# coding = utf-8
  
def min_path(maze, n, m, start_x, start_y, path):
    # 判断是否越界
    if start_x<0 or start_y<0 or start_x > n-1 or start_y > m-1:
        return
    # 判断是否非墙壁或已走过的点
    if maze[start_x][start_y] != 0:
        return
    if start_x == n-1 and start_y == m-1 and maze[start_x][start_y] == 0:
        # 将最后一个点加入路径
        path.append((start_x, start_y))
        # 将路径以要求格式输出输出
        for i in path:
            print('(%d,%d)'%(i[0],i[-1]))
        return
    # 满足要求的点标记为2,并添加到路径中
    maze[start_x][start_y] = 2
    path.append((start_x, start_y))
    # 递归寻找下一个点
    # 移动方式为上下左右
    min_path(maze, n, m, start_x, start_y + 1, path)
    min_path(maze, n, m, start_x, start_y - 1, path)
    min_path(maze, n, m, start_x + 1, start_y, path)
    min_path(maze, n, m, start_x - 1, start_y, path)
    # 一条路尝试不通的时候回溯
    path.pop()
 
 
if __name__ == '__main__':
    while True:
        try:
            n_m = input().split()
            n = int(n_m[0])
            m = int(n_m[-1])
            maze = []
            for i in range(n):
                maze.append(list(map(int, input().split())))
             
            min_path(maze, n, m, 0, 0, [])
        except:
            break

45名字的漂亮度

给出一个名字,该名字有26个字符组成,定义这个字符串的“漂亮度”是其所有字母“漂亮度”的总和。每个字母都有一个“漂亮度”,范围在1到26之间。没有任何两个不同字母拥有相同的“漂亮度”。字母忽略大小写。给出多个名字,计算每个名字最大可能的“漂亮度”。
# coding = utf-8
import string
 
 
def pretty(name_list):
    # 最大即出现频率最高的漂亮度最大,统计该名字中各字符出现次数
    count = []
    for name in name_list:
        # tmp 统计单词中不重复字符出现的频数
        tmp = list(set(name))
        count.append([name.count(i) for i in tmp])
    # 对出现频率排序并进行计算
    score = []
    for i in count:
        res = 0
        # 进行升序排列
        i.sort(reverse = True)
        # 计算漂亮度
        for j in range(len(i)):
            res += i[j] * (26 - j)
        score.append(res)
    return score
 
 
if __name__ == '__main__':
    while True:
        try:
            N = int(input())
            name_list = [input() for i in range(N)]
            score = pretty(name_list)
            for i in score:
                print(i)
        except:
            break

46截取字符串

输入一个字符串和一个整数k,截取字符串的前k个字符并输出
# coding = utf-8
 
 
def split_string(input_string, K):
    return input_string[:K]

 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            K = int(input())
            print(split_string(input_string, K))
        except:
            break

48从单向链表中删除指定值的节点

# coding = utf-8
 
def remove_list(nums, head, l, rm):
    res = [head]
    for i in range(0, len(l), 2):
        a = l[i]
        b = l[i+1]
        res.insert(res.index(b)+1, a)
    res.remove(rm)
    return ' '.join(res)+' '
 
 
 
if __name__ == '__main__':
    while True:
        try:
            input_ = input().split()
            nums = input_[0]
            head = input_[1]
            rm = input_[-1]
            l = input_[2:-1]
            print(remove_list(nums, head, l, rm))
        except:
            break

49多线程

# conding = utf-8
import threading
import sys
import time
 
 
def showA(N):
    for i in range(N):
        lockd.acquire()  # 获取对方的锁,释放自己的锁
        print('A', end='')
        sys.stdout.flush()  # 释放缓冲区
        locka.release()
 
 
 
def showB(N):
    for i in range(N):
        locka.acquire()
        print('B', end='')
        sys.stdout.flush()
        lockb.release()
 
 
 
def showC(N):
    for i in range(N):
        lockb.acquire()
        print('C', end='')
        sys.stdout.flush()
        lockc.release()
 
 
 
def showD(N):
    for i in range(N):
        lockc.acquire()
        print('D', end='')
        sys.stdout.flush()
        lockd.release()
 
 
 
 
 
 
if __name__ == '__main__':
    while True:
        try:
            N = int(input())
            locka = threading.Lock()  # 定义4个互斥锁
            lockb = threading.Lock()
            lockc = threading.Lock()
            lockd = threading.Lock()
 
            t1 = threading.Thread(target=showA, args=(N,))  # 定义4个线程
            t2 = threading.Thread(target=showB, args=(N,))
            t3 = threading.Thread(target=showC, args=(N,))
            t4 = threading.Thread(target=showD, args=(N,))
 
            locka.acquire()
            lockb.acquire()
            lockc.acquire()
 
            t1.start()
            t2.start()
            t3.start()
            t4.start()
        except:
            break

52计算字符串的距离

给定任意两个字符串,写出一个算法计算它们的编辑距离。
# coding = utf-8
 
 
def minDistance(word1, word2):
        #  topens 用于堆放(word1*, word2*..)
        # visited 用于存放已见过的(word1*, word2*..)词语对
        # 用删除的方式,把已经匹配好的word1*, word2*字母删去,
        # 三种基本操作
        # word1*删去头字母
        # word2*删去头字母
        # 两词同时删去头字母
        w1, w2, opened = word1, word2, set()
        topens = [(w1, w2, 0)]
        while True:
            (w1, w2, value) = topens.pop(0)
            if (w1, w2) in opened:
                continue
            if w1 == w2:
                return value
            opened.add((w1, w2))
            while w1 and w2 and w1[0] == w2[0]:
                w1, w2 = w1[1:], w2[1:]
            value += 1
            topens += [(w1[1:], w2, value),
                        (w1, w2[1:], value),
                        (w1[1:], w2[1:], value)
            ]
        return -1
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string1 = input()
            input_string2 = input()
            print(minDistance(input_string1, input_string2))
        except:
            break

55挑7

输出7有关数字的个数,包括7的倍数,还有包含7的数字
# coding = utf-8
 
def main(num):
    # 包含7的数
    contains = []
    # 7的倍数
    sevens = []
    for i in range(1,num+1):
        if i % 7 ==0:
            sevens.append(i)
        if '7' in str(i):
            contains.append(i)
    res = contains + sevens
    # 对结果去重
    res = list(set(res))
#     print(res)
    return len(res)
 

 
if __name__ == '__main__':
    while True:
        try:
            num = int(input())
            print(main(num))
        except:
            break

57高精度整数加法

输入两个用字符串表示的整数,求它们所表示的数之和。
# encoding = utf-8
def main(input_string1, input_string2):
    return str(int(input_string1) + int(input_string2))
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string1 = input()
            input_string2 = input()
            print(main(input_string1, input_string2))
        except:
            break

59找出字符串中第一个只出现一次的字符

# coding = utf-8
 
def main(input_string):
    # 统计每个字符的词频
    count = {}
    for i in input_string:
        count[i] = input_string.count(i)
    # 进行对比
    for i in input_string:
        if count[i] == 1:
            return i
    return -1
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            res = main(input_string)
            print(res)
        except:
            break

60查找组成一个偶数最接近的两个素数

任意一个偶数(大于2)都可以由2个素数组成,组成偶数的2个素数有很多种情况,本题目要求输出组成指定偶数的两个素数差值最小的素数对。本题含有多组样例输入。
# coding = utf-8
 
def main(nums):
    all_nums = {}
    for i in range(1, nums + 1):
        # 素数 仅有1和本身能整除法
        # 求所有数的公因数,长度为2的就是素数
        tmp = []
        for j in range(1, i+1):
            if i%j == 0:
                tmp.append(j)
        if len(tmp) == 2:
            all_nums[i] = tmp
    # 找出两者之和等于nums的数
    res = []
    for i in range(1, nums + 1):
        if (nums - i) in all_nums.keys() and i in all_nums.keys():
            value = max(i, nums-i) - min(i, nums-i)
            res.append([i, nums-i, value])
    # 按差值排序
    res = sorted(res, key = lambda x:x[-1])
    return res
     
             
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            res = main(nums)
            print(res[0][0])
            print(res[0][1])
        except:
            break

63 DNA序列

一个DNA序列由A/C/G/T四个字母的排列组合组成。
# coding = utf-8
 
def count(sub_string):
    res = sub_string.count('C') + sub_string.count('G')
    return res / len(sub_string)
     
     
def main(input_string, N):
    split_list = []
    for i in range(len(input_string)):
        split_list.append(input_string[i:i+N])
    # 计算子串的ratio
    ratio = {}
    for i in split_list:
        if len(i) == N:
            ratio[i] = count(i)
    # 对ratio 排序
    ratio = sorted(ratio.items(), key = lambda x:x[-1], reverse = True)
    res = []
    for i in ratio:
        if i[-1] == ratio[0][-1]:
            res.append(i)
    # 判断res中是否存在多个值,存在则根据出现先后顺序排列
    if len(res) >1:
        res = sorted(res, key = lambda x:input_string.index(x[0]))
    return res[0][0]
             
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            N = int(input())
            res = main(input_string, N)
            print(res)
        except:
            break

64MP3光标位置

# coding = utf-8
 
def main(nums, commands):
    # 生成所有歌曲
    songs = [i for i in range(1, nums+1)]
    start = 0  # 每页的起始位置
    cur = 0  # 当前鼠标位置
      
    for i in commands:
        # 起始位置为第一首歌
        if i == 'U':
            if cur == 0:
                cur = nums-1
            else:
                cur -= 1
                  
        if i == 'D':
            if cur == nums -1 :
                cur = 0
            else:
                cur += 1
    if commands[-1] == 'U':
        if songs[cur] in songs[-4:]:
            start = nums - 4
        elif songs[cur] in songs[:4]:
            start = 0
        else:
            start = cur
    if commands[-1] == 'D':
        if songs[cur] in songs[:4]:
            start = 0
        elif songs[cur] in songs[-4:]:
            start = nums - 4
        else:
            start = cur - 3
    print(*songs[start:start+4])
    print(songs[cur])
  
 
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            commands = input()
            main(nums, commands)
        except:
            break

65查找两个字符串a,b中的最长公共子串

查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
# coding = utf-8
 
 
def main(input_string1, input_string2):
 
    # 找到两者中较短的字符串,使得较短为input_string1
    if len(input_string2) < len(input_string1):
        input_string1, input_string2 = input_string2, input_string1
    n = len(input_string1)
    m = len(input_string2)
    sub_string_list = []
    for i in range(n):
        for j in range(i + 1, m):
            sub_string = input_string1[i:j]
            if sub_string in input_string2 and len(sub_string)>1:
                sub_string_list.append(sub_string)
    # 对子串进行去重和根据长度排序
    sub_string_list = sorted(list(set(sub_string_list)), key = lambda x : len(x), reverse = True)
    # 找出和最长子串长度相同的子串
    res = [i for i in sub_string_list if len(i) == len(sub_string_list[0])]
    # 出现多个相同长度的符合要求子串,根据要求,返回在最短字符串中最先出现的子串
    if len(res)>1:
        res.sort(key = lambda x : input_string1.index(x))
    return res[0]
                 
     
if __name__ == '__main__':
    while True:
        try:
            input_string1 = input()
            input_string2 = input()
            res = main(input_string1, input_string2)
            print(res)
        except:
            break

67 24点游戏算法

问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
# coding = utf-8
 
def TweentyFour(num_list, item):
    if item <1:
        return False
    if len(num_list) == 1:
        return num_list[0] == item
    for i in range(len(num_list)):
        a = num_list[:i] + num_list[i+1:]
        b = num_list[i]
        if TweentyFour(a, item - b) or TweentyFour(a, item + b) or TweentyFour(a, item * b) or TweentyFour(a, item / b):
            return True
    return False
     
 
if __name__ == '__main__':
    while True:
        try:
            num_list = [int(i) for i in input().split()]
            res = TweentyFour(num_list, 24)
            if res:
                print('true')
            else:
                print('false')
        except:
            break

69矩阵乘法

# coding = utf-8
 
 
def matrix(x, y, z, A, B):
    C = []
    for i in range(x):
        tmp = []
        for j in range(z):
            res = 0
            for k in range(y):
                res += A[i][k] * B[k][j]
            tmp.append(res)
        C.append(tmp)
    return C
 
 
if __name__ == '__main__':
    while True:
        try:
            x = int(input())
            y = int(input())
            z = int(input())
            A = [list(map(int, input().split())) for i in range(x)]
            B = [list(map(int, input().split())) for i in range(y)]
            C = matrix(x, y, z, A, B)
            for i in C:
                print(' '.join([str(j) for j in i]))
        except:
            break

70矩阵乘法计算量估算

矩阵乘法的运算量与矩阵乘法的顺序强相关。
while True:
    try:
        n,dic,stk,num = int(input()),{},[],0
        for i in range(n):
            # chr(ord('A') ->A
            key = chr(ord('A')+i)
            dic[key] = list(map(int,input().strip().split()))
        x = input()
        for i in range(len(x)):
            if x[i] != ')':
                stk.append(x[i])
            else:
                C,B = stk.pop(),stk.pop()
                stk.pop()
                num += dic[B][0]*dic[C][1]*dic[B][1]
                dic[B] = [dic[B][0],dic[C][1]]
                stk.append(B)
        print(num)
    except:
        break

71字符串通配符

问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
#正则化,发现会超时,对输入进行了进一步处理降低复杂度就行了
import re
while True:
    try:
        str1 = input()#记录第一行
        str2 = input()#记录第二行
        str1 = list(str1)
        counter=0#初始判定值
        for i in range (len(str1)):
            if str1[i] == "*" and counter ==0:
                counter = 1#当为相隔后第一个*时,保留此*并继续
            elif str1[i] == "*" and counter ==1:#当后续依然为*时,去除多余*因为*本身代表0-n个,从而减小计算复杂度
                str1[i] = ""#比如最后一个例子“h*h*ah**ha*h**h***hha” 重复*太多复杂度太大
            else:
                counter=0#一旦不是连续的*则重置判定值
        str1=''.join(str1)#合并为str
        str1 = str1.lower()
        str2 = str2.lower()#不分大小写,统一小写处理
        str1=str1.replace('?', '[0-9 a-z]')#统一小写+数字,不能用\w因为\w包括下划线,别涂省事规规矩矩打上
        str1=str1.replace('*','[0-9 a-z]*')#统一小写+数字 *代表0或多个
        str1=str1.replace('.','\.' )#由于.本身代表匹配除换行符以外的任意字符,需要转义
        str1 = "^"+str1+"$"
        search = re.match(str1, str2)#这道题用match(),如果是要求匹配整个字符串,直到找到一个匹配的规则的字符串则用search()
        if search != None:
            print('true')
        else:
            print('false')
    except:
        break

88扑克牌大小

扑克牌游戏大家应该都比较熟悉了,一副牌由54张组成,含3~A、2各4张,小王1张,大王1张。牌面从小到大用如下字符和字符串表示(其中,小写joker表示小王,大写JOKER表示大王):
# coding = utf-8
 
def main(input_string):
    l1, l2 = input_string.split('-')
    a = l1.split()
    b = l2.split()
    poker_dict = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':11, 'Q':12, 'K':13, 'A':14, '2':15, 'joker':16, 'JOKER':17}
    # 若存在对王,则对王最大
    if 'joker JOKER' == l1 or 'joker JOKER' == l2:
        return 'joker JOKER'
    # 两边牌数量一致,已经根据大小排列且是相同类型,比较最小的牌点数
    if len(a) == len(b):
        if poker_dict[a[0]] < poker_dict[b[0]]:
            return l2
        else:
            return l1
            # 判断是否存在炸弹
    elif len(a) == 4:
        return l1
    elif len(b) == 4:
        return l2
    else:
        # 其他情况下不存在比较关系
        return 'ERROR'
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            res = main(input_string)
            print(res)
        except:
            break

90合法IP

# coding = utf-8
 
def main(input_list):
    res = []
    for i in input_list:
        if 0<=i<=255:
            res.append(1)
    if sum(res) == 4:
        print('YES')
    else:
        print('NO')
 
         
if __name__ =='__main__':
    while True:
        try:   
            input_list = list(map(int, input().split('.')))
            main(input_list)
        except:
            break

96表示数字

将一个字符中所有的整数前后加上符号“*”,其他字符保持不变。连续的数字视为一个整数。
# coding = utf-8
import re
 
def main(input_string):
    res = ''
    # 为了避免第一个字符为数字,拼接一个特殊字符
    input_string = ' '+input_string
    n = len(input_string)
    for i in range(n):
#         if input_string[i].isalpha():
        res += input_string[i]
        if i!= n - 1 and not input_string[i].isdigit() and input_string[i+1].isdigit():
            res += '*'
        elif i!= n -1 and input_string[i].isdigit() and not input_string[i+1].isdigit():
            res +='*'
        elif i == n-1 and input_string[i].isdigit():
            res += '*'
    # 去除人为拼接字符并返回结果
    return res[1:]
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

98自动售货系统

"""
Created on Tue Dec 22 07:53:19 2020
 
@author: legen
"""
 
class Machine(object):
    def __init__(self, arr):
        self.products = arr[0]
        self.changes = arr[1]
        self.price = [2,3,4,5,8,6]
        self.balance = 0
        print("S001:Initialization is successful")
     
    def insertMoney(self, coin):
        if coin not in [1,2,5,10]:
            print("E002:Denomination error")
            return
        if coin in [5, 10]:
            if self.changes[0] + self.changes[1]*2 < coin:
                print("E003:Change is not enough, pay fail")
                return
        if sum(self.products) == 0:
            print("E005:All the goods sold out")
            return
        h = {1:0, 2:1, 5:2, 10:3}
        self.changes[h[coin]] += 1
        self.balance += coin
        print("S002:Pay success,balance={}".format(self.balance))
        return
     
    def buy(self, item):
        h = {'A1':0, 'A2':1, 'A3':2, 'A4':3, 'A5':4, 'A6':5}
        if item not in h:
            print("E006:Goods does not exist")
            return
        if self.products[h[item]] == 0:
            print("E007:The goods sold out")
            return
        if self.price[h[item]] > self.balance:
            print("E008:Lack of balance")
            return
        self.products[h[item]] -= 1
        self.balance -= self.price[h[item]]
        print("S003:Buy success,balance={}".format(self.balance))
        return
     
    def popChange(self):
        if self.balance == 0:
            print("E009:Work failure")
            return
        self._combination()
        return
     
    def _combination(self):
        val = [1,2,5,10]
        f = [[None] * 4 for y in range(self.balance+1)]
        for i in range(self.balance+1):
            if i == 0:
                for j in range(4):
                    f[i][j] = 0
                continue
            for j in range(len(val)):
                if i >= val[j]:
                    if f[i-val[j]][j] + 1 <= self.changes[j]:
                        if f[i-val[j]][0] is not None:
                            prev = sum(f[i-val[j]])
                        else:
                            continue
                        if f[i][0] is None:
                            for k in range(4):
                                f[i][k] = f[i-val[j]][k]
                            f[i][j] += 1
                        else:
                            if sum(f[i]) > prev+1:
                                for k in range(4):
                                    f[i][k] = f[i-val[j]][k]
                                f[i][j] += 1
        for i in range(len(f)-1, -1, -1):
            if f[i][0] is not None:
                for j in range(4):
                    print("{} yuan coin number={}".format(val[j], f[i][j]))
                    self.changes[j] -= f[i][j]
                break
        self.balance = 0
        return
     
    def queryItem(self):
        name = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
        arr = [list(x) for x in zip(name, self.price, self.products)]
        arr.sort(key=lambda x: -x[2])
        for ele in arr:
            print(" ".join([str(x) for x in ele]))
        return
     
    def queryChange(self):
        val = [1,2,5,10]
        for i in range(len(self.changes)):
            print("{} yuan coin number={}".format(val[i], self.changes[i]))
        return
 
def vendingMachineOperation(jobs):
    for job in jobs:
        if job[0] == 'r':
            M = Machine([list(map(int, ele.split('-'))) for ele in job[1:]])
        elif job[0] == 'p':
            M.insertMoney(int(job[-1]))
        elif job[0] == 'b':
            M.buy(job[-1])
        elif job[0] == 'c':
            M.popChange()
        elif job[0] == 'q':
            if job[1] == 0:
                M.queryItem()
            elif job[1] == 1:
                M.queryChange()
            else:
                print("E010:Parameter error")
        else:
            print("E010:Parameter error")
    return
 
while True:
    try:
        jobs = list(input().split(';'))[:-1]
        jobs = [list(x.split()) for x in jobs]
        vendingMachineOperation(jobs)
    except:
        break

99 自守数

自守数是指一个数的平方的尾数等于该数自身的自然数。例如:25^2 = 625
# coding = utf-8
 
def main(nums):
    res = []
    for i in range(nums+1):
        if str(i) == str(i**2)[-len(str(i)):]:
            res.append(i)
#     print(res)
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            res = main(nums)
            print(len(res))
        except:
            break

102字符统计

输入一个只包含小写英文字母和数字的字符串,按照不同字符统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASCII码由小到大排序输出。
# coding = utf-8
 
def main(input_string):
    ch_dict = {}
    for i in input_string:
        ch_dict[i] = input_string.count(i)
    ch_dict = sorted(ch_dict.items(), key = lambda x:(-x[-1], x[0]))
    res = ''
    for i in ch_dict:
        res += i[0]
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            res = main(input_string)
            print(res)
        except:
            break

103Redraiment的走法

Redraiment是走梅花桩的高手。
# coding = utf8
 
def main(n, nums_list):
    # 起点为一步
    dp = [1 for i in range(n)]
    max_step = 0
    for i in range(n):
        for j in range(i):
            if nums_list[j] < nums_list[i]:
                dp[i] = max(dp[i], dp[j]+1)
            if max_step < dp[i]:
                max_step = dp[i]
    return max_step
     
     
if __name__ == '__main__':
    while True:
        try:
            n = int(input())
            nums_list = list(map(int, input().split()))
            print(main(n, nums_list))
        except:
            break

107求解立方根

# coding = utf-8
 
def main(num):
    # 立方根需要考虑负数的情况
    if num == 0:
        return 0
    elif num>0:
        flag = 1
    else:
        flag = -1
    # 取绝对值
    num = abs(num)
    # 判断num是<1还是>1,并确定相应的区间
    if num<1:
        start = num / 2
        end = 1
    else:
        start = 0
        end = num / 2
    mid = (start + end) / 2
    while abs(mid**3 - num)>1e-7:
        # 缩小范围
        if mid**3 > num:
             end = mid
        else:
            start = mid
        mid = (start + end) / 2
    return round(float(flag*mid), 1)
 
 
if __name__ == '__main__':
    while True:
        try:
            num = float(input())
            print(main(num))
        except:
            break

11数字颠倒

输入一个整数,将这个整数以字符串的形式逆序输出
# coding = utf-8
 
 
def main(input_num):
    return ''.join(list(str(input_num))[::-1])
 
 
if __name__ == '__main__':
    input_num = int(input())
    print(main(input_num))

12字符串反转

接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
def main(input_string):
    if len(input_string) > 1000:
        return '字符串长度超过1000'
    temp = ''.join([i for i in input_string[::-1] if i.lower()])
    return temp
 
 
if __name__ == '__main__':
    input_string = input()
    print(main(input_string))

22汽水瓶

如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝?
# coding = utf-8
import sys
 
def main(nums):
    if nums <= 1:
        return 0
    return nums // 2
 
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            if nums ==0:
                break
            print(main(nums))
        except:
            break

37统计每个月兔子的总数

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
# coding = utf-8
 
# 斐波那契数列
def count():
    month = int(input())
    a = 0
    b = 1
    while month>0:
        a, b = b, a+b
        month -= 1
    return a
           
     
if __name__ == '__main__':
    while True:
        try:
            print(count())
        except:
            break

50四则运算

输入一个表达式(用字符串表示),求这个表达式的值。保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
# coding = utf-8
 
 
def count(input_string):
    input_string = input_string.replace('{','(').replace('[','(').replace('}',')').replace(']',')')
    return int(eval(input_string))
     
 
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(count(input_string))
        except:
            break

53杨辉三角的变形

求第n行第一个偶数出现的位置。如果没有偶数,则输出-1。例如输入3,则输出2,输入4则输出3。
# coding = utf-8
 
def YangHui(line_index):
    # 杨辉三角每行的元素个数为 2n -1
    # 构建一个全0矩阵
    n = 2*line_index - 1
    # +2的目的是防止越界
    matrix = [[0 for i in range(n+2)] for j in range(line_index+1)]
    # 令第一行最中间值为1
    mid = (n+2)//2
    matrix[1][mid] = 1
    # 对杨辉三角赋值
    for i in range(2, line_index + 1):
        for j in range(1, n+1):
            matrix[i][j] = matrix[i-1][j] + matrix[i-1][j-1] + matrix[i-1][j+1]
    for j in range(1, len(matrix[line_index])-1):
        if matrix[line_index][j]%2 == 0:
            return j
 
    return -1
 
 
if __name__ == '__main__':
    while True:
        try:
            line_index = int(input())
            print(YangHui(line_index))
        except:
            break

54 表达式求值

给定一个字符串描述的算术表达式,计算出结果值。
# coding = utf-8
 
def main(input_string):
    if len(input_string)<=100:
        return eval(input_string)
     
     
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

56 完全数计算

它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。1+2+4+7+14=28
# coding = utf-8
 
def main(num):
    # res {1:[], 2:[1],...,4:[1,2]}
    res = {}
    for i in range(1, num+1):
        # 存储该数的所有公约数
        tmp = []
        for j in range(1, i+1):
            if i%j==0 and i != j:
                tmp.append(j)
        res[i] = tmp
    count = []
    # 计算满足条件的完全数
    for k, v in res.items():
        if k == sum(v):
            count.append(k)
    return len(count)
    # 计算是否为
 
 
 
if __name__ == '__main__':
    while True:
        try:
            num = int(input())
            print(main(num))
        except:
            break

61放苹果

把m个同样的苹果放在n个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?
 
def main(m, n):
    # 1.n个盘子有一个为空盘,即m个苹果放在n-1个盘子上
    # 2.至少每个盘子都放一个苹果,最多剩下m-n个苹果,将m-n个苹果放在n个盘子上
    if m<0 or n<0:
        return 0
    if m == 1 or n == 1:
        return 1
    return main(m, n-1) + main(m-n, n)
 
 
if __name__ == '__main__':
    while True:
        try:
            m, n = map(int, input().split())
            print(main(m, n))
        except:
            break

62查找输入整数二进制中1的个数

# coding = utf-8
 
def main(num):
    return bin(num).count('1')
 
 
if __name__ == '__main__':
    while True:
        try:
            num = int(input())
            print(main(num))
        except:
            break

66配置文件恢复

有6条配置命令
# coding = utf-8
 
 
def main(input_string):
    command_dict = {'reset':'reset what', 'reset board':'board fault','board add':'where to add', 'board delete':'no board at all',
                   'reboot backplane': 'impossible', 'backplane abort':'install first', 'he he':'unknown command'}
    input_string = input_string.strip()
    input_list = input_string.split()
    if len(input_list) <1:
        return ' '
    elif len(input_list) == 1:
        if input_list[0] == 'r' or 'res':
            return command_dict['reset']
        else:
            return command_dict['he he']
    elif len(input_list) == 2:
        for i in command_dict.keys():
            if input_list[0] in i and input_list[1] in i:
                return command_dict[i]
        else:
            return command_dict['he he']
    else:
        return command_dict['he he']
         
         
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

72百钱买百鸡问题

import random
 
 
def GetResult():
    # 百钱最多买20只公鸡, 33只母鸡
    for x in range(0, 21):
        for y in range(0, 34):
            z = 100 - x - y
            price = 5*x + 3*y + z/3
            if price == 100:
                print(x, y, z)
         
         
if __name__ == '__main__':
    begin = int(input())

73计算日期到天数转换

根据输入的日期,计算是这一年的第几天。
# coding = utf-8
 
def main(year, month, day):
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if year%4 == 0 and year%100 != 0:
        days[1] = 29
    last_day = sum(days[:month-1]) + day
    print(last_day)
 
     
if __name__ == '__main__':
    year, month, day = list(map(int, input().split()))
    main(year, month, day)

74

在命令行输入如下命令:xcopy /s c:\ d:\,请编写一个参数解析程序,实现将命令行各个参数解析出来。
#coding = utf-8
 
def main(input_string):
    input_string_list = list(input_string)
    # 存储每个"的索引
    tmp = []
    for i in range(len(input_string_list)):
        if input_string_list[i] == '"':
            tmp.append(i)
    # 将"中间部分的空格替换为特殊标记
    for i in range(0,len(tmp),2):
        for j in range(tmp[i],tmp[i+1]+1):
            if input_string_list[j] == ' ':
                input_string_list[j] = '$replace$'
    # 将处理完的列表拼接,并根据空格切分为列表
    replace_string = ''.join(input_string_list)
    replace_list = replace_string.split()
    # 输出每一个部分,并将"和特殊标记还原
    print(len(replace_list))
    for i in replace_list:
        if '$replace$' in i:
            i = i.replace('$replace$', ' ')
        print(i.replace('"',''))
     
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            main(input_string)
        except:
            break

75公共子串计算

给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。
# coding = utf-8
 
def main(input_string1, input_string2):
    if len(input_string1) > len(input_string2):
        input_string1, input_string2 = input_string2, input_string1
    m = len(input_string1)
    n = len(input_string2)
    res = []
 
    for i in range(m):
        for j in range(i+1, m):
            if input_string1[i:j] in input_string2 and len(input_string1[i:j])>2:
                res.append(input_string1[i:j])
    res = sorted(res, key = lambda x:len(x), reverse=True)
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string1 = input()
            input_string2 = input()
            res = main(input_string1, input_string2)
            print(len(res[0]))
        except:
            break

76尼科彻斯定理

验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。
# coding = utf-8
 
def main(nums):
    result = nums**3
    # 定理中,第一个数为 x = n(n-1) +1
    # 后续每个值+2
    res = [nums*(nums-1)+1]
    if nums>1:
        for i in range(1, nums):
            res.append(res[i-1] + 2)
    res = list(map(str, res))
    return res
 
 
 
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            res = main(nums)
            for i in range(len(res)):
                if i == nums-1:
                    print(res[i])
                else:
                    print(res[i]+'+', end='')
        except:
            break

83二维数组操作

# coding = utf-8
import random
def main(m, n, x1, y1, x2, y2, x, y, index_x, index_y):
    if 0<=m<=9 and 0<=n<=9:
        table = [[random.randint(1, m*n) for i in range(n)] for j in range(m)]
        print('0')
    else:
        print('-1')
         
    if 0<=x1<m and 0<=x2<m and 0<=y1<n and 0<=y2<n:
        table[x1][y1], table[x2][y2] = table[x2][y2], table[x1][y1]
        print('0')
    else:
        print('-1')
         
    if m<9 and 0<=x<m:
        table.insert(x,[0 for i in range(n)])
        table = [[random.randint(1, m*n) for i in range(n)] for j in range(n)]
        print('0')
    else:
        print('-1')
         
    if n<9 and 0<=y<n:
        for i in table:
            i.insert(y,0)
        table = [[random.randint(1, m*n) for i in range(n)] for j in range(n)]
        print('0')
    else:
        print('-1')
         
    if 0<=index_x<m and 0<=index_y<n:
        print('0')
    else:
        print('-1')
        
 
 
if __name__ == '__main__':
    while True:
        try:
            m, n = map(int, input().split())
            x1, y1, x2, y2 = map(int, input().split())
            x = int(input())
            y = int(input())
            index_x, index_y = map(int, input().split())
            main(m, n, x1, y1, x2, y2, x, y, index_x, index_y)
        except:
            break

84统计大写字母个数

找出给定字符串中大写字符(即’A’-‘Z’)的个数。
# coding = utf-8
 
def main(input_string):
    alpha_dict = {}
    for i in input_string:
        if i.isupper():
            alpha_dict[i] = input_string.count(i)
    res = 0
    for k, v in alpha_dict.items():
        res += v
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

85最长回文子串

# coding = utf-8
 
def main(input_string):
    sub_string = {}
    for i in range(len(input_string)):
        for j in range(1, len(input_string)+1):
            if input_string[i:j] == input_string[i:j][::-1]:
                sub_string[input_string[i:j]] = len(input_string[i:j])
    sub_string = sorted(sub_string.items(), key = lambda x:x[-1], reverse = True)
    return sub_string[0][-1]
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

86求最大连续bit数

# coding = utf-8
import re
 
 
def main(nums):
    # bin()->0bxxxxx->[:2]->xxxxx
    bytes_string = ''.join([str(i) for i in bin(nums)[2:]])
    res = re.findall(r'1+',bytes_string)
    res.sort(key = lambda x:len(x),reverse = True)
    return len(res[0])
 
 
if __name__ == '__main__':
    while True:
        try:
            nums = int(input())
            print(main(nums))
        except:
            break

87密码强度等级

# coding = utf-8
import re
 
 
def main(input_string):
    input_length = len(input_string)
    score = 0
    flag = 0 # 奖励
     
    if input_length<=4:
        score += 5
    elif 5<=input_length<=7:
        score += 10
    elif input_length>=8:
        score += 25
         
    alpha_list = re.findall(r'[a-zA-Z]+', input_string)
    if len(alpha_list) == 0:
        score += 0
    else:
        flag += 1
        ch_string = ''.join(alpha_list)
        ch_length = len(ch_string)
        # 统计所有字母长度,并找到所有小写字母长度,比较,若相等则说明没有大写字母
        lower_list = ''.join(re.findall(r'[a-z]+', ch_string))
        if len(lower_list) == ch_length:
            score += 10
        # 说明全是大写字母
        elif len(lower_list) == 0:
            score += 10
        # 大小写混合
        else:
            flag += 1
            score += 20
 
    if len(re.findall(r'\d', input_string)) == 1:
        flag += 1
        score += 10
    elif len(re.findall(r'\d', input_string)) >1:
        flag += 1
        score += 20
    else:
        score += 0
         
         
    item = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
    item_list = []
    for i in item:
        if i in input_string:
            item_list.append(i)
    if len(item_list) == 1:
        flag += 1
        score += 10
    elif len(item_list) > 1:
        flag += 1
        score += 25
    else:
        score += 0
 
    if flag == 2:
        score += 2
    elif flag == 3:
        score += 3
    else:
        score += 5
    if score>=90:
        print('VERY_SECURE')
    elif 80<=score<90:
        print('SECURE')
    elif 70<=score<80:
        print('VERY_STRONG')
    elif 60<=score<70:
        print('STRONG')
    elif 50<=score<60:
        print('AVERAGE')
    elif 25<=score<50:
        print('WEAK')
    else:
        print('VERY_WEAK')
         
         
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            main(input_string)
        except:
            break

91走方格的方案数

请计算n*m的棋盘格子
# coding = utf-8
 
def fn(n, m):
    if n == 0 or m == 0:
        return 1
    else:
        return fn(n-1, m) + fn(n, m-1)
 
 
if __name__ =='__main__':
    while True:
        try:
            n, m = map(int, input().split())
            print(fn(n, m))
        except:
            break

100等差数列

# coding = utf-8
 
def main(nums):
    a0 = 2
    d = 3
    res = []
    for i in range(1, nums+1):
        res.append(a0 + d*(i-1))
    # 或者 n*a0 + d*n*(n-1)/2
    return res
 
 
if __name__ =='__main__':
    while True:
        try:
            nums = int(input())
            res = main(nums)
            print(sum(res))
        except:
            break

106字符逆序

将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。
# coding = utf-8
 
def main(input_string):
    res = ''
    for i in range(len(input_string)-1, -1, -1):
        res += input_string[i][::-1]
    return res
 
 
if __name__ == '__main__':
    while True:
        try:
            input_string = input()
            print(main(input_string))
        except:
            break

108求最小公倍数

# coding = utf-8
 
def main(a, b):
    i = 1
    while a*i%b !=0:
        i+=1
    return a*i
     
 
if __name__ == '__main__':
 
    a, b = map(int, input().split())
    print(main(a, b))


7取近似值

写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。
# coding = utf-8
 
 
def main(nums):
    if (nums * 10 - int(nums) * 10) < 5:
        return int(nums)
    else:
        return int(nums) + 1
     
     
if __name__ == '__main__':
    nums = float(input())
    print(main(nums))

15求int型正整数在内存中存储时1的个数

# coding = utf-8
 
def main(nums):
    return (bin(nums).count('1'))
 
     
if __name__ == '__main__':
    nums = int(input())
    print(main(nums))

你可能感兴趣的:(笔记,python)