整理了自己练习的Python基础:

偶数求和

# 偶数求和
sum([i for i in range(101) if i%2==0])

sum = 0
for i in range(0,101,2):
    sum += i
print(sum)

something = sys.stdin.readline().strip()

请输出奇数位字母

# 请输出奇数位字母
st = 'Hello Python DuShuSir'
sr =[]
i=0
while i<len(st):
    if i%2!=0:
        sr.append(st[i])
    i +=1
print(sr)

请输出纯数字项

>>> str ="h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]

输出数字

import re
totalCount = '100abc'
totalCount = re.sub("\D", "", totalCount)
print(totalCount)
>>> 100

已知一个二叉树前序遍历和中序遍历分别为ABDEGCFH和DBGEACHF,则该二叉树的后序遍历为?

答:DGEBHFCA

计算题,判断变量是否为0, 是0则为False,非0判断为True

# and中含0,返回0; 均为非0时,返回后一个值, 
2 and 0   # 返回0
2 and 1   # 返回1
1 and 2   # 返回2

# or中, 至少有一个非0时,返回第一个非0,
2 or 0   # 返回2
2 or 1   # 返回2
0 or 1   # 返回1 

#实际题目,网易的选择题好像是
a = 'hello'
b = [1,2]
print(a and b)  #[1, 2]
print(b and a)  #hello

改变字母大小写

# 改变字母大小写
def change(text):
    list_a = []
    for i in text.split(' '):
        list_a.append(i.capitalize())
    a = ' '.join(list_a)
    return a

text = 'hello your world!'
change(text)

list_b = []
for i in text.split(' '):
    list_b.append(i.capitalize())
b = ' '.join(list_b)
print(b)

字母大小写

s='What is Your Name?'
s2=s.lower()
print(s2) #返回小写字符串
# what iss your name?
print(s.upper())    #返回大写字符串
# WHAT IS YOUR NAME?
print(s.capitalize())   #字符串首字符大写
# What is your name?
print(s.title())    #每个单词的首字母大写
# What Is Your Name?
print(s.swapcase()) #大小写互换
# wHAT IS yOUR nAME?

#提取一个整数的偶数位

# 第一题:提取一个整数的偶数位
# 1.输入123456,输出246
list[::2 ] #就是取奇数位 这里的 i j 我们省略的话就是默认数组最开头到结尾
list[1::2] #这里缺省了j 但是i定义了1 也就是从数组第二个数开始取 ,所以这个是取偶数位
a = int(12345678)
b = list(str(a))
c = []
for i, num in enumerate(b):
    if i%2 != 0:
        c.append(num)

print(''.join(c))

统计一个字符串中的字符和数字出现个数

# 统计一个字符串中的字符和数字出现个数
# 2.输入a3rcd57sc8,输出 数字个数 4 字符个数 6
intCount = 0  #用来记录列表中的int元素个数
strCount = 0 #记录str元素个数
spacecount = 0
otherCount = 0
a = "pl421z inp42ut442 a string343bgb2 gfregfe%%%%%"
# 使用for循环遍历字符串,每次循环判断当前获取的元素的类型,并给对应计数器计数
for i in a:   
    if i.isdigit(): #判断i是不是int
        intCount += 1
    elif i.isalpha(): #判断i是不是str
        strCount += 1
    elif i.isspace():
        spacecount += 1
    else:
        otherCount += 1
print ("数字=%d,字母=%d,其他=%d, 空格%d" % (intCount,strCount,otherCount,spacecount))

A-Z对应1-26,输入一串字符,输出对应的数。

# A-Z对应1-26,输入一串字符,输出对应的数。
l1 = ['a','b','c','d','e']
l2 = [1,2,3,4,5]
a = input()
dict_1 = dict(zip(l1,l2))
print(dict_1[a])

子字符串

# 子字符串
def cut(s: str):
    results = []
    # x + 1 表示子字符串长度
    for x in range(len(s)):
        # i 表示偏移量
        for i in range(len(s) - x):
            results.append(s[i:i + x + 1])
    return results


print(cut('abc'))

统计字符个数

#统计字符个数
str=input("请输入一串字符:")
resoult={}
for i in set(str):
    resoult[i]=str.count(i)
print(resoult)

def count_char(test_str):
    """统计字符串的个数"""
    count_dict = {}  # 存储统计结果的字典
    for k in set(test_str):
        if k == " ":
            continue
        count_dict[k] = test_str.count(k)
    return count_dict

test_str = "hello world"
count_dict = count_char(test_str)
print(count_dict)

判断闰年

def mian():
    year = int(input('请输入年份: '))
    # 如果代码太长写成一行不便于阅读 可以使用\或()折行
    is_leap = ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0)
    print(is_leap)

if __name__ == '__main__':
    main()

词频统计,统计计数

#词频统计
a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
b = set(a)
for each_b in b:
    count = 0
    for each_a in a:
        if each_b == each_a:
            count += 1
    print(each_b, ": ", count)
