首页 > 其他分享 >2.2-2.50

2.2-2.50

时间:2024-10-20 09:59:08浏览次数:7  
标签:2.50 random np import print 2.2 x1 numpy

2.2

点击查看代码
from scipy.special import gamma
import pylab as plt
import numpy as np

plt.rc('text',usetex = True)
x=np.linspace(-5,5,1000)
plt.plot(x,gamma(x),c='k')
plt.xlabel('$x$')
plt.ylabel('$\Gamma(x)$');plt.show()
2.3
点击查看代码
L=['abc',12,3.45,'Python',2.789]
print(L)
print(L[0])
L[0] = 'a'
L[1:3]=['b','Hello']
print(L)
L[2:4] = []
print(L)
print("学号:2023310143010")
2.4
点击查看代码
a=[[1,2,3],[4,5,6],[7,8,9]]
d=[c for b in a for c in b]
print(d)
2.5
点击查看代码
'''
#(1)列出文件夹下所有exe和py文件
import os
fn=[filename for filename in
    os.listdir('C:/Users/setup/.spyder-py3/python数学建模')
    if filename.endswith(('.exe','.py'))]
print(fn)
print("学号:2023310143010")
 '''
 #(2)用列表推导式查找数组中最大元素的所有位置
from numpy.random import randint
import numpy as np
a = randint(10,20,16)
ma = max(a)
indl = [index for index,value in enumerate(a) if value==ma]
ind2=np.where(a==ma)
print(indl);print(ind2[0])
print("学号:2023310143010")
2.6 T = ('abc',12,3.45,'Python',2.789)#元组操作示例 print(T) print(T[-1]) print(T[1:3])

2.7
student = {'Tom','Jim','Mary','Tom','Jack','Rose'}
print(student)
a = set('abcdabc')#设置空集合用set(),它可将列表转换为集合
print(a)

2.8
dict1={'Alice':'123','Beth':'456','Cecil':'abc'}
print(dict1['Alice'])
dict1['new']='Hello'
dict1['Alice']='1234'
dict2 = {'abc':123,456:78.9}
print(dict2[456])

2.9
Dict= {'age':18,'score':[98,97],'name':'Zhang','sex':'male'}
print(Dict['age'])
print(Dict.get('age'))
print(Dict.get('address','Not Exists'))
print(Dict['address'])

2.10
Dict= {'age':18,'score':[98,97],'name':'Zhang','sex':'male'}
for item in Dict:
print(item)
print('-----------')
for item in Dict.items():
print(item)
print('-----------')
for value in Dict.values():
print(value)

2.11
import string
import random
x = string.ascii_letters+string.digits
y=''.join([random.choice(x) for i in range(1000)])
d=dict()
for ch in y:
d[ch] = d.get(ch,0)+1
for k,v in sorted(d.items()):
print(k,':,v')

import string,random,collections
x = string.ascii_letters+string.digits
y=''.join([random.choice(x) for i in range(1000)])
count = collections.Counter(y)
for k,v in sorted(count.items()):
print(k,':,v')

2.12
def factorial(n):
r = 1
while n>1:
r*=n
n-=1
return r
def fib(n):
a,b =1,1
while a<n:
print(a,end='')
a,b = b,a+b
print('%d!=%d'%(5,factorial(5)))
fib(3)

2.13
def bifurcate_by(L,fn):
return[[x for x in L if fn(x)],[x for x in L if not fn(x)]]
s = bifurcate_by(['beep','boop','foo','bar','boo'],lambda x:x[0]=='b')
print(s)

2.14
f = lambda x, y,z:xyz
L = lambda x:[x2,x3,x**4]
print(f(3,4,5));print(L(2))

2.15
import math
import random
import numpy.random as nr
a = math.gcd(12,21)
b=random.randint(0,2)
c = nr.randint(0,2,(4,3))
print(a);print(b);print(c)

2.16
from random import sample
from numpy.random import randint
a = sample(range(10),5)#在【0,9】区间上选择不重复的5个整数
b = randint(0,10,5)#在【0,9】区间上生成5个随机整数
print(a);
print(b)

2.17
from math import *
a = sin(3)
b = pi
c = e
d = radians(180)#把角度转化为弧度
print(a);print(b);print(c);print(d)

2.18
from ex2_12_2 import *
print(factorial(6))
fib(300)

2.19
import numpy.random as nr
x1 = list(range(9,21))
nr.shuffle(x1)
x2=sorted(x1)
x3=sorted(x1,reverse=True)
x4=sorted(x1,key=lambda item:len(str(item)))
print(x1);print(x2);print(x3);print(x4)

