Stackoverflow有多少赏金?


33

任务:

您是一位了不起的程序员和Stackoverflow-answerer,您决定在Stackoverflow上悬赏所有问题。你太好了,以至于你设法在所有问题上都得到了赏识。在等待代表涌入时,您编写了一个程序,该程序找出所有这些赏金中代表的总数。

规则:



2
stackoverflow.com/?tab=featured。所有特色问题都在1页上。
Nzall 2014年

7
@NateKerkhofs并不是全部。滚动到底部。例如,当我刚加载它时,它显示472个问题中的96个。
bazzargh 2014年


@justhalf已经讨论过……
TheDoctor

Answers:


23

JavaScript- 176 133 130 108 106

function f()(t+=$("[title~=an]").text(),u=$("[rel*=x]")[0])?$("html").load(u.href,f):alert(eval(t));f(t=0)

编辑1:缩减一些选择器,并使用了?:Google Closure Compiler 的建议(通过@Sirko-谢谢)

编辑2:INITIALISE sd并初始化t0,而不是""

编辑3:意识到我实际上并不需要针对特定​​的容器,并且可以扫描整个文档,从而摆脱了一堆.find调用和一个不必要的选择器(加上保存它的变量)

编辑4:t在函数调用中推入初始化程序,以避免;(始终会被提升到顶部)并将函数压缩为一个语句(在三元语句条件内将两个语句合并为一个)以删除{}

注意:我不确定它是否在作弊,但这必须从已经指向的浏览器的控制台窗口中运行http://stackoverflow.com/questions?page=1&sort=featured。它依赖于jQuery和相应的页面链接在页面本身上可用的事实。另外,它似乎只能在Firefox中运行,而不能在IE或Chrome中运行。

输出(在发布时):

38150 (in an alert dialog)

爆炸/评论

function f()
    //concat all the bounty labels to t (they take the format "+50")
    //happens to be elements with title attribute containing word 'an'
    (t+=$("[title~=an]").text(),
    //find the "next" (has rel=next attribute) button
    u = $("[rel*=x]")[0])       
        ?
        //if there is a next button, load it, and then recurse f again
        $("html").load(u.href,f)
        :
        //else eval the 0+a+b+...+z tally and alert the result
        alert(eval(t))
//kick off the initial scrape (and simultaneously init the total tally)
f(t=0)

s=" #mainbar";d=$(s);t="";function a(){d.find(".bounty-indicator").each(function(){t+=this.innerHTML});(u=d.find("[rel=next]")[0])?d.load(u.href+s,a):alert(eval(t))}a();169-二手Google Closure编译器。
锡尔科2014年

8
选择语言和上下文时会绕开许多必填字符!(例如“ stackoverflow.com/”)我喜欢它!
AlexC 2014年

我想您应该提到这是使用jQuery插件完成的。我认为应该是.. :)
Mr_Green

