当前位置: 首页 > article >正文

100+Python挑战性编程练习系列 -- day 3

Question 10

编写一个程序,接受一系列空格分隔的单词作为输入,并在删除所有重复的单词并按字母数字排序后打印这些单词。
假设向程序提供以下输入:
hello world and practice makes perfect and hello world again
然后,输出应为:
again and hello makes perfect practice world

方法1:

word = input().split()

for i in word:
    if word.count(i) > 1:    #count function returns total repeatation of an element that is send as argument
        word.remove(i)     # removes exactly one element per call

word.sort()
print(" ".join(word))

方法2:

word = sorted(list(set(input().split())))              #  input string splits -> converting into set() to store unique
                                                       #  element -> converting into list to be able to apply sort
print(" ".join(word))

Question 11

写一个程序,它接受一个由逗号分隔的4位二进制数序列作为输入,然后检查它们是否能被5整除。可被5整除的数字将以逗号分隔的顺序打印。
示例:
0100,0011,1010,1001
那么输出应该是:
1010

方法1:

def check(x):                       # converts binary to integer & returns zero if divisible by 5
    total,pw = 0,1
    reversed(x)

    for i in x:
        total+=pw * (ord(i) - 48)   # ord() function returns ASCII value
        pw*=2
    return total % 5

data = input().split(",")           # inputs taken here and splited in ',' position
lst = []

for i in data:
    if check(i) == 0:               # if zero found it means divisible by zero and added to the list
        lst.append(i)

print(",".join(lst))

方法2:

def check(x):                   # check function returns true if divisible by 5
    return int(x,2)%5 == 0      # int(x,b) takes x as string and b as base from which
                                # it will be converted to decimal
data = input().split(',')

data = list(filter(check,data)) # in filter(func,object) function, elements are picked from 'data' if found True by 'check' function
print(",".join(data))

方法3:

data = input().split(',')
data = [num for num in data if int(num, 2) % 5 == 0]
print(','.join(data))

Question 12

写一个程序,它将找到所有这样的数字之间的1000和3000(包括),使每个数字的数字是一个偶数。所获得的数字应以逗号分隔的顺序打印在一行上。

方法1:

lst = []

for i in range(1000,3001):
    flag = 1
    for j in str(i):          # every integer number i is converted into string
        if ord(j)%2 != 0:     # ord returns ASCII value and j is every digit of i
            flag = 0          # flag becomes zero if any odd digit found
    if flag == 1:
        lst.append(str(i))    # i is stored in list as string

print(",".join(lst))

方法2:

def check(element):
    return all(ord(i)%2 == 0 for i in element)  # all returns True if all digits i is even in element

lst = [str(i) for i in range(1000,3001)]        # creates list of all given numbers with string data type
lst = list(filter(check,lst))                   # filter removes element from list if check condition fails
print(",".join(lst))

方法3:(一行)

print(','.join([str(num) for num in range(1000, 3001) if all(map(lambda num: int(num) % 2 == 0, str(num)))]))

Question 13

写一个程序,接受一个句子并计算字母和数字的数量。
假设向程序提供以下输入:
hello world! 123
然后,输出应为:
LETTERS 10
DIGITS 3

方法1:

word = input()
letter,digit = 0,0

for i in word:
    if ('a'<=i and i<='z') or ('A'<=i and i<='Z'):
        letter+=1
    if '0'<=i and i<='9':
        digit+=1

print("LETTERS {0}\nDIGITS {1}".format(letter,digit))

方法2:

word = input()
letter, digit = 0,0

for i in word:
    if i.isalpha(): # returns True if alphabet
        letter += 1
    elif i.isnumeric(): # returns True if numeric
        digit += 1
print(f"LETTERS {letter}\n{digits}") # two different types of formating method is shown in both solution

方法3:

#using reduce for to count
from functools import reduce

def count_letters_digits(counters,char_to_check):
    counters[0] += char_to_check.isalpha()
    counters[1] += char_to_check.isnumeric()
    return counters

print('LETTERS {0}\nDIGITS {1}'.format(*reduce(count_letters_digits,input(),[0,0])))

所有上述问题大多是字符串相关的问题。解决方案的主要部分包括字符串相关函数和理解方法,以更短的形式写下代码。


http://www.kler.cn/news/17297.html

相关文章:

  • 2008-2019年主要城市PITI指数
  • 简单有趣的轻量级网络 Efficientnet(网络结构详解+详细注释代码+核心思想讲解)——pytorch实现
  • 华为OD机试 - 快递业务站(Python)
  • 三分钟教你看懂 spring 官方文档
  • 【ansys】project may be corrupted and recovery information is available
  • 达梦:dts工具迁移mysql decimal(65,30)的字段,报精度超出定义
  • 净利润下滑13%,帅丰电器已掉队?
  • ChatGPT 探讨内存屏障的意内存
  • 虹科荣誉 | 虹科工业物联网产品荣获中国自动化产业年会用户信赖产品奖!
  • 将 Segment Anything 扩展到医学图像领域
  • 数据埋点2
  • 华为OD机试 - 识图谱新词挖掘(Python)
  • PBDB Data Service:Output formats and Vocabularies(输出格式与术语表)
  • 腾讯高工手写13W字“Netty速成手册”,3天走向实战
  • 《可穿戴监测中的数据质量评估》阅读笔记
  • TypeScript进阶
  • 【数字IC前端笔试真题精刷(2022年)】大疆——数字芯片开发工程师A卷
  • Python | 人脸识别系统 — 用户操作
  • 单链表——单链表的定义及基本操作(初始化、头插法尾插法建表、查找、插入、删除、判空等)
  • 当ChatGPT续写《红楼梦》,能替代原著吗?
  • [计算机图形学]动画与模拟:关键帧动画、质点弹簧系统、运动学与绑定(前瞻预习/复习回顾)
  • 为什么用Selenium做自动化测试
  • ebpf-linux 安全“双刃剑”
  • 不合格机器人工程讲师如何坦然面对失败
  • Java算法比赛常用方法
  • Java入门超详细(内含Java基础 Java高级)
  • 100种思维模型之万物系统思维模型-57
  • Packet Tracer - 配置扩展 ACL - 场景 1
  • C语言通过控制台命令行传入参数
  • 安卓联发科MT6737手机开发核心板 开发模块