2.20
x1="abcde"
x2=list(enumerate(x1))
for ind,ch in enumerate(x1):print(ch)

2.21
import random
x = random.randint(1e5,1e8)
y = list(map(int,str(x)))
z = list(map(lambda x,y:x%21 and y%20,[1,3,2,4,1],[3,2,1,2]))
print(x);print(y);print(z)

2.22
a=filter(lambda x: x>10,[1,11,2,45,7,6,13])
b=filter(lambda x:x.isalnum(),['abc','xy12','***'])

isalnum是测试是否为字母或数字的方法

print(list(a));print(list(b))

2.23
def filter_non_unique(L):
return[item for item in L if L.count(item)==1]
a=filter_non_unique([1,2,2,3,4,4,5])
print(a)

2.24
s1=[str(x)+str(y) for x,y in zip(['v']*4,range(1,5))]
s2=list(zip('abcd',range(4)))
print(s1);print(s2)

2.25
import numpy as np
a1=np.array([1,2,3,4])
a2=a1.astype(float)
a3=np.array([1,2,3,4],dtype=float)
print(a1.dtype);print(a2.dtype);print(a3.dtype)
b=np.array([[1,2,3],[4,5,6]])
c=np.arange(1,5)
d=np.linspace(1,4,4)
e=np.logspace(1,3,3,base=2)

2.26
import numpy as np
a = np.ones(4,dtype=int)
b = np.ones((4,),dtype=int)
c = np.ones((4,1))
d = np.zeros(4)
e = np.empty(3)
f = np.eye(3)
g = np.eye(3,k=1)
h = np.zeros_like(a)
print(a);print(b);print(c);print(d);print(e);print(f);print(g);print(h);

2.27
import numpy as np
a = np.arange(16).reshape(4,4)
b = a[1][2]
c = a[1,2]
d = a[1:2,2:3]
f = np.array([0,1,2,1])
print(a);print(b);print(c);print(d);print(f);

2.28
import numpy as np
a = np.arange(16).reshape(4,4)
b = np.floor(5np.random.random((2,4)))
c = np.ceil(6
np.random.random((4,2)))
d = np.vstack([a,b])
e = np.hstack([a,c])
print(a);print(b);print(c);print(d);print(e);

2.29

import numpy as np
a = np.arange(16).reshape(4,4)
b = np.vsplit(a,2)
print('行分割:\n',b[0],'\n',b[1])
c = np.hsplit(a,4)
print('列分割:\n',c[0],'\n',c[1],'\n',c[2],'\n',c[3])

2.30

import numpy as np
a = np.array([[0,3,4],[1,6,4]])
b = a.sum()
c1 = sum(a)
c2 = np.sum(a,axis = 0)
c3 = np.sum(a,axis = 0,keepdims = True)
print(c2.shape,c3.shape)

2.31
import numpy as np
a = np.array([[0,3,4],[1,6,4]])
b = np.array([[1,2,3],[2,1,4]])
c = a/b
d = np.array([2,3,2])
e = ad
f = np.array([[3],[2]])
g = a
f
h = a**(1/2)
print(a);print(b);print(c);print(d);print(e);print(f);print(g);print(h);

2.32
import numpy as np
a = np.ones(4)
b = np.arange(2,10,2)
c = a@b
d = np.arange(16).reshape(4,4)
f = a@d
g = d@a
print(a);print(b);print(c);print(d);print(f);print(g)

2.33
import numpy as np
a = np.array([[0,3,4][1,6,4]])
b = np.linalg.norm(a,axis=1)
c = np.linalg.norm(a,axis=0)
d = np.linslg.norm(a)
print('行向量2范数为:',np.round(b,4))
print('列向量2范数为:',np.round(c,4))
print('矩阵2范数为:',round(d,4))

2.34
import numpy as np
a = np.array([[3,1],[1,2]])
b = np.array([9,8])
x1 = np.linalg.inv(a)*b
x2 = np.linalg.solve(a,b)
print(x1);print(x2)

2.35

import numpy as np
a = np.array([[3,1],[1,2],[1,1]])
b = np.array([9,8,6])
x = np.linalg.pinv(a)@b
print(np.round(x,4))

2.36
import numpy as np
a = np.eye(4)
b = np.rot90(a)
c,d = np.linalg.eig(b)
print('特征值为:',c)
print('特征向量为:\n',d)