Chrome抛出语法错误。用(括号打开功能主体,这真的有效吗?
thejh 2014年

@Mr_Green-我已经注意到了,但是我将其加粗了以引起更多关注……
Alconja 2014年

21

Python- 232231195183176174

使用正则表达式解析来自https://stackoverflow.com/questions?sort=featured的HTML 。

上界rangefor循环必须number of pages + 1否则代码将提高HTTPError,因为404的。每页的默认结果数是15,这是代码使用的内容(省略会?pagesize=50节省字符并且同样有效)。

感谢@Gabe提供了进一步减少字符数的技巧。

Golfed

import requests,re;print sum(sum(map(int,re.findall(r"<.*>\+(\d+)<.*>",requests.get("https://stackoverflow.com/questions?sort=featured&page=%u"%i).text)))for i in range(1,33))

输出(在发布时):

37700

未打高尔夫球

这是一个有点古板的版本,应该更容易阅读和理解。

import requests, re

print sum(
          sum(
              map( int,
                   re.findall( r"<.*>\+(\d+)<.*>",
                               requests.get( "https://stackoverflow.com/questions?sort=featured&page=%u" % i).text
                   )
              )
          ) for i in range( 1, 33 )
      )

1
您可以摆脱显式for循环并将其降至176:import urllib,re;print sum(sum(map(int,re.findall(r"<.*>\+(\d+)<.*>",urllib.urlopen("http://stackoverflow.com/questions?sort=featured&page=%u"%i).read())))for i in range(1,33))
Gabe 2014年

硬编码的上限使测试变得有些困难
Einacio


6
@Richard是的,但这是代码高尔夫,因此简洁性胜过它是否是一个“好主意”。我的意思是,在“现实生活”中,编写没有空格的可怕的单行代码也不是一个好主意……
Tim Goodman 2014年

3
@Richard解析html和从html提取是完全不同的任务。由于网站不是稳定的API,因此不能保证这种提取不会起作用。尽管Tony的代码有点过头了,所以如果有任何包含后缀数字的标签,它就会失败+。例如,问题标题可能适合该格式。
CodesInChaos 2014年

18

雷博尔- 164 133 130(139与404检查)

使用parseRebol 的子语言解析html 。检查前98页。我意识到我与python解决方案具有相同的约束-太多重复击中404错误并停止执行。感谢@rgchris进行了许多改进!更新以检查多达98页。

s: 0 repeat n 99[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]s

使用404错误检查(139):

s: 0 repeat n 99[attempt[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]]s

测试

>> s: 0 repeat n 20[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]s
== 23600

>> s: 0 repeat n 99[attempt[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]]s
Script: none Version: none Date: none
== 36050

说明

Rebol忽略空格,因此您可以选择将其全部放在一行上。PARSE有两个输入,第一个参数read join ...相当不言自明。但是,这里有一些关于语法分析方言说明的注释,使用的是更传统的缩进形式:

s: 0
repeat n 99 [
    parse read join http://stackoverflow.com/questions?sort=featured&page= n [
        ;-- match the enclosed pattern 15 times (the rule will fail politely when there are less entries)
        15 [
            ;-- seek the match position up THRU (and including) the string >+
            thru {>+}
            ;-- copy contents at the current position up TO (but not including) <
            copy x to {<}
            ;-- (Basically, run some non-dialected Rebol if this match point is reached) the do is a bit dangerous as it runs the string as code
            (s: s + do x)
        ]
    ]
]
;-- evaluator returns last value, we want the value in S
;-- (not the result of PARSE, that's a boolean on whether the end of input was reached)
s

很好...我添加了一些注释的普通格式版本,希望您不要介意!总是很高兴看到Rebol在这样的读写能力上解决了这么多问题(全部都在一个半跨平台的Apache许可的可执行文件中,但是这使REFORM之类的东西像一个酸痛的拇指一样伸出来,其他各点都很有意义,但我仍然看起来用那个词去“减少和将表格转换为表格”是很丑陋的。痴迷于霍桑,哦,您可以将SOME更改为ANY,然后
删除

哎呀,应该是133
rgchris

注意:您需要循环到更高的n值...当前有28个页面的赏金(页面大小为15)。不过不会影响您的字符数。
Alconja 2014年

感谢Alconja。在向解决方案添加任何字符之前,可以轻松浏览多达98页。今晚我必须在家中重新进行测试
johnk

11

红宝石260

require'open-uri'
require'zlib'
i=b=0
d=''
until /"has_more":f/=~d
i+=1
d=Zlib::GzipReader.new(open("http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow&page=#{i}&pagesize=100")).read
b+=d.scan(/"bounty_amount":(\d+)/).map{|x|x[0].to_i}.reduce :+
end
p b

使用Stack Exchange API。

输出(截至原始发布时间):

37200

我没有&pagesize=100在字符数中进行计数,因为没有它就可以工作,但我只是为了方便测试而添加了它。如果将其删除,它会执行相同的操作(除了它会占用更多配额并且需要更长的时间)。


不错,我只用Python达到了275
Claudiu 2014年

吃更多的配额???您应该只使用SO和SO。
John Dvorak 2014年

@JanDvorak ??? 我的意思是API配额。
门把手

1
requireS可与被替换-r命令行标记。
贾斯汀

8

Rebmu - 108 107

rtN99[parseRDrj[http://stackoverflow.com/questions?sort=featured&page=N][15[thru{>+}copyXto{<}(a+JdoX)]]]j

测试 (美国东部标准时间19:05)

>> rebmu [rtN99[parseRDrj[http://stackoverflow.com/questions?sort=featured&page=N][15[thru{>+}copyXto{<}(a+JdoX)]]]j]
Script: none Version: none Date: none
== 79200

Rebmu看起来很神秘,但是一旦掌握了它,它就很容易阅读。让我们首先取消粘贴并将其正确布置。

rt n 99 [
    parse rd rj [
        http://stackoverflow.com/questions?sort=featured&page= n
    ][
        15 [
            thru {>+}
            copy x to {<}
            (a+ j do x)
        ]
    ]
]
j

Rebmu是Rebol的方言,因此您可以在解决方案中看到相似之处。Rebmu尚无法减小每个语句的大小,但这是一种不断发展的语言。再次感谢@rgchris对我第一次尝试的改进。


ti(到整数!)比doRebmu 更安全,并且代码长度没有变化。
rgchris 2014年

6

红宝石-197

简洁版本:

require 'nokogiri'
require 'open-uri'
s=0
(1..33).each{|p|Nokogiri::HTML(open("http://stackoverflow.com/questions?page=#{p}&sort=featured")).css('.bounty-indicator').each{|b|s+=b.content.to_i}}
p s

人性化版本:

require 'nokogiri'
require 'open-uri'
s=0
(1..33).each do |p|
    Nokogiri::HTML(open("http://stackoverflow.com/questions?page=#{p}&sort=featured")).css('.bounty-indicator').each do |b|
        s += b.content.to_i
    end
end
puts s

并回答- 39700

带有脚本参数的Ruby-139

require 'nokogiri'
require 'open-uri'
s=0
(1..33).each{|p|Nokogiri::HTML(open(ARGV[0]+p.to_s)).css(ARGV[1]).each{|b|s+=b.content.to_i}}
p s

要从bash运行此命令,只需键入

ruby code_golf_stack_overflow2.rb http://stackoverflow.com/questions?sort=featured\&page= .bounty-indicator

requireS可与被替换-r命令行标记。
贾斯汀

6

PHP-121字节

<?for(;preg_filter('/>\+(\d+)/e','$t+=\1',@file('http://stackoverflow.com/questions?sort=featured&page='.++$n)););echo$t;

使用正则表达式“ eval”修饰符,以避免使用array_sum或类似用法。似乎是有效条目中最短的解决方案。


4
ePHP 5.5起,该修饰符已被弃用,但它仍然对高尔夫很有用。
法布里西奥磨砂

6

PHP,134131,127

while($q=array_sum(preg_filter('#.*>\+#',0,file("http://stackoverflow.com/questions?sort=featured&page=".++$n))))$s+=$q;echo$s;

将遍历所有页面,pagesize未设置为节省字节,因此需要更多GETs。

非常非常肮脏,但是...利用了PHP“缺陷”!

  • 之后没有空格 echo
  • while 停止作业
  • RegEx替换后输出的是以赏金金额开头的字符串
  • array_sum() 累加字符串
  • $n并且$s已初始化,但从零开始是等效的。从零开始
  • 等等...

5

重击206

可能的优化,太懒了

s=0;for i in `seq 1 11`;do for j in `wget -q -O - "http://stackoverflow.com/questions?pagesize=50&sort=featured&page=$i" | grep -o -E "bounty worth [0-9]*" | grep -o -E "[0-9]*"`;do s=$(($s+$j));done;done;echo $s

结果:

39450

4
我可能是错的,但是如果进行一些质量优化,这看起来可能会短。
rickcnagy 2014年

seq 1 11可以减少到seq 11
fedorqui 2014年

您应该能够摆脱管道周围的空间以节省四个字符,并且可以肯定地将这两个抓手合并为一个(您是说“ [0-9] +”吗?)。
Desty

同样是“ grep -o -E” =>“ egrep -o”。
Desty

您可以更改:“ egrep -o'[0-9] +'” =>“ cut -d''
f3

5

Javascript- 129 119 110 107个字符

编辑:无效的答案!这仅处理“热门话题”,其中只有一小部分。Alconja的答案更有效。

s="#mainbar";t="";eval("$(s).find('.bounty-indicator').each(function(){t+=this.innerHTML});alert(eval(t))")

在控制台窗口中的https://stackoverflow.com/?tab=feature上执行。基于Alconja的解决方案。

通过删除不必要的空白,使它更加有效。

使用eval删除函数调用,清除另外9个字符。

清除了一些不必要的空白。


3

Java,540个字符

警告:活跃赏金数量约为470。此代码将多次访问stackoverflow上的页面。可能会因为发出如此多的数据请求而惹恼您。

import java.io.*;import java.net.*;public class B{public static void main(String[]A){String u="http://stackoverflow.com/questions",d;Long i,s=i=0L,n=i.parseLong(o(u).replaceAll("^.*b.>(\\d+).*$","$1"));while(i++<n){d=o(u+"?pagesize=1&sort=featured&page="+n).replaceAll("^.*ion.>.(\\d+).*$","$1");s+=d.matches(".*\\D.*")?0:n.parseLong(d);}System.out.print(s);}static String o(String s){String d="";try{BufferedReader r=new BufferedReader(new InputStreamReader(new URL(s).openStream()));while((s=r.readLine())!=null)d+=s;}finally{return d;}}}

我的输出是23400,但是当我运行@TonyH的代码时,我得到了37550。坏消息。

漂亮的代码:

import java.io.*;
import java.net.*;

public class StackOverflowBounty {

    public static void main(String[] args) {
        String u = "http://stackoverflow.com/questions", d;
        Long i, s = i = 0L, n = i.parseLong(o(u).replaceAll("^.*b.>(\\d+).*$", "$1"));
        while (i++ < n) {
            d = o(u + "?pagesize=1&sort=featured&page=" + n).replaceAll("^.*ion.>.(\\d+).*$", "$1");
            s += d.matches(".*\\D.*") ? 0 : n.parseLong(d);
        }
        System.out.print(s);
    }

    static String o(String s) {
        String d = "";
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(new URL(s).openStream()));
            while ((s = r.readLine()) != null) {
                d += s;
            }
        } finally {
            return d;
        }
    }
}

它的工作方式很简单。它从url读取http://stackoverflow.com/questions"以确定有赏金的问题的数目(注意:如果数目增加,程序将失败,但是如果数目减少,则可以正常工作)。它使用正则表达式搜索该数字b.>(\\d+)。迄今为止,这在所有测试中均有效,但是如果有人提出了与该正则表达式匹配的问题,则可能无法正常工作。

然后,我们打开网址http://stackoverflow.com/questions?pagesize=1&sort=featured&page=+current question #。换句话说,我们为每个特色问题打开一个新页面,并将问题的数目强制为1,因此我们将全部解决。信誉部分将始终匹配ion.>.(\\d+),因此我用它来查找它。我将操作分为两部分,以便可以廉价地检查问题的数量是否减少(即返回的字符串不是整数)。

然后,我们将所有信誉汇总并打印出来。

在我的机器上运行大约需要3分20秒。


有谁知道为什么打印的号码不正确?


pagesize = 100给出较大的数字。我认为发生了一些奇怪的事情,因为您传递的是pagesize = 1。在我的回答中,如果我未指定“ pagesize”,则结果接近您的数字。
jzm 2014年

@malik是的,我意识到我“误读了”您的评论,所以我删除了我的:-)。pagesize = 100的行为就像pagesize = 50。您是说您以pagesize = 100运行了我的代码吗?
贾斯丁

2

C#-407

class B{void Main(string[] a){var o=0;for(int i=1;i<11;i++){var r=((System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)))).GetResponse();if(r.ContentLength>0){using(var s=new StreamReader(r.GetResponseStream()))foreach(Match m in Regex.Matches(s.ReadToEnd(),"bounty worth (.+?) "))o+=int.Parse(m.Value.Substring(m.Value.IndexOf('h')+2));}}Console.Write(o);}}

使用Stackoverflow.com。除没有Gzip解压缩和不同的正则表达式外,其余与以下相同。

测试

> prog.exe http://stackoverflow.com/questions?pagesize=50&sort=featured
38150

奇怪的是,获得了与下面不同的值。


C#-496

这将使用api.stackexchange和json。

using System.IO.Compression;class B{void Main(string[] a){var o=0;for(int i=1;i<11;i++){var r=((System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)))).GetResponse();if(r.ContentLength>0)using(var s=new StreamReader(new GZipStream(r.GetResponseStream(),CompressionMode.Decompress)))foreach(Match m in Regex.Matches(s.ReadToEnd(),@"bounty_amount"":(.+?),"))o+=int.Parse(m.Value.Substring(m.Value.IndexOf(':')+1).Replace(",",""));}Console.Write(o);}}

