Python学习第三天

GitHub中Python的简单题训练(共24天)

1 字符串排序 删重复

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

s=input()
words=[word for word in s.split(' ')]
print(" ".join(sorted(list(set(words)))))

注意:
① set()可以删去重复的,生成集合
list()生成列表【】
② 输入单独拎出来,再分割借用【】里 for语句
set()用法

list()用法

另外解法: 统计个数多于1的删去即可

word = input().split()

for i in word:
    if word.count(i) > 1:
        word.remove(i)
word.sort()
print(' '.join(word))

count()用法

注意:
count 如果检测是list里面的‘’里的内容,不是单个字母出现的次数,若检测单个字母出现的次数,可把list转换成str:

举例count()用法
str = "this is string example....wow!!!";
 
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)

以上实例输出结果如下:
str.count(sub, 4, 40) :  2
str.count(sub) :  1

另外解法

inp_string = input('enter:').split()

out_string = []

for words in inp_string:
    if words not in out_string:
        out_string.append(words)

print(' '.join(sorted(out_string)))

输出的list【】最开始空的,不重复往里添加split好的words,最后sorted

2.进制转换

Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010

value=[]
items=[x for x in input().split(',')]
for p in items:
    intp = int(p,2)
    if not intp %5:
        value.append(p)
print(','.join(value))

注意:
①进制转换直接int(‘xxx’,2/10/8)
int()用法

②被5整除,即:若除了5以后余数为零,if not一转即为TRUE,则执行下面的语句append

   在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False 
   **对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。** 

if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。
if not用法(有举例详细)
if not 用法

另外解法

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))

注意:
①设一个函数判断是否符合
②filter(fun,object)里面自变量object就是上一步输入的data,返回后可放在列表中,即list()框起来
③ 函数部分 也可以写成:

def check(x):
   if int(x,2)%5 ==0:
       return x

return int(x,2)%5 == 0 即满足条件再返回,∴也可以拆成if判断

另外解法

print(*(binary for binary in input().split(',') if int(binary,base=2)%5==0))

3.数字str

Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.

(每个数字各个位上的数字都是偶数)

values=[]
for i in range(1000,3001):
    s=str(i)
    if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2 == 0) and (int(s[3])%2 == 0):
        values.append(s)
        
print(','.join(values))

注意:
①∵一共四位,∴0~3位上一起判断
②s=str(i)把每个数字变成字符串str形式,然后可以索引0-3位置

**另外解法 **
像上一题列函数

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))

注意:
ord()用法
即int(’xx’,10)返回十进制的数值
for i in element 即是 找element每个位上的数字!!

4.计算字符串长度和单词数

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

s=input()
d={'DIGITS':0,'LETTERS':0}
for c in s:
    if c.isdigit():
        d['DIGITS']+=1
    elif c.isalpha():
        d['LETTERS']+=1
    else:
        pass
print('LETTERS',d['LETTERS'])
print('DIGITS',d['DIGITS'])
    

注意:
isdigit()用法
识别数字 字符串是否由数字组成
isalpha()用法
是否由字母组成
③ 用字典存放数字 字母 分别对应的个数
④输入直接赋给s不用split等操作 直接视为str
for c in s判断每一个字母

另外解法

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))

注意:
①最直观的判断方法
② format输出用法
format输出及Python格式化输出

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
位置匹配
  (1)不带编号,即“{}”
  (2)带数字编号,可调换顺序,即“{1}”、“{2}”
  (3)带关键字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world'))  # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字
world hello world

另外解法
(我的idle一直报错 输出f那里“”还是‘’都报错,这里放上 主要学习一下f用法,但是估计用不上(⊙o⊙)…

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

其中 输出的格式:
格式化的字符串文字前缀为’f’和接受的格式字符串相似str.format()。它们包含由花括号包围的替换区域。替换字段是表达式,在运行时进行评估,然后使用format()协议进行格式化。
formatted string literals, 以 f 开头,包含的{}表达式在程序运行时会被表达式的值代替。

print里面f’'的用法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值