# 统计计数
a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
b = {}
for i in a :
    b[i] = a.count(i)
print(b)

# 字典、列表计数
list=[1,2,1,2,3,3,4,5,4]
set=set(list)
dict={}
for item in set:
    dict.update({item:list.count(item)})
print(dict)

l = 'give me an offer' 
a = list(l.split(' '))
d = {}
for i in a:
    d[i] = l.count(i)

print(d)

# 或者
l = 'give me an offer' 
a = list(l.split(' '))
d = {}
for i in a:
    d[i] = len(i)
sort_str = max(d.items(),key = lambda x: x[1])
print(sort_str)

#利用pandas模块下的value_counts方法(这里需要安装pandas模块)
import pandas as pd
list=[1,2,1,2,3,3,4,5,4]
result=pd.value_counts(list)
print(result)
# 按照sort的value排序,默认降序
import pandas as pd
list=[1,2,1,4,4,1,1,1,5,2,2,2,2,3,3,3,4,4,4,4,3,4,5,4]
result=pd.value_counts(list,sort = True,ascending = True)
print(result)

n = int(input())
b = int(input())
count = 0
for i in range(1,n+1):
    if i%b == 0:
        count += 1
print(count)

字符串反转

import operator
l = 'give me an offer' 
a = list(l.split(' '))
b = {}
for i in a :
    b[i] = len(i)
c = sorted(b.items(), key = operator.itemgetter(1))
print(c[-1])
# 或者 
l = 'give me an offer' 
a = list(l.split(' '))
d = {}
for i in a:
    d[i] = len(i)
sort_str = sorted(d.items(),key = lambda x: x[1],reverse = True)
print(sort_str[0])


a = list(l.split(' '))
a = list(l.split(' '))    #后面存在空格





# 不能list(int(a)),可以list(str(a))
# 字符串反转
a = str(1234537378)
print(a[::-1])
# 或者
def fanzhaun(str):
    b = list(str)
    b.reverse()
    return ''.join(b)
a = str(1234537378)
print(fanzhaun(a))
   
a = str(1234537378)
b = list(a)
b.reverse()     
print(''.join(b))

走台阶,斐波那契数列

