zoukankan      html  css  js  c++  java
  • Perl-求交集和并集(Nvidia2018笔试)

    1、原题

     2、代码

    @A = (5,6,7);  # 数组用@和圆括号,用$A[index]访问;哈希用%和圆括号,用
                                 # $A{'key'}访问
    @B = (6,7,8);
    
    @intersection;
    @union;
    
    # 计算交集,依次取出A中元素,判断其是否与B中的某个元素相等
    foreach $a (@A){
        for($i=0;$i<@B;$i++){   # @B的含义由上下文决定,此处表示其size
            if($B[$i] == $a){
                push(@intersection,$a);
            }
        }
    }
    
    print("intersection is:
    ");
    foreach $item (@intersection){
        print("$item ");
    }
    print("
    ");
    
    # 计算并集,先将A和B直接合并,接着依次判断A_B中的各个元素是否已经存在于
    # 当前的union数组中,若没有则push进去
    @A_B = (@A,@B);
    for $item (@A_B){
        $item_in_current_union = 0;
        for($i=0;$i<@union;$i++){
            if($union[$i]==$item) {
                    $item_in_current_union = 1;
            }
        }
        if($item_in_current_union == 0){ 
            push(@union,$item);
            $size = @union;                # union的大小动态改变
            print("union size is $size
    ");
        }
    }
    
    print("union is:
    ");
    foreach $item (@union){
        print("$item ");
    }
    print("
    ");

    3、输出

    intersection is:
    6 7
    union size is 1
    union size is 2
    union size is 3
    union size is 4
    union is:
    5 6 7 8
  • 相关阅读:
    A*算法在栅格地图上的路径搜索(python实现)_1.1
    python基础
    Celery ---异步任务,定时任务,周期任务
    Flask-Script
    Flask-SQLAlchemy
    SQLAlchemy的增删改查 一对多 多对多
    Django Rest framework
    django之forms组件
    缓存, 队列(Redis,RabbitMQ)
    django框架(2)
  • 原文地址:https://www.cnblogs.com/wt-seu/p/12418611.html
Copyright © 2011-2022 走看看