告诉我我必须做多少数学问题!


36

我的老师总是给我做作业中最复杂的数学问题。像:pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even。我想提前知道有多少时间留给我的家庭作业,但我不想弄清楚所有这些。这就是为什么要为我编程的任务。

技术指标

  • 您将得到一个字符串,详细说明我必须以args,stdio等形式完成的问题。
  • 它们将以逗号分隔(可能comma-space分隔)
  • 它将仅以数字形式包含单个问题(例如79
  • 和形式的范围17-18(同样,您必须处理可选空格)
  • 范围包括两端
  • 该范围可以选择加odd或后缀even,您必须考虑这些范围。
  • 一组范围/页面将以格式的页码开头pg. 545:,再次必须处理可选的空格。您可以放心地忽略这些,因为您需要在所有页面上都解决问题
  • 文本可以大写或小写,但不能同时使用。
  • Return,stdout等我必须做的家庭作业的数量。
  • 由于这是,因此以字节为单位的最短代码将获胜!

测试用例

pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even   ->    27
pg. 34: 1                                                    ->    1
PG. 565: 2-5,PG.345:7                                        ->    5
pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80                ->    70
pg.492: 2-4 odd,7-9 even                                     ->    2

12
教授能给你一个范围2-4 odd吗?对于更简单的方法,似乎会引起一些问题。
比约恩·林奎斯特

1
^根据当前的问题陈述,我认为这应该是一个测试案例。
mbomb007

2
应该有这个测试用例:pg.492: 2-4 odd,7-9 even -> 2
mbomb007

2
范围可以重叠吗?例如22-26,25-30
Reto Koradi

1
@RetoKoradi号
Maltysen

Answers:


15

CJam,61 58 51 48 46 43 41 38字节

leuS-',/{':/W>:~_2*2<~z),>1f&\,5--~}%,

CJam解释器中验证测试用例。

怎么运行的

leuS-      e# Read a line from STDIN, convert to uppercase and remove spaces.
',/        e# Split at commas.
{          e# For each chunk:
  ':/W>    e#   Split at colons and only keep the last chunk.
  :~       e#   Evaluate the string inside the array.
  _2*      e#   Copy the array, repeated twice.
  2<       e#   Keep only the first two elements.

           e#   In all possible cases, the array now contains exactly two
           e#   integers, which are equal in case of a single problem.

  ~        e#   Dump the array on the stack.
  z),      e#   Push [0 ... -N], where N is the second integer.
  >        e#   Discard the first M elements, where M is the first integer.
  1f&      e#   Replace each element by its parity.
  \,       e#   Push L, the length of the original array.

           e#   EVEN and ODD all push elements, so L is 1 for single problems,
           e#   2 for simple ranges, 5 for odd ranges and 6 for even ranges.

  5--      e#   Discard all elements equal to L - 5 from the array of parities.

           e#   This removes 0's for odd ranges, 1's for even ranges, -3's for
           e#   other ranges and -4's for single problems, thus counting only
           e#   problems of the desired parities.

  ~        e#   Dump the resulting array on the stack.
}%         e# Collect the results in an array.
,          e# Compute its length.

这适用于最新的测试用例吗?
mbomb007

是的 我已经在链接中添加了最新的测试用例。
丹尼斯

10

Perl-47字节

