【问题标题】:Digit Occurence of a Number in PerlPerl中数字的出现次数
【发布时间】:2012-10-18 15:52:29
【问题描述】:

问题是: 计算每个数字在给定输入中出现的次数的 Perl 脚本。打印每个数字的总数和所有总数的总和。

脚本是:

#!/usr/bin/perl

my $str = '654768687698579870333';

if ($str =~ /(.*)[^a]+/) {

    my $substr = $1;
    my %counts;

    $counts{$_}++ for $substr =~ /./g;

    print "The count each digit appears is: \n";
    print "'$_' - $counts{$_}\n" foreach sort keys %counts;
    my $sum = 0;
    $sum += $counts{$_} foreach keys %counts;
    print "The sum of all the totals is $sum\n";    
}

我得到的输出是:

The count each digit appears is:
'0' - 1
'3' - 2
'4' - 1
'5' - 2
'6' - 4
'7' - 4
'8' - 4
'9' - 2
The sum of all the totals is 20

但我应该得到的输出是:

The count each digit appears is:
'0' - 1
'3' - 3
'4' - 1
'5' - 2
'6' - 4
'7' - 4
'8' - 4
'9' - 2
The sum of all the totals is 21

我哪里错了?请帮忙。提前致谢

【问题讨论】:

    标签: perl


    【解决方案1】:

    您不是检查整个字符串 ($str),而是检查除最后​​一个字符之外的所有字符 ($substr)。

    if ($str =~ /(.*)[^a]+/) {
        my $substr = $1;
    
        my %counts;
        $counts{$_}++ for $substr =~ /./g;
    

    应该是

    my %counts;
    ++$counts{$_} for $str =~ /[0-9]/g;
    

    【讨论】:

      【解决方案2】:
      #! /usr/bin/env perl
      use strict;
      use warnings;
      use Data::Dumper;
      
      my $numbers = "654768687698579870333";
      $numbers =~ s{(\d)}{$1,}xmsg;
      
      my %counts;
      map {$counts{$_}++} split (/,/, $numbers);
      
      print Dumper(\%counts);
      

      输出

      $VAR1 = {
            '6' => 4,
            '3' => 3,
            '7' => 4,
            '9' => 2,
            '8' => 4,
            '4' => 1,
            '0' => 1,
            '5' => 2
          };
      

      【讨论】:

        【解决方案3】:

        解决方案

        #!/usr/bin/perl                                             
        
        use strict;
        
        my $str = '654768687698579870333';
        my (%counts, $sum);
        
        while ($str =~ m/(\d)/g) {
        
            $counts{$1}++;
            $sum++;
        }
        
        print "The count each digit appears is: \n";
        print "'$_' - $counts{$_}\n" for sort keys %counts;
        print "The sum of all the totals is $sum\n";
        

        输出

        The count each digit appears is: 
        '0' - 1
        '3' - 3
        '4' - 1
        '5' - 2
        '6' - 4
        '7' - 4
        '8' - 4
        '9' - 2
        The sum of all the totals is 21
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多