我在Ipython笔记本中编写了下面的代码来生成由参数a控制的sigmoid函数,参数a定义了sigmoid中心的位置,b定义了它的宽度:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x,a,b):
#sigmoid function with parameters a = center; b = width
s= 1/(1+np.exp(-(x-a)/b))
return 100.0*(s-min(s))/(max(s)-min(s)) # normalize sigmoid to 0-100
x = np.linspace(0,10,256)
sigm = sigmoid(x, a=5, b=1)
fig = plt.figure(figsize=(24,6))
ax1 = fig.add_subplot(2, 1, 1)
ax1.set_xticks([])
ax1.set_xticks([])
plt.plot(x,sigm,lw=2,color='black')
plt.xlim(x.min(), x.max())
Run Code Online (Sandbox Code Playgroud)
我想为参数a和b添加交互性,所以我重新编写了如下函数:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from IPython.html.widgets import interactive
from IPython.display import display
def sigmoid_demo(a=5,b=1):
x = np.linspace(0,10,256)
s = 1/(1+np.exp(-(x-a)/(b+0.1))) …Run Code Online (Sandbox Code Playgroud) 我为此目的编写了一个函数:
matplotlib图形,但不显示它numpy数组对于类似于第 1-2 点或第 4 点的任务,有很多问题和答案;对我来说,自动化第 5 点也很重要。因此,我首先将 @joe-kington 的答案和 @matehat 的答案和评论中的部分结合起来,并进行了一些小的修改,我得到了:
def mk_cmapped_data(data, mpl_cmap_name):
# This is to define figure & ouptput dimensions from input
r, c = data.shape
dpi = 72
w = round(c/dpi, 2)
h = round(r/dpi, 2)
# This part modified from @matehat's SO answer:
# /sf/answers/575322121/
fig = plt.figure(frameon=False)
fig.set_size_inches((w, h))
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
plt.set_cmap(mpl_cmap_name)
ax.imshow(data, …Run Code Online (Sandbox Code Playgroud) 我正在编写来自codingbat.com的以下Python列表练习:
给定一个int数组,返回数组中前两个元素的总和.如果数组长度小于2,则只需总结存在的元素,如果数组长度为0,则返回0.示例:
Run Code Online (Sandbox Code Playgroud)sum2([1, 2, 3]) ? 3 sum2([1, 1]) ? 2 sum2([1, 1, 1, 1]) ? 2
我的解决方案有效:
def sum2(nums):
if len(nums)>=2:
return nums[0] + nums[1]
elif len(nums)==1:
return nums[0]
return 0
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有任何方法可以用更少的条件语句来解决问题.
我正在进行一项python 练习,询问:
# Return True if the string "cat" and "dog" appear the same number of
# times in the given string.
# cat_dog('catdog') ? True
# cat_dog('catcat') ? False
# cat_dog('1cat1cadodog') ? True
Run Code Online (Sandbox Code Playgroud)
这是我目前的代码:
def cat_dog(str):
c=0
d=0
for i in range(len(str)-2):
if str[i:i+3]=="cat":
c=+1
if str[i:i+3]=="dog":
d=+1
return (c-d)==0.0
Run Code Online (Sandbox Code Playgroud)
我看着它,我认为它应该工作,但它失败了一些测试,这告诉我,我不理解Python逻辑如何工作.关于为什么我的解决方案不起作用的任何解释都会很棒.这些都是测试结果:
cat_dog('catdog') ? True True OK
cat_dog('catcat') ? False False OK
cat_dog('1cat1cadodog') ? True True OK
cat_dog('catxxdogxxxdog') ? False True X
cat_dog('catxdogxdogxcat') ? True True OK
cat_dog('catxdogxdogxca') ? …Run Code Online (Sandbox Code Playgroud) python ×4
arrays ×1
colors ×1
for-loop ×1
if-statement ×1
interactive ×1
list ×1
matplotlib ×1
numpy ×1
slider ×1
sum ×1
widget ×1