Unconfigured Ad

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • semna
    Member
    • Apr 2010
    • 55

    #1

    perl

    Hi,
    I have two list like this:
    a1 = [2,5,7,9,10]
    a2 = [1,4,7,8,10]
    first I tried to find the first common element by perl script:

    #!/usr/bin/perl -w
    use strict;
    use warnings;
    my $index1 = length(@a1)-1;
    my $index2 = length(@a2)-1;
    my $commonElement = "";
    while ($a1[$index1] eq $a2[$index2]){
    $commonElement = $a1[$index1];
    $index1--;
    $index2--;
    }
    return "$commonElement\n";

    if I want to find get distance simultaneously, how can do that? for instance in this exapmle for both list should be 3.
    I wrote this but it doesn't work:
    $index1 = 1;
    $index2 =1;
    if ($a1[$index1] ne $a2[$index2]){
    $index1++;
    $index2++;

    }elsif ($a1[$index1] eq $a2[$index2]){
    return $index1, $index2;
    exit;
    }
    Any response would be appreciated.
  • rglover
    rg
    • Dec 2008
    • 51

    #2
    Hi Semna,

    There are a number of things that are making your code not work, but first a few pointers:
    1. Enclosing your code in
      Code:
      code tags
      is a really good idea if you want people to help you out - it's much easier to read.
    2. Look up http://www.perlmonks.com - it's an excellent resource for perl questions, especially as yours isn't a bioinformatics problem, but a perl one.


    I'm in a good mood today so I've put together some code that will do what I think you want. You wanted to find the first elements that matched and then find the position of those elements and their value - so where your two arrays match (with values of 7) and find the position of those elements, rather than the elements that match with values of 10?

    Firstly, you're working backwards through your arrays, which will not give you the first matching values, but the last. I don't think the code you've written there would ever work... I don't understand your logic. It says "while the length of my two arrays are the same, the common element is the length of the array. Reduce the size of the array and start again".

    Secondly, you're trying to use "length" to get the size of your array. The way to get the number of elements present in an array is to use "scalar" (see the code below). Using "length" would kill your code straight away because both of your index values would be 0 all of the time.

    Thirdly, you say you want to find the "distance" simultaneously. I've understood that to be that you want the element position within the array. In that case, the element position for your example arrays will be 2, not 3, because array positions are counted from 0, not 1.

    Hopefully the code below will show you enough when you run it - try it with different values in your array and see if you understand how it is working and why. I think it would be a good learning exercise if you're not familiar with Perl.

    Code:
    use strict;
    use warnings;
    
    my @a1 = (2,5,7,9,10);
    my @a2 = (1,4,7,8,10);
    my $size = scalar(@a1);
    
    my $common_element = undef;
    my $common_element_array_position = undef;
    
    for (my $i=0; $i<$size; $i++) {
      print "a1:".$a1[$i]."\n";
      print "a2:".$a2[$i]."";
      if ($a1[$i] == $a2[$i]) {
        print " They match so we'll skip the rest of the array\n";
        $common_element = $a1[$i];
        $common_element_array_position = $i;
        last;
      }
      else {
        print " They don't match\n";
      }
    }
    
    if (defined $common_element && defined $common_element_array_position) {
      print "CE: $common_element\nPosition: $common_element_array_position\n";
    }
    else {
      print "Could not find any common elements\n";
    }

    Comment

    • westerman
      Rick Westerman
      • Jun 2008
      • 1104

      #3
      Finding the first common element of two lists, eh? Sounds like a 1st year programming assignment. I suspect that there is some algorithmic function you could look up

      Of course in Perl TIMTOWTDI but I would

      1) Convert the first list into a hash via the map command
      2) Use a foreach loop to go through the second list to find the first element in the second list that has a definition in the hash.
      3) Then, since you also want the index in the first list, do a foreach to find the index of the element.

      I can see problems with the above with large lists or sparse hit lists. I.e., it isn't the most efficient code in the world.

      Or you could use List::Compare.

      Comment

      • westerman
        Rick Westerman
        • Jun 2008
        • 1104

        #4
        Ah, rglover's solution gives the first position where both elements are common. My suggestion just gives the first common element. It was nice of her to give a solution -- Rachel must be having a better day than I. :-)

        Comment

        • rglover
          rg
          • Dec 2008
          • 51

          #5
          report writing distraction technique I'm not normally someone who answers "my code doesn't work" questions...

          Comment

          • damiankao
            Member
            • Jan 2010
            • 49

            #6
            To find first common element of two lists in python...

            Code:
            a = [1,2,3,4,5]
            b = [6,7,8,9,1,10,12,2,3,4]
            
            intersection = [overlap for overlap in a if overlap in b]
            
            print intersection[0]

            Comment

            • simonandrews
              Simon Andrews
              • May 2009
              • 870

              #7
              Aargh. Shouldn't have started playing with this.

              Code:
              #!/usr/bin/perl
              use warnings;
              use strict;
              my @ar1 = (2,5,7,9,10,12,16);
              my @ar2 = (1,4,5,7,8,10);
              my %c;
              
              for (0..$#ar1){$c{$ar1[$_]}->[0] = $_ unless (defined $c{$ar1[$_]}->[0])};
              for (0..$#ar2){$c{$ar2[$_]}->[1] = $_ unless (defined $c{$ar2[$_]}->[1])};
              
              my @common;
              for (keys %c){push @common,$c{$_}->[0] if (defined $c{$_}->[0] and defined $c{$_}->[1])};
              @common = sort {$a<=>$b} @common;
              
              print "First common value is ",$ar1[$common[0]]," at indices ",$common[0]," and ",$c{$ar1[$common[0]]}->[1],"\n";
              Finds the first common value and only needs to do a single pass through each list. Pretty trivially modified to get all overlaps or just those with the same index in both sets.

              Figuring out how it works is left as an exercise to the reader, but looking back at it even makes my eyes hurt!

              Off to do something more productive....

              Comment

              Latest Articles

              Collapse

              • SEQadmin2
                New Genomics Technologies Take Aim at Long-Standing Limits
                by SEQadmin2


                Researchers using sequencing and genomics tools often have to make trade-offs. They can choose between speed or scale, short reads or long-range information, or targeted panels or a view of the whole transcriptome. New technologies that have been released this year are built to address those tough choices.

                We asked six companies the same four questions to learn about their latest products. The new technologies bring a lot to the table, including rethinking sequencing
                ...
                Today, 10:25 AM
              • SEQadmin2
                How Immunogenomics Decodes Immunity’s Genetic Blueprint
                by SEQadmin2




                The immune system’s power comes from its genetic diversity, allowing myriad threats to be neutralized through first recognizing foreign antigens. That diversity is also what makes the immune system so difficult to study. Recent advances in sequencing technology and computational biology, however, are giving researchers new tools to understand immune responses and immune-related diseases in greater detail.

                This convergence of genetics, immunology, and computation...
                09-01-2026, 05:41 AM

              ad_right_rmr

              Collapse

              News

              Collapse

              Topics Statistics Last Post
              Started by SEQadmin2, 09-25-2026, 09:06 AM
              0 responses
              28 views
              0 reactions
              Last Post SEQadmin2  
              Started by SEQadmin2, 09-23-2026, 11:05 AM
              0 responses
              24 views
              0 reactions
              Last Post SEQadmin2  
              Started by SEQadmin2, 09-18-2026, 11:37 AM
              1 response
              46 views
              0 reactions
              Last Post pekgio
              by pekgio
               
              Started by SEQadmin2, 09-16-2026, 10:23 AM
              1 response
              55 views
              0 reactions
              Last Post pekgio
              by pekgio
               
              Working...