Python 练习二

1、判断一个数是否是回文数。

a、什么是回文数?

"回文"是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如"我为人人,人人为我"等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。

设 n 是一任意自然数。若将 n 的各位数字反向排列所得自然数 n1 与 n 相等,则称 n 为一回文数。例如,若 n=1234321,则称n为一回文数;但若 n=1234567,则 n 不是回文数。

注意:

1.偶数个的数字也有回文数124421
2.小数没有回文数

b、1千以内的回文数

在自然数中,最小的回文数是 0,其次是1,2,3,4,5,6,7,8,9,11,22,33,44,…,979,989,999.

c、平方回数

一个回文数,它同时还是某一个数的平方,这样的数字叫做平方回数。例如:121。
100以上至1000以内的平方回数只有3个,分别是:121、484、676。

# palindromeNumber.py
# 1、判断回文数
# 方法 1 flag 用法
pn = input('Please enter a number:')
i  =0
j = len(pn)-1
flag = True
while i <= j:
    if pn[i] != pn[j]:
        print('No')
        flag=False
        break
    i,j = i+1, j-1
if flag:
    print('Yes')

# 方法 2 while else 用法
pn = input('Please enter a number:')
i = 0
j = len(pn)-1

while i <= j:
    if pn[i] != pn[j]:
        print('No')        
        break

    i,j = i+1,j-1

else:  # 只要不是通过break退出循环就运行
    print('Yes')

# 方法 3 切片
pn = input('Please enter a number:')
if pn == pn[::-1]:
    print('Yes')
else:
    print('No')

# 方法 3 进一步简化
print('Yes') if pn==pn[::-1] else print('No')

# 2、1千内的回文数
for i in range(1000):
    s = str(i)    
    if s == s[::-1]:
        print(i,end=',') 

# 3、判断平方回数
pn = input('Please enter a number:')
num = int(pn)**0.5
print('Yes') if pn==pn[::-1] and int(num)==num else print('No')

def ispn(n):
    num = str(n)
    if num == num[::-1]:
        return True
    else:
        return False

if __name__=='__main__':
    print('测试成功') if ispn(12321) and ispn(123321) and ispn(6) and not ispn(342) else print('测试失败')

2、输入一个标识符,判断是否合法。

# isid.py
# 判断变量名是否合法
import keyword

value = input('变量名:')
if value[0].isdigit() or value in keyword.kwlist:
    print('不合法')
else:
    for i in value:
        if not i.isalnum() and not i == '_':
            print('不合法')
            break
    else:
        print('合法')
# 封装成函数
import keyword

def isname(name):
    if not name or name in keyword.kwlist:return False  # 考虑空串和保留字        

    # s = name.replace('_', '') # 删除'_',因为有它是合法的
    # if not s:return True # 考虑只含 '_' 的情况 s='_' or '___'
    s = name.replace('_', 'x') # 用任意的字母替换 _ 可以简化

    return not name[0].isdigit() and s.isalnum() 

if __name__ == '__main__':
    # print('测试成功') if not isname('') and isname('_') and isname('_1') \
    #     and isname('___') and isname('_a1') and not isname('as$12') and \
    #     not isname('1_asdf') and not isname('_$') and not isname('$') else print('测试失败')
    try:
        assert not isname('')
        assert not isname('as$12') 
        assert not isname('1_asdf') 
        assert not isname('_$') 
        assert not isname('$') 
        assert isname('_') 
        assert isname('_1')
        assert isname('___') 
        assert isname('_a1')
        print('测试成功')
    except Exception as e:
        print(e)
        print('测试失败')

3、重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含标点符号;

# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;

# countWords.py
# 打印出每个单词及其重复的次数

sentence = input('Please enter a sentence :')
words = sentence.split()
print(words)
wordCount = {}
# 方法一
for word in words:
    if word in wordCount:
        wordCount[word] += 1
    else:
        wordCount[word] = 1

print(wordCount)
# 方法二
w = set(words)
for word in w:
	wordCount[word] = words.count(word)
	
print(wordCount)

4、反转句子中单词的顺序

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。
比如: “hello xiao mi”-> “mi xiao hello”

# inverseSentence.py
# 将给定句子中的单词的位置反转

# 题目描述:
# 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,>单词用空格分割, 单词之间只有一个空格,前>后没有空格。
# 比如: “hello xiao mi”-> “mi xiao hello”

sentence = input('Please enter a sentence:')
words = sentence.split()

for i in words[::-1]:
    print(i,end=' ')

print(' '.join(input().split()[::-1]))
print(' '.join(input('enter:').split()[::-1]))

5、编写一个程序,实现编码功能。

# chr(i)
# 返回 Unicode 码位为整数 i 的字符的字符串格式。
# 例如,chr(97) 返回字符串 'a',chr(8364) 返回字符串 '€'。这是 ord() 的逆函数。

# ord(c)
# 对表示单个 Unicode 字符的字符串,
# 返回代表它 Unicode 码点的整数。
# 例如 ord('a') 返回整数 97, ord('中') 返回 20013 。

把汉字的 Unicode 编码转换成 UTF-8 编码,即实现 ‘中’.encode() 功能。
如:”中” Unicode 编码是 20013(ord(‘中’) = 20013,二进制:

>>> bin(ord('中'))
'0b100111000101101'

UTF-8 编码是

>>> '中'.encode()
b'\xe4\xb8\xad'

转换规则:二进制分成三段,11100100 10111000 10101101 对应 16 进制 0xe4 0xb8 0xad

# encodeing.py
# 把“中” unicode => utf-8

s = bin(ord('中')).replace('b', '')
l = list(s)

l.insert(-12,'10')
l.insert(-6,'10')
l.insert(0,'1110')

x = ''.join(l)
print(x)
f1 = x[:8]
f2 = x[8:-8]
f3 = x[-8:]
print(f1,f2,f3)
g1 = int(f1,2)
g2 = int(f2,2)
g3 = int(f3,2)
print(g1,g2,g3)
h1 = hex(g1)
h2 = hex(g2)
h3 = hex(g3)
print(h1,h2,h3)