#!perl -p054
{map$\+=($_%2x9^lc$')!~T,$&..$'*/\d+ ?-/}}{

修改以通过新的测试用例。


原版的

Perl-36字节

#!perl -p054
$\+=/\d+ ?-/*($'-$&>>/o|e/i)+1}{

将shebang计为4,输入来自stdin。


样品用量

$ echo pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even | perl math-problems.pl
27

$ echo pg. 34: 1 | perl math-problems.pl
1

$ echo PG. 565: 2-5,PG.345:7 | perl math-problems.pl
5

$ echo pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80 | perl math-problems.pl
70

注意事项

对于偶数/奇数范围,期望至少一个端点与范围的奇偶性匹配。例如,11-19 odd11-20 odd,和10-19 odd将所有被正确地计为5,但是10-20 odd将过算作6。


这是如何工作的pg. 20: 13-15 even?还是pg. 20: 13-14 even
并不是查尔斯(Charles)

1
*比短一个字符&&,可以轻松改进:$\+=/\d+ ?-/*($'-$&>>/o|e/i)+1for@F}{
Grimmy 2015年

1
伙计,这很聪明!除非我缺少任何东西,否则您应该可以消除lc=~
丹尼斯

1
我掌握了这一T^部分,但是以某种方式错过了这一点,从而lc改变了情况$'。预先考虑lc$'本来稍短。对于任何一种方法,这仍然应该起作用:lc$'!~(T^lc$_%2)($_%2x9^lc$')!~T
Dennis

1
@Dennis对于以前的版本,将需要括号。!~T是个天才,谢谢!
primo

6

Python 2中,259个 253 249 239字节

在这里尝试

这可能仍然可以打更多。

编辑:修复了导致我无法正常使用的错误2-4 even。然后对该修复程序进行调整。该修复程序为我节省了四个字节!

编辑:现在使用input()+2字节作为用户必须用输入包围的两个引号。

import re
c=0
for x in re.sub(r'..\..*?:','',input()).replace(' ','').split(','):
 y=x.split('-')
 if len(y)<2:c+=1
 else:
    a,b=y[0],y[1];d=int(re.sub('[A-z]','',b))-int(a)+1
    if b[-1]>':':d=d/2+d%2*(int(a)%2==ord(b[-3])%2)
    c+=d
print c

少打高尔夫球(带注释!:D):

希望这些评论对您有所帮助。我仍然不确定我是否正确解释了最后一条复杂的线。

import re
def f(s):
    c=0
    l=re.sub(r'..\..*?:','',s).replace(' ','').split(',')   # remove pg #'s and split
    for x in l:
        y=x.split('-')
        if len(y)<2:                                # if not a range of numbers
            c+=1
        else:
            a,b=y[0],y[1]                           # first and second numbers in range
            d=int(re.sub('[A-z]','',b))-int(a)+1    # number of pages
            if b[-1]>':':                           # if last character is not a digit
                # half the range
                # plus 1 if odd # of pages, but only if first and last numbers in the range
                #       are the same parity
                # ord(b[-3])%2 is 0 for even (v), 1 for odd (o)
                d=d/2+(d%2)*(int(a)%2==ord(b[-3])%2)
            c+=d
    print c

2
一件小事,由于您使用的是Python 2,因此可以将空格和制表符(每个1字节)用作不同的缩进。相关提示
FryAmTheEggman 2015年

还发现我一开始算错了。从编辑器复制选项卡会将其转换为空格。
mbomb007 2015年

通过s=raw_input()删除一些缩进,可以节省至少4个字节。

4

Pyth,43 42 44 42字节

lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\,

在线尝试:演示测试工具

我想我仍然可以砍一两个字节。

说明

lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\,  implicit: z = input string
                                    rzZ     convert z to lower-case
                                   -   d    remove all spaces from z
                                  c     \,  and split by ","
  m                                         map each part d to:
               cd\:                           split d by ":"
              e                               and only use the last part (removes page number)
             -     G                          remove all letters (removes odd/even)
            c       \-                        split by "-"
          vM                                  and evaluate all (one or two) numbers
         K                                    and store the result in K
       }hK            eK                      create the list [K[0], K[0]+1, ..., K[-1]]
    %R2                                       apply modulo 2 to each element
   -                                          and remove:
                         }\ed                   "e" in d (1 for in, 0 for not in)
                        ?    }edG               if d[-1] in "abcde...z" else
                                 Y              dummy value
 s                                            combine all the lists
l                                             print the length                                      

这适用于最新的测试用例吗?
mbomb007

@ mbomb007:是的。
丹尼斯

3

JavaScript(Spidermonkey控制台)-139

在命令行上测试更容易。

for(r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi,m=readline(z=0);f=r.exec(m);z+=!b||((p=b-a)%2||!c|a%2^/e/i.test(c))+p/(2-!c)|0)[,a,b,c]=f
print(z)

取消高尔夫:

// any number set after "pg:" or a comma
// \1 is FROM, \2 is TO, \3 is odd/even 
r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi;
m=readline();
z=0; // this is the sum.
while(f=r.exec(m)){
    [,from,to,oddEven]=f;
    if(!to) {
        z++;
    } else {
        if((to-from)%2) {
            // if to and from are not the same parity, add 1
            z++;
        } else {
            // if to and from are not the same parity...
            if(!oddEven) {
                // and we don't have a parity marker, add one
                z++;
            } else if(a%2 != /e/i.test(c)) {
                // if we do have a parity marker,
                // AND the parity of from and to matches the 
                // parity of the oddEven sign, then add 1
                z++;
            }
        }
        // then add the difference between to-from and
        // if oddEven exists, divide by two and round down
        z+=(to-from)/(oddEven?2:1)|0;
    }

}
print(z);

可以[,from,to]只是[from,to]吗?
Yytsi

1
@TuukkaX否,因为那是从中丢弃数组的第一个值r.exec,其中包含整个匹配的字符串。
Patrick Roberts

3

因子-488字节:

USING: arrays ascii kernel math math.parser math.ranges pcre sequences ;
IN: examples.golf.homework

: c ( a -- b )
    >lower "(?:[,:]|^) *(\\d+) *(?:- *(\\d+) *(e|o)?)?" findall [
        rest [ second dup string>number swap or ] map
        dup length 1 = [ drop 1 ] [
            dup length 2 = [ first2 swap - 1 + ] [
                first3 "o" = [ [a,b] [ odd? ] count ] [
                    [a,b] [ even? ] count
                ] if
            ] if
        ] if
    ] map sum ;

2

344 315 306 294 262 252 242 240

IFS=,
o(){ R=0;for ((i=$1;i<=$2;R+=i++%2));do :
done
}
e(){ q=$R;o $*;((R=q-R))
}
for c in ${1,,};do
c=${c#*:}
m=${c##* }
l=${c%-*}
l=${l// }
h=${c#*-}
[[ a< $m ]]&&h=${h% *}
h=${h// }
((R=h-l+1))
eval "${m::1} $l $h"
((t+=R))
done;echo $t

我认为我没有尽可能多地打高尔夫球,但对于第一次提交来说还不错。下面的评论版本。

IFS=, # Setup IFS for the for loops, We want to be able to split on commas

o(){ # Odd
    R=0  # Reset the R variable

    # Increments R for each odd element in the range
    # $1-$2 inclusive
    for ((i=$1;i<=$2;R+=i++%2));do
        : # Noop command
    done
}

e(){ # Even
    # Save R, it contains the total number of elements between low
    # and high
    q=$R
    # Call Odd, This will set R
    o $*
    # Set R = total number of elements in sequence - number of odd elements.
    ((R=q-R))
}

# This lowercases the firs arg. IFS causes it to split on commas.
for c in ${1,,};do
    c=${c#*:}  # Strips the page prefix if it exists
    m=${c##* }  # Capture the odd/even suffix if it exists
    l=${c%-*}  # Capture low end of a range, Strips hyphen and anything after it
    l=${l// }  # Strips spaces
    h=${c#*-}  # Capture high end of a range, Strips up to and including hyphen

    # If we have captured odd/even in m this will trigger and strip
    # it from the high range variable.
    [[ a< $m ]]&&h=${h% *}
    h=${h// }  # Strip Spaces

    # Give R a value.
    # If we are in a range it will be the number of elements in that range.
    # If we arent l and h will be equal are R will be 1
    ((R=h-l+1))

    # Call the odd or even functions if we captured one of them in m.
    # If we didnt m will contain a number and this will cause a warning
    # to stderr but it still works.
    eval "${m::1} $l $h"

    # Add R to total
    ((t+=R))
done

# Print result
echo $t

运行测试用例:

bash math.sh "pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even"
bash math.sh "pg. 34: 1"
bash math.sh "PG. 565: 2-5,PG.345:7"
bash math.sh "pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80"
bash math.sh "pg.492: 2-4 odd,7-9 even"

根据我阅读规则的方式,可以另外保存4个字节。如果总是偶数/奇数,${1,,}可以将小写更改为$1


这适用于最新的测试用例吗?
mbomb007

刚刚测试过,是的。
Daniel Wakefield

1

JavaScript(ES6),149

在Firefox中运行代码段进行测试

F=s=>s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig,(_,c,v,o,e)=>
  c=='-'?(t+=1+(o?(v-(r|1))>>1:e?(v-(-~r&~1))>>1:v-r),r=0)
  :c!='.'&&(t+=!!r,r=v)
,r=t=0)&&t+!!r

// Less golfed

U=s=>{
  var r = 0, // value, maybe range start
  t = 0; // total
  s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig, // execute function for each match
    (_ // full match, not used
     , c // separator char, match -:,.
     , v // numeric value
     , o // match first letter of ODD if present
     , e // match first letter of EVEN if present
    )=>
    {
      if (c == '-') // range end
      {
        t++; // in general, count range values as end - start + 1
        if (o) // found 'odd'
        {
          r = r | 1; // if range start is even, increment to next odd
          t += (v-r)>>1; // end - start / 2
        }
        else if (e) // found 'even'
        {
          r = (r+1) & ~1; // if range start is odd, increment to next even
          t += (v-r)>>1; // end - start / 2
        }
        else
        {
          t += v-r; // end - start
        }
        r = 0; // range start value was used
      }
      else if (c != '.') // ignore page numbers starting with '.'
      { 
        // if a range start was already saved, then it was a single value, count it
        if (r != 0) ++t;
        r = v; // save value as it counld be a range start
      }
    }
  )            
  if (r != 0) ++t; // unused, pending range start, was a single value
  return t
}

// TEST

out=x=>O.innerHTML+=x+'\n';

test=["pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even",
"pg. 34: 1", "PG. 565: 2-5,PG.345:7",
"pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80"];

test.forEach(t=>out(t + ' --> ' + F(t)))
<pre id=O></pre>


1

C ++ 226 224 222

我知道我参加聚会有点晚了,但这似乎是一个有趣的问题,而且缺少使用C族语言的条目,这让我感到困扰。

因此,这是一个不使用正则表达式或字符串替换的C ++函数,只是一些简单的数学运算:

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

Ungolfed

void f()
{
  char c;
  int o=0,i,j;
  while(cin>>c)
    c=='p'||c==80?cin.ignore(9,58):cin.unget(),
    cin>>i>>c&&c==45?
      cin>>j>>c&&(c=='e'||c=='o')?
        cin.ignore(9,44),
        c=='e'?
          i+=i&1,j+=!(j&1)
        :(i+=!(i&1),j+=j&1),
        o+=(j-i)/2
      :o+=j-i
    :0,
    ++o;
  cout<<o;
}

我没有说这是可读的,是吗?:)三元运算符是地狱。不过,我尽了最大努力来格式化它,所以我希望它至少可以有所帮助。

用法

#include <iostream>
using namespace std;

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

int main()
{
  f();
}


0

Python 2-163字节:

在这里尝试

输入必须在引号内

import re
print len(eval(re.sub('([^,]+:|) *(\d+) *-? *(\d*)(?=.(.)).*?,',r'[x for x in range(\2,\3+1 if \3.0 else \2+1)if x%2!="oe".find("\4")]+',input()+',[]')))

说明:

通用方法是将现有输入转换为有效的python,然后对此进行评估。每个逗号分隔的值都转换为一个数组,然后将它们全部附加在一起,并且长度给出最终结果。

例如,使用input 12-15 odd,19,在求值前,正则表达式替换将产生:

[x for x in range(12,15+1 if 15.0 else 12+1)if x%2!="oe".find("o")]
+[x for x in range(19,+1 if .0 else 19+1)if x%2!="oe".find("[")]
+[]

要进一步分解:

  • 15+1 if 15.0 else 12+1 该位将确保range()的第二个参数正确,具体取决于是否存在范围或给定单个值(如果\ 3为空,则\ 3.0将得出false)。
  • if x%2!="oe".find("o")根据找到的值与该范围内最后一位数字相距两个字符的值((?=.(.))在正则表达式中-在不消耗它们的情况下提前查找两个字符),可能产生三种结果:

    • x%2!="oe".find("o")评估为x % 2 != 0(仅奇数匹配)
    • x%2!="oe".find("e")评估为x % 2 != 1(仅匹配)
    • x%2!="oe".find("[")计算结果x % 2 != -1(此字符可能是多个字符,因为它与最后一位数字相距仅两个字符,但是如果要使用奇/偶,则只能为o或e)
  • 末尾看似随机的[[]是为了确保逗号分隔列表中的最后一个标记的字符与末尾数字相距两个,但也允许我们在末尾附加一些内容以耗尽末尾的“ +”否则就会落后。
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.