# 走台阶,斐波那契数列
def taijie(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    elif n >2:
        return taijie(n-1)+taijie(n-2)
    else:
        return 0 
print(taijie(20))
# 函数要打印   函数要打印   函数要打印 只是运行了

二进制求和

# 二进制求和
a = '11'
b = '1'
print(bin(int(a,2)+int(b,2))[2:])

计算字符串长度,中文算两个,一个中文utf8编码后是占3个字符

# 计算字符串长度,中文算两个,一个中文utf8编码后是占3个字符
txt = '名字12' 
lenTxt = len(txt) 
lenTxt_utf8 = len(txt.encode('utf-8')) 
size = int((lenTxt_utf8 - lenTxt)/2 + lenTxt)
print("size = " , size ," ,urf8 = ",lenTxt_utf8," ,len = " ,lenTxt)

判断是否为素数

# 判断是否为素数
def is_leap(a):
    for i in range(2,a):
        if a%i == 0:
           return '不是质数'
    return '质数'        
print(is_leap(13))


n = 13
for i in range(2,n):
    if n % i == 0:    
        print("%d不是素数!"%n)
        break
else:
    print("%d是素数!"%n)

提取数字

# 提取数字
totalCount = '100abc'
totalCount = re.sub("\D", "", totalCount)

import re
string="A1.45,b5,6.45,8.82"
print(re.findall(r"\d+\.?\d*",string))
# ['1.45', '5', '6.45', '8.82']

从字符串中提取字母字符串

#从字符串中提取字母字符串
import re
st = "hello,world!!%[545]你好234世界。。。"
result = ''.join(re.findall(r'[A-Za-z]', st)) 
print(result)

re模块 提取数字

import re
str1 = '2016年1月9日'
pattern = re.compile(r'\d+') 
res = re.findall(pattern, str1)
for i in res:
    print(i)
#提取数字  输出三个数 2016    1   9 
#如果是re.sub 输出 一个字符串201619

阶乘

# 阶乘
def jiecheng(n):
    if n == 1:
        return 1
    else :
        return n*jiecheng(n-1)    
print(jiecheng(5))
# 或者
n = 10
a = 1
for i in range(1,n+1):
	a = a*i
print(a)

from fuctools import reduce
n = 10
result = reduce(lambda x,y:x*y,range(1,n+1))
print(result)

统计列表数量

# 统计列表数量
list=[1,2,1,2,3,3,4,5,4]
set=set(list)
dict={}
for item in set:
    dict.update({item:list.count(item)})
print(dict)

求完全数

# 求完全数
for i in range(1,1000):
  s=0
  for k in range(1,i):
    if i%k==0:
      s=s+k
  if i==s:
    print i

求1000以内的完全平方数

# 求1000以内的完全平方数
l = []
for i in range(1,1000):
    if i*i <1000:
        l.append(i*i)
print(l)

import math
n = 10
a = int(math.sqrt(n))
if a*a == n:
    print('True')
else:
    print('False')
# 完全平方数

判断是否完全平方数

import math
def is_sqr(n):
    a = int(math.sqrt(n))
    return a * a == n

print(is_sqr(12))

输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组.

#  输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组.
l = '2 1 4 5 6 13 7 2 9 6'
a = list(l.split(' '))
b = list(map(int,a))
max_b = max(b)
b.remove(max_b)
b.insert(0,max_b)
min_b = min(b)
b.remove(min_b)
b.append(min_b)
print(b)

求只出现一次的第一个字符

l = 'givemeanoffer' 
a = list(l)
d = {}
for i in a:
    d[i] = a.count(i)
sort_str = min(d.items(),key = lambda x: x[1])
for key,value in d.items():    
    if value == 1:
        print(key)
        break
#遍历字典,通过值求键

猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

p = 1
for i in range(5,0,-1):
    p = (p+1)*2
print(p)
# 或者

p = 1
print('第10天吃之前就剩1个桃子')
for i in range(9, 0, -1):
    p = (p+1) * 2
    print('第%s天吃之前还有%d个桃子' % (i, p))
print('第1天共摘了%s个桃子' % p)

字符串反转

# 字符串反转
print(''.join(reversed(list(a))))

print(a[::-1])

替换字符串

# 替换字符串
import re
totalCount = '100abca'
totalCount_1 = re.sub("a", "A", totalCount)
totalCount_2 = totalCount.replace("a", "A")
print(totalCount_2)

字符串大小写

# 字符串大小写
s.swapcase()
s.tltle()

判断{}年{}月{}日是这一年的第:{}天

if __name__=="__main__":
    a=[[31,28,31,30,31,30,31,31,30,31,30,31],[31,29,31,30,31,30,31,31,30,31,30,31]]
    year=int(input("请输入需要判断的年:"))
    month = int(input("请输入需要判断的月:"))
    day = int(input("请输入需要判断的日:"))
    sum=0
    if (year%4==0 and year%100!=0)or year%400==0:
        for i in range(1,month):
            sum=sum+a[1][i]
    else:
        for i in range(1,month):
            sum=sum+a[0][i]
    sum=sum+day
    print("{}年{}月{}日是这一年的第:{}天".format(year,month,day,sum))

判断一个数组是否存在两数之和等于一个数

# 判断一个数组是否存在两数之和等于一个数
def twoSum(nums, target):
    n = len(nums)

    for x in range(n):
            for y in range(x+1,n):
                if nums[y] == target - nums[x]:
                    #返回x和y
                    return x,y
                    break
                else:
                    continue
                
print(twoSum([1,2,4,6,7,2,4,9],10))
#辗转相除法
def first_way(a, b):
    """
    第一种方法:欧几里得算法----辗转相除法
    :param a: 第一个数
    :param b: 第二个数
    :return: 最大公约数
    """
    # 如果最终余数为0 公约数就计算出来了
    while(b!=0):
        temp = a % b
        a = b
        b = temp
    return a

# 求两个数的最小公倍数
def lcm(a,b):
    return a * b / first_way(a, b)
print()

奇偶互换

# 奇偶互换
s = 'abcdef49'
t=list(s)
t[::2],t[1::2]=t[1::2],t[::2]
print(''.join(t))

1 2 3 4组成不重复的三位数

for i in range(1,5):
 for j in range(1,5):
  for k in range(1,5):
   if( i != k ) and (i != j) and (j != k):
    print(i,j,k)
# 1 2 3 4组成不重复的三位数

好累啊,剩下的自己琢磨是啥东西吧

import sys
string=list(sys.stdin.readline().strip())
if len(set(string))==2:
    print(2)
if len(set(string))==1:
    print(1)
if len(set(string))>2:
    print(0)
#x,f,d,p=map(int,input().split())
import sys
line = sys.stdin.readline().split(' ')
lines = map(lambda x:int(x.strip('/n')),line)



import math
if __name__ == "__main__":
    learning_rate = 0.01
    for a in range(1,100):
        cur = 0
        for i in range(1000):
            cur -= learning_rate*(cur**2 - a)
        print(' %d的平方根(近似)为:%.8f,真实值是:%.8f' % (a, cur, math.sqrt(a)))

	main()


lists = [1,0,0,3,2]
j = lists.count(0)
while 0 in lists:
	lists.remove(0)
n = 0
while n < j:
	lists.append(0)
	n += 1
print(lists)

a = '13036009'
b = list(a)
l = list(map(int,b))
j = l.count(0)
while 0 in l:
	l.remove(0)
n = 0
while n < j:
    l.append(0)
    n += 1
print(l)


a = ['1','2','3']
print(list(map(int,a)))