递归蛮力解决方案
def sliding_triangle(triangle, row = 0, index = 0):
if row >= len(triangle) or index >= len(triangle[row]):
return 0 # row or index out of bounds
# Add parent value to max of child triangles
return triangle[row][index] + max(sliding_triangle(triangle, row+1, index), sliding_triangle(triangle, row+1, index+1))
测试
print(sliding_triangle([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]))
# Output: 23
print(sliding_triangle([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]))
# Output: 1074
,但是,蛮力进近时间在 larges数据集
优化解决方案
将记忆应用于蛮力解决方案。
- 使用缓存来避免反复求解父母的子路径
code
def sliding_triangle(triangle):
' Wrapper setup function '
def sliding_triangle_(row, index):
' Memoized function which does the calcs'
if row >= len(triangle) or index >= len(triangle[row]):
return 0
if not (row, index) in cache:
# Update cache
cache[(row, index)] = (triangle[row][index] +
max(sliding_triangle_(row+1, index),
sliding_triangle_(row+1, index+1)))
return cache[(row, index)]
cache = {} # init cache
return sliding_triangle_(0, 0) # calcuate starting from top most node
测试
- 与简单测试用例的蛮力解决方案相同的结果
- 在大型数据集上工作IE https://projecteuler.net/project/resources/p067_triangle.txt.txt
查找并显示最佳路径*
- 修改野蛮力量返回路径
- 显示三角形的路径在三角形
code 中突出显示路径
####### Main function
def sliding_triangle_path(triangle, row = 0, index = 0, path = None):
'''
Finds highest scoring path (using brute force)
'''
if path is None:
path = [(0, 0)] # Init path with top most triangle node
if row >= len(triangle) or index >= len(triangle[row]):
path.pop() # drop last item since place out of bounds
return path
# Select best path of child nodes
path_ = max(sliding_triangle_path(triangle, row+1, index, path + [(row+1, index)]),
sliding_triangle_path(triangle, row+1, index+1, path + [(row+1, index+1)]),
key = lambda p: score(triangle, p))
return path_
####### Utils
def getter(x, args):
'''
Gets element of multidimensional array using tuple as index
Source (Modified): https://stackoverflow.com/questions/40258083/recursive-itemgetter-for-python
'''
try:
for k in args:
x = x[k]
return x
except IndexError:
return 0
def score(tri, path):
' Score for a path through triangle tri '
return sum(getter(tri, t) for t in path)
def colored(r, g, b, text):
'''
Use rgb code to color text'
Source: https://www.codegrepper.com/code-examples/python/how+to+print+highlighted+text+in+python
'''
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
def highlight_path(triangle, path):
' Created string that highlight path in red through triangle'
result = "" # output string
for p in path: # Looop over path tuples
row, index = p
values = triangle[row] # corresponding values in row 'row' of triangle
# Color in red path value at index, other values are in black (color using rgb)
row_str = ' '.join([colored(255, 0, 0, str(v)) if i == index else colored(0, 0, 0, str(v)) for i, v in enumerate(values)])
result += row_str + '\n'
return result
test
# Test
triangle = ([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
])
path = sliding_triangle_path(triangle)
print(f'Score: {score(tri, path)}')
print(f"Path\n {'->'.join(map(str,path))}")
print(f'Highlighted path\n {highlight_path(tri, path)}')
输出
Score: 1074
Path
(0, 0)->(1, 1)->(2, 2)->(3, 2)->(4, 2)->(5, 3)->(6, 3)->(7, 3)->(8, 4)->(9, 5)->(10, 6)->(11, 7)->(12, 8)->(13, 8)->(14, 9)
这是一个在MySQL 5.7上解决的毛茸茸的问题。这是一种方法:
SELECT s1.section, s1.sub_section, s1.category
FROM
(
SELECT section, sub_section, category, COUNT(*) AS cnt
FROM yourTable
GROUP BY section, sub_section, category
) s1
INNER JOIN
(
SELECT section, sub_section, MAX(cnt) AS max_cnt
FROM
(
SELECT section, sub_section, category, COUNT(*) AS cnt
FROM yourTable
GROUP BY section, sub_section, category
) t
GROUP BY section, sub_section
) s2
ON s2.section = s1.section AND
s2.sub_section = s1.sub_section AND
s1.cnt = s2.max_cnt
ORDER BY s1.section, s1.sub_section, s1.category;
这是一个运行
您是否听说过 object.entries
, object.values
, object.keys.keys
和 in
and 对于
循环?
const data = {
"channel_count": "1",
"channels": [
{
"logo": "default.png",
"name": "Default Channel",
"token": "default"
}
],
"messages": [
{
"2022-07-04": [
{
"body": "Body",
"title": "Title"
},
]
},
{
"2022-07-01": [
{
"body": "Body",
"title": "Title"
}
]
}
]
}
console.log(data.messages.flatMap(e => Object.entries(e)))
您不能将元素添加到尚不存在的索引中。通常,正如Japhei所说,您只能将元素添加到索引较小或等于阵列长度。这意味着,如果您的ArrayList仍然为空,则只能在索引0上添加元素,或者不指定索引(只需将其添加到末端)。
您想做的是用空元素初始化arraylist。通常,我使用毫无意义的值(例如0或-1)作为整数或空字符串,具体取决于数组类型(或无效元素),然后稍后将它们填充。
但是,如果您知道自己有多少个元素,或者需要什么数尺寸,为什么不使用普通数组呢?那将是正确的方法。
我首选的方法是用 ecmascript模块 。
您可以将每个功能都放入单独的文件中。您可以将文件命名为您喜欢的每个文件,但是我通常在包含的函数之后将它们命名。对于Web,我将给文件一个 .js
文件扩展名。在节点中,我会给它一个 .mjs
扩展名。
在每个文件中,prepend export export 这样的功能:
export function funcName()
{
}
然后从主代码文件中,您可以 import> import 您的函数您从这些独立文件中的函数
import { funcName } from "./fileName.mjs";
之后,您可以将函数像在主代码文件中声明一样(因为现在已导入)。
在映射中添加一个日期:
"lastasseceddate": {
"type": "date"
}
当然,每次访问文档时,您都必须对其进行更新。显然,如果您同时连接了许多更新 /用户,则可能会遇到一些麻烦。不要忘记检查您的“刷新”设置是否可以,您也可以考虑在任何更新后也强制刷新。
要检索文档,只需按以下日期字段(DESC)进行排序。
"sort": [
{
"lastasseceddate": {
"order": "desc"
}
}
]
如果您的用户在每次访问它时修改文档,则可以考虑使用Collape( https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html )
注意:
如果仅需要保留X个最后访问的文档(让S的最后5个),最好的解决方案是将ES文档保存在应用程序端的静态列表中。
在使用字符串属性时,使用
window["MyNamespace"] = window["MyNamespace"] || {};
应该是正确的,但是如果您确实想拥有一个分离的窗口并组织了代码,则可以扩展窗口对象:
interface MyNamespacedWindow extends Window {
MyNamespace: object;
}
declare var window: MyNamespacedWindow;
要么使用。eq()它将从其索引返回元素或使用CSS选择器像:nth-child()。
console.log($('.test').eq(3).text());
console.log($('.test:nth-child(4)').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="test">div 1</div>
<div class="test">div 2</div>
<div class="test">div 3</div>
<div class="test">div 4</div>
</div>
在这里,您有一个带有虚拟数据的示例,并使用 geom_rec
您可以选择要用某种颜色填充的背景的那一部分,更改 xmin
和 xmax < /代码>。
library(tidyverse)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# Plot
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
geom_rect(data=NULL,aes(xmin=0.25,xmax=1.25,ymin=-Inf,ymax=Inf),
fill="lightgreen", alpha=0.1) +
geom_rect(data=NULL,aes(xmin=1.25,xmax=2.25,ymin=-Inf,ymax=Inf),
fill="red", alpha=0.1) +
geom_rect(data=NULL,aes(xmin=2.25,xmax=3.25,ymin=-Inf,ymax=Inf),
fill="lightblue", alpha=0.1) +
geom_rect(data=NULL,aes(xmin=3.25,xmax=4.25,ymin=-Inf,ymax=Inf),
fill="yellow", alpha=0.1) +
geom_errorbar(aes(x=name, ymin=value-sd, ymax=value+sd),
width=0.4, colour="orange", alpha=0.9, size=1.3)
今天的表现
今天27.12.2019我在
结论
-
str.replace(/abc/g,'');
( c )是所有字符串的良好跨浏览器快速解决方案。 - 基于
split-join
( a,b )或替换
( c,d )的解决方案是 - 基于快速解决方案的()( e,f,g,h )的速度很慢 - 通常,小字符串慢了4倍,大约3000次(
- !解决方案( ra,rb )很慢,不适用于长字符串,
我还创建了自己的解决方案。看来目前是做问题作业的最短的:
str.split`abc`.join``
str = "Test abc test test abc test test test abc test test abc";
str = str.split`abc`.join``
console.log(str);
详细信息
测试是在Chrome 79.0,Safari 13.0.4和Firefox 71.0(64位)上进行的。测试 RA
和 RB
使用递归。结果
短字符串 - 55个字符
可以在计算机上运行测试在这里。 Chrome的结果:
长字符串:275 000个字符
递归解决方案 ra 和 rb 给出
连击:最大呼叫堆栈大小超过
1M字符的最大呼叫堆栈大小,甚至可以打破Chrome
我尝试为其他解决方案执行1M字符的测试,但是 e,f,g,g,h 都这样做浏览器要求我打破脚本的很多时间,所以我将测试字符串缩小到275K字符。您可以在计算机上运行测试在这里。 Chrome
测试中使用的代码
var t="Test abc test test abc test test test abc test test abc"; // .repeat(5000)
var log = (version,result) => console.log(`${version}: ${result}`);
function A(str) {
return str.split('abc').join('');
}
function B(str) {
return str.split`abc`.join``; // my proposition
}
function C(str) {
return str.replace(/abc/g, '');
}
function D(str) {
return str.replace(new RegExp("abc", "g"), '');
}
function E(str) {
while (str.indexOf('abc') !== -1) { str = str.replace('abc', ''); }
return str;
}
function F(str) {
while (str.indexOf('abc') !== -1) { str = str.replace(/abc/, ''); }
return str;
}
function G(str) {
while(str.includes("abc")) { str = str.replace('abc', ''); }
return str;
}
// src: https://stackoverflow.com/a/56989553/860099
function H(str)
{
let i = -1
let find = 'abc';
let newToken = '';
if (!str)
{
if ((str == null) && (find == null)) return newToken;
return str;
}
while ((
i = str.indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
}
return str;
}
// src: https://stackoverflow.com/a/22870785/860099
function RA(string, prevstring) {
var omit = 'abc';
var place = '';
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return RA(prevstring, string)
}
// src: https://stackoverflow.com/a/26107132/860099
function RB(str) {
var find = 'abc';
var replace = '';
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + RB(st2, find, replace);
}
}
return str;
}
log('A ', A(t));
log('B ', B(t));
log('C ', C(t));
log('D ', D(t));
log('E ', E(t));
log('F ', F(t));
log('G ', G(t));
log('H ', H(t));
log('RA', RA(t)); // use reccurence
log('RB', RB(t)); // use reccurence
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>
您可以为此purporse使用 wp_kses
。使用 WP_KSES_ALLOD_HTML
filter添加 img
元素的过滤器。
在您的functions.php中。
function theme_slug_kses_allowed_html($tags, $context) {
switch($context) {
case 'no-images':
$tags = wp_kses_allowed_html('post');
unset( $tags['img'] );
return $tags;
default:
return $tags;
}
}
add_filter( 'wp_kses_allowed_html', 'theme_slug_kses_allowed_html', 10, 2);
然后在index.php中。
echo wp_kses( get_the_content(), 'no-images' );
定义函数 f
中的比较,然后通过 Outs
, rowsums
是您想要的。
f <- \(x, y) df1[x, 1] >= df2[y, 2] & df1[x, 1] <= df2[y, 3]
cbind(df1, number=rowSums(outer(1:nrow(df1), 1:nrow(df2), f)))
# dates number
# 1 2020-01-01 2
# 2 2020-01-02 2
# 3 2020-01-03 1
# 4 2020-01-04 0
# 5 2020-01-05 1
# 6 2020-01-06 1
# 7 2020-01-07 1
# 8 2020-01-08 1
# 9 2020-01-09 1
# 10 2020-01-10 2
鉴于新的症状(崩溃是从CMDNext返回之后),播放处理程序返回后的队列在上运行:
说明:启动另一个音频显然是 disposes 。原始代码启动了另一个音频,然后处理程序结束,然后返回到该音频的播放事件处理器。在该处置的音频上可以访问一些东西。因此处置了例外。
以上代码将
cmdnextClicked
调用到Mainthread队列,然后立即返回到该音频的播放。因此,在要求下一个音频之前,它有机会完成。Given the new symptom (crash happens after return from cmdNext), queue to run after PlaybackEnded handler returns:
EXPLANATION: Starting another audio apparently disposes the previous audio. Original code started another audio, then handler ends, and returns to that audio's PlaybackEnded event processor. Something is accessed on that disposed audio. Thus the disposed Exception.
The above code puts the
cmdNextClicked
call on to MainThread's queue, then immediately returns to that audio's PlaybackEnded. Which thus has a chance to finish, before the next audio is asked for.音频播放器会自动处置