未缩小:

using System.IO.Compression;

class B
{
    void Main(string[] a)
    {
        var o = 0;
        for (int i=1; i<11; i++) {
            var w = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)));
            if(w.GetResponse().ContentLength > 0)
                using(var s = new StreamReader(new GZipStream(w.GetResponse().GetResponseStream(),CompressionMode.Decompress)))
                    foreach(Match m in Regex.Matches(s.ReadToEnd(), @"bounty_amount"":(.+?),"))
                        o += int.Parse(m.Value.Substring(m.Value.IndexOf(':')+1).Replace(",", ""));
        }
        Console.Write(o);
    }
}

测试

默认页面大小:

> prog.exe http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow
25300

页面大小= 100:

> prog.exe "http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow&pagesize=100"
37400

2

jQuery 191

i=0;function f(p){$.get('//api.stackexchange.com/2.2/questions/featured?site=stackoverflow&page='+p,function(d){for(x in d.items)i+=d.items[x].bounty_amount;d.has_more?f(p+1):alert(i)})};f(1)

它可以在stackexchange(以及许多其他站点)中的任何地方工作,而无需像@ Alconja / @ NateKerkhofs那样位于特定页面中


jQuery是一个库,不是一种语言。不知道它是否有效...
rickcnagy 2014年