2.37
import pandas as pd
import numpy as np
dates = pd.date_range(start = '20191101',end = '20191124',freq = 'D')
a1 = pd.DataFrame(np.random.randn(24,4),index = dates,columns = list('ABCD'))
a2 = pd.DataFrame(np.random.rand(24,4))
print(a1);print(a2)

2.38
import pandas as pd
import numpy as np
dates = pd.date_range(start = '20191101',end = '20191124',freq = 'D')
a1 = pd.DataFrame(np.random.randn(24,4),index = dates,columns = list('ABCD'))
a2 = pd.DataFrame(np.random.rand(24,4))
a1.to_excel('data2_38_1.xlsx')
a2.to_csv('data2_38_2.csv')
f = pd.ExcelWriter('data2_38_3.xlsx')
a1.to_excel(f,"Sheet1")
a2.to_excel(f,"Sheet2")
f.save()

2.39
import pandas as pd
a = pd.read_csv("data2_38_2.csv",usecols = range(1,5))
b = pd.read_excel("data2_38_3.xlsx","Sheet2",usecols = range(1,5))

2.40
import pandas as pd
import numpy as np
d = pd.DataFrame(np.random.randint(1,6,(10,4)),columns = list("ABCD"))
d1 = d[:4]
d2 = d[4:]
dd = pd.concat([d1,d2])
s1 = d.groupby('A').mean()
s2 = d.groupby('A').apply(sum)

2.41
import pandas as pd
import numpy as np
a = pd.DataFrame(np.random.randint(1,6,(5,3)),index = ['a','b','c','d','e'],columns = ['one','two','three'])
a.iloc['a','one'] = np.nan
b = a.iloc[1:3,0:2].values
a['four'] = 'bar'
a2 = a.reindex(['a','b','c','d','e','f'])
a3 = a2.dropna()

2.42
with open('data2_2.txt') as fp:
L1 =[];L2 = [];
for line in fp:
L1.append(len(line))
L2.append(len(line.strip()))
data = [str(num)+'\t'for num in L2]
print(L1);print(L2)
with open('data2_42.txt','w')as fp2:
fp2.writelines(data)

2.43
import numpy as np
a = np.random.rand(6,8)
np.savetxt("data2_43_1.txt",a)
np.savetxt("data2_43_2.csv",a,delimiter =',')
b = np.loadtxt('data2_43_1.txt')
c = np.loadtxt("data2_43_2.csv",delimiter = ',')

2.44
from scipy.optimize import fsolve,root
fx = lambda x: x980-5.01*x979+7.398x**978-3.388x977-x3+5.01x**2-7.398x+3.388
x1 = fsolve(fx,1.5,maxfev = 4000)
x2 = root(fx,1.5)
print(x1,'\n','-----------');print(x2)

2.45
from scipy.optimize import fsolve,root
fx = lambda x:[x[0]2+x[1]2-1,x[0]-x[1]]
s1=fsolve(fx,[1,1])
s2=root(fx,[1,1])
print(s1,'\n','-------');print(s2)

2.46
from scipy.integrate import quad
def fun46(x,a,b):
return ax**2+bx
I1 = quad(fun46,0,1,args = (2,1))
I2 = quad(fun46,0,1,args = (2,10))
print(I1);print(I2)

2.47
from scipy.optimize import least_squares
import numpy as np
a = np.loadtxt('data2_47.txt')
x0 = a[0];y0 =a[1];d=a[2]
fx = lambda x:np.sqrt((x0-x[0])2+(y0-x[1])2)-d
s = least_squares(fx,np.random.rand(2))
print(s,'\n','-------','\n',s.x)

2.48、

点击查看代码
from scipy.sparse.linalg import eigs
import numpy as np
a = np.array([[1,2,3],[2,1,3][3,3,6]],dtype=float)
b,c = np.linalg.eig(a)
d,e = eigs(a,1)
print('最大模特征值:',d)
print('对应的特征向量为:\n',e)
2.49
点击查看代码
import sympy as sp
a,b,c,x = sp.symbols('a,b,c,x')
x0 = sp.solve(a*x**2+b*x+c,x)
print(x0)
2.50
点击查看代码
import sympy as sp
sp.var('x1,x2')
s = sp.solve([x1**2+x2**2-1,x1-x2],[x1,x2])
print(s)

标签:2.50,random,np,import,print,2.2,x1,numpy
From: https://www.cnblogs.com/zhhhhha/p/18467344

