华为机试在线训练–牛客网(python)

华为机试在线训练–牛客网(python)

第一部分(1~10)

第一题:求字符串最后一个单词的长度

#coding=utf-8
str = raw_input("")
space_sky = ' '
if space_sky in str:
    str_sp = str.split(' ')
    print len(str_sp[-1])
else:
    print len(str)

第二题:计算字符个数

#coding=utf-8
str1 = raw_input('')
str2 = raw_input('')
str1_new = str1.upper()#大写upper()或小写lower()
str2_new = str2.upper()
print str1_new.count(str2_new)

第三题:明明的随机数

import sys
while True:
    try:
        num=input()
        num_list=[]
        for i in range(num):
            input_num=sys.stdin.readline()
#            input_num=raw_input()
            num_list.append(int(input_num))
        num_list=sorted(set(num_list))
        for i in num_list:
            print i
    except:
        break

第四题:字符串分割

#coding=utf-8
def str_split_8(str):
    n = len(str)/8
    for i in range(n):
        print str[i*8:(i+1)*8]
    if len(str)%8>0:
        #字符串左对齐,长度为8,不够的用0补齐;如果字符串长度大于8,返回原始字符串
        print str[-(len(str)%8):].ljust(8,'0')
str1 = raw_input()
str2 = raw_input()
str_split_8(str1)
str_split_8(str2)

第五题:进制转换

#coding=utf-8
while True:
    try:
        print int(raw_input(),16)
    except:
        break

第六题:质数因子

#coding=utf-8
while True:
    try:
        num=int(input())
        i=2
        while num!=1:
            if num%i==0:
#,不能少使得每个质因数在同一行表示并且用空格隔开
                print i,
                num=num/i
            else:
                i+=1
    except:
        break

第七题:取近似值

#coding=utf-8
import string
while True:
    try:
        num = string.atof(raw_input())
        #四舍五入round();向下取整int();向上取整ceil();取整后还是浮点型
        print int(round(num))
    except:
        break

第八题:合并表记录

#coding=utf-8
while True:
    try:
        num = input()
        dic = {}
        for i in range(num):
            key, value = map(int,raw_input().split(' '))
            dic[key] = dic.setdefault(key, 0) + value
        for key in sorted(dic.keys()):
            print key, str(dic[key])
    except:
        break

第九题:提取不重复的整数

#coding=utf-8
while True:
    try:
        num = list(reversed(raw_input()))#reversed()倒置列表
        arr = []
        for i in num:
            if i not in arr:
                arr.append(i)
        print ''.join(arr)
    except:
        break

第十题:字符个数统计

#coding=utf-8
while True:
    try:
        def count_str(str):
            s= list(set(str))
            arr = []
            for i in s:
                if ord(i) > 0 and ord(i) < 127:
                    arr.append(s)
            print len(arr)
        num = raw_input()
        count_str(num)
    except:
        break

未完待续

你可能感兴趣的:(python基础编程)