@ br1ckb0t如果愿意,可以将其作为javascript。无论如何,jQuery已经在$
stackexchange

是的,这很有道理!好的代码。
rickcnagy 2014年

2

PHP-139

打高尔夫球:

<?php
$a=file_get_contents('http://stackoverflow.com/?tab=featured');preg_match_all('/n">\+([0-9]+)<\/div>/',$a,$r);echo array_sum($r[1]);

未打高尔夫球-147

简单file_get_contents/ preg_match/array_sum

<?php
$a = file_get_contents('http://stackoverflow.com/?tab=featured');
preg_match_all('/n">\+([0-9]+)<\/div>/', $a, $r);
echo array_sum($r[1]);

测试:

php run.php

10250


2

重击174

基于https://codegolf.stackexchange.com/a/25180/7664

s=0;for i in {1..11};do for j in `wget -qO- "stackoverflow.com/questions?pagesize=50&sort=featured&page=$i"|cut -d' ' -f18|egrep '^[0-9]+$'`;do s=$(($s+$j));done;done;echo $s

您可以摆脱pagesize=50&而只是循环更多(我认为默认页面大小为15)。
Alconja 2014年

@Alconja Hmm,对,所以我可以将其降低到162 ...,但这只是对服务器发送更多请求垃圾邮件的不利影响。
thejh 2014年

2

Python(174个字符):

扩展上面的python答案(没有足够的业力来评论):

import requests,re;print sum(sum(map(int,re.findall(r"<.*>\+(\d+)<.*>",requests.get("http://stackoverflow.com/questions?sort=featured&page=%u"%i).text)))for i in range(1,33))

代替urllib的请求减少了2个字符。


1

红宝石(176个字符):

按照Tony H.使用硬编码页码的示例,这是我得到的:

require'open-uri';b=0;(1..29).each{|i|d=open("http://stackoverflow.com/questions?sort=featured&page=#{i}").read;b+=d.scan(/<.*>\+(\d+)<.*>/).map{|x|x[0].to_i}.reduce 0,:+};p b

在撰写本文时给了我35300。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.