相关文章

  • sicp每日一题[2.50]
    Exercise2.50Definethetransformationflip-horiz,whichflipspaintershorizontally,andtransformationsthatrotatepainterscounterclockwiseby180degreesand270degrees.这道题挺有意思的,搞明白这道题就明白了frame的3个点的位置。如上图所示,为了更好......
  • CDR2024最新25.2.2.313官方离线特别版下载+永久注册机
    CorelDRAW(简称CDR)是一款专业的图形设计软件。该软件是加拿大Corel公司开发的一款功能强大的专业平面设计软件、矢量设计软件、矢量绘图软件。这款矢量图形制作工具软件广泛应用于商标设计、标志制作、封面设计、CIS设计、产品包装造型设计、模型绘制、插图描画、时装/服饰设计......
  • 【Azure Developer】com.azure:azure-identity jar包版本从1.2.0 升级到1.12.2 版本之
    问题描述com.azure:azure-identityjar包版本从1.2.0升级到1.12.2版本之后报错,错误信息如下:Anattemptwasmadetocallamethodthatdoesnotexist.Theattemptwasmadefromthefollowinglocation:  com.azure.identity.implementation.IdentityClientBase.getConf......
  • 【Azure Developer】com.azure:azure-identity jar包版本从1.2.0 升级到1.12.2 版本之
    问题描述com.azure:azure-identityjar包版本从1.2.0升级到1.12.2版本之后报错,错误信息如下:Anattemptwasmadetocallamethodthatdoesnotexist.Theattemptwasmadefromthefollowinglocation:  com.azure.identity.implementation.IdentityClientBase.get......
  • 常见的公共 DNS 服务器地址有:谷歌 DNS:8.8.8.8 和 8.8.4.4阿里云 DNS:223.5.5.5 和 223.
    常见的公共DNS服务器地址有:谷歌DNS:8.8.8.8和8.8.4.4阿里云DNS:223.5.5.5和223.6.6.6腾讯DNS:119.29.29.29和182.254.116.116阿里公共DNS:IPv4:223.5.5.5、223.6.6.6IPv6:2400:3200::1、2400:3200:baba::1腾讯公共DNS(DNSPod):IPv4:119.29.29.29IPv6:2402:4e00::百......
  • 白骑士的JavaScript教学JavaScript语法基础篇之运算符与表达式 2.2.4 逻辑运算符
            逻辑运算符是用于布尔逻辑运算的符号,它们常用于控制流程和条件判断,帮助程序员编写更复杂和更动态的条件语句。在JavaScript中,主要的逻辑运算符包括逻辑与(‘&&‘)、逻辑或(‘||‘)、逻辑非(‘!‘)以及一些其他特定场景的运算符。逻辑运算符用于将多个布尔值或表达式......
  • 白骑士的JavaScript教学JavaScript语法基础篇之运算符与表达式 2.2.5 条件运算符(三元
            条件运算符,也称为三元运算符,是JavaScript中唯一的三目运算符,它提供了一种简洁的方式来编写条件判断和赋值语句。通过使用条件运算符,你可以在一行代码中实现简单的条件判断,从而让代码更加紧凑和易读。条件运算符        条件运算符由三个部分组成:条件......
  • Delphi 12.2 新增的 WebStencils 尝鲜
    WebStencils是Delphi新增的服务器端WEB控件 这个玩意怎么用,用起来有意义吗?试试才知道。以下测试的描述都是基于DelphiWebBroker这个WEB服务器端框架。最新出来的,各方面资料很少,官方也没有详细文档,只能自己摸索。网上我能够搜到的相关资料:corneliusdavid/webste......
  • [使用目前最新版]HybridCLR6.9.0+YooAsset2.2.4实现纯C# Unity热更新方案 (一)
    1.前言什么是热更新游戏或者软件更新时,无需重新下载客户端进行安装,而是在应用程序启动的情况下,在内部进行资源或者代码更新Unity目前常用热更新解决方案HybridCLR,Xlua,ILRuntime等Unity目前常用资源管理解决方案AssetBundles,Addressable,YooAsset等在这里我们采用HybridCLR......
  • 哔咔漫画最新版2024下载官网版-哔咔漫画2024最新版本永久免费v2.2.1.3-百步下载
    哔咔漫画简介:在当今这个数字化日益发展的时代,二次元文化已经成为许多年轻人的精神食粮之一。哔咔漫画App,作为一款集成了大量正版漫画资源的移动应用,凭借其丰富的内容、优质的用户体验和便捷的操作方式,迅速成为了漫画爱好者们的首选平台。本文将带你深入了解哔咔漫画App的魅力所在......