[Codility]Lesson7

TASK1

A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:

  • S is empty;
  • S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.

For example, the string "{[()()]}" is properly nested but "([)()]" is not.

Write a function:

def solution(S)

that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..200,000];
  • string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def trans(a):
    if a=='{':
        return 1
    elif a=='[':
        return 2
    elif a=='(':
        return 3
    elif a=='}':
        return -1
    elif a==']':
        return -2
    elif a==')':
        return -3
    else:
        print("ERROR!",a)
        return "error"   
def solution(S):
    # write your code in Python 3.6
    if isinstance(S,str)==0:
     return 0
    if len(S)==0:
        return 1
    s=trans(S[0])
    if s<0:
        return 0
    B=[s]
    N=len(S)
    #print("N=",N)
    for i in range(1,N):
        s=trans(S[i])
        #print("i=",i,"B=",B)
        if s>0:
            B.append(s)
        elif len(B)>0 and B[-1]+s==0:
            del B[-1]
            continue
        else:
            return 0
    if len(B)==0:
        return 1
    return 0

Task2 

You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.

The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.

Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:

  • 0 represents a fish flowing upstream,
  • 1 represents a fish flowing downstream.

If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:

  • If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
  • If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.

We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.

For example, consider arrays A and B such that:

A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0

Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive.

Write a function:

def solution(A, B)

that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive.

For example, given the arrays shown above, the function should return 2, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [0..1,000,000,000];
  • each element of array B is an integer that can have one of the following values: 0, 1;
  • the elements of A are all distinct.
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
class fish():
    def __init__(self,a,b):
        self.size=a
        self.direction=b

def solution(A, B):
    # write your code in Python 3.6
    N=len(A)
    if N==0 or len(B)!=N:
        return EOF
    fi=fish(A[0],B[0])
    F=[fi]
    # print("when i=",0)
    # for i in range(len(F)):
    #     print("F=",F[i].size,F[i].direction)
    for i in range(1,N):
        fi=fish(A[i],B[i])
        # print("i=",i,"fi=",fi.size,fi.direction)
        # #不可能出现没有鱼,总有大佬
        # if len(F)==0:
        #     F.append(fi)
        if B[i]==1:
            # print(">>")
            F.append(fi)#如果乖乖顺流而下,不会和上面的大佬碰上
        elif B[i]==0:#逆流而上,开始battle
            # print("<<")
            k=len(F)#开始与k条鱼一个一个battle
            F.append(fi)#首先把新来的鱼加入水流中
            while F[k-1].direction==1:  #当最靠近的鱼确实是在往下游(否则前面的鱼都在逆流而上,跟着逆流而上也不会出问题)               
                #print("k=",k)
                if A[i]>F[k-1].size:#如果最靠近的一条鱼没有我大
                    #print("win")
                    del F[k-1]#把它吃掉
                    k=k-1#我之前还有k-1条鱼
                else:#最靠近我的那条鱼已经比我大
                    #print("lose")
                    del F[k]#把我自己吃掉了
                    break
#                 for j in range(len(F)):
#                     print("F=",F[j].size,F[j].direction)
        # for j in range(len(F)):
        #     print(F[j].size,F[j].direction)
    return len(F)

         Task3:

A string S consisting of N characters is called properly nested if:

  • S is empty;
  • S has the form "(U)" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.

For example, string "(()(())())" is properly nested but string "())" isn't.

Write a function:

def solution(S)

that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise.

For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..1,000,000];
  • string S consists only of the characters "(" and/or ")".
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def trans(a):
    if a=='(':
        return 1
    elif a==')':
        return -1    
    else:
        print("ERROR!")
        return 0
def solution(S):
    # write your code in Python 3.6
    N=len(S) 
    if N&2==1:
        return 0
    if N==0:
        return 1
    t=trans(S[0])
    if t<0:
        return 0#第一个不能是")"
    B=[t]
    M=1
    for i in range(1,N):
        if trans(S[i])==1:
            B.append(1)
            M=M+1
        else:#trans(S[i])==-1
            if M==0 or B[M-1]==-1:
                return 0
            else:#B[M-1]==1:
                del B[M-1]
                M=M-1
    if M==0:
        return 1
    else:
        return 0

    

 Task4:

You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

def solution(H)

that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

H[0] = 8 H[1] = 8 H[2] = 5 H[3] = 7 H[4] = 9 H[5] = 8 H[6] = 7 H[7] = 4 H[8] = 8

the function should return 7. The figure shows one possible arrangement of seven blocks.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..100,000];
  • each element of array H is an integer within the range [1..1,000,000,000].

Copyright 2009–2022 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

 开始想用一个数列存储现在已经有的”隔断“,得分是85%,有两个TIMEOUT(后来发现{0,1}序列完全可以用二进制来存,但是计算也很复杂)

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(H):
    # write your code in Python 3.6
    N=len(H)
    print("N=",N)
    if N==0:
        return 0
#     B=[]
#     for i in range(H[0]-1):
#         B.append(0)
#     B.append(1)
    B=pow(2,H[0]-1)
    h=H[0]
    count=1
    print("i=",0,"B=",B,"h=",h)
    for i in range(1,N):
        if H[i]>h:
#             for j in range(h,H[i]-1):
#                 B.append(0)
#             B.append(1)
            B=B+pow(2,H[i]-1)
            count=count+1
        elif H[i]==h:
            continue
        else:#H[i]<h
#             if B[H[i]-1]==0:
#                 count=count+1
#                 B[H[i]-1]=1
            tmp=pow(2,H[i])
            if B%tmp<tmp/2:
                count=count+1
                B=B+(pow(2,H[i]-1))
#             for j in range(H[i],h):
#                  del B[H[i]]
            B=B%pow(2,H[i])
        h=H[i]
        print("i=",i,"B=",B,"count=",count,"h=",h)
    return count

后来想好像还是用栈存储比较合适

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(H):
    # write your code in Python 3.6
    N=len(H)
    #print("N=",N)
    if N==0:
        return 0
    B=[H[0]]
    count=1
    M=1
    #print("i=",0,"B=",B,"h=",h)
    for i in range(1,N):
        if H[i]>B[M-1]:
            B.append(H[i])
            count=count+1
            M=M+1
        elif H[i]==B[M-1]:
            continue
        else:#H[i]<B[M-1]
            # if B[H[i]-1]==0:
            #     count=count+1
            #     B[H[i]-1]=1
            # for j in range(H[i],h):
            #      del B[H[i]]
            j=M-1
            while j>=0 and B[j]>H[i]:
                del B[j]
                j=j-1
                M=M-1
            #这样得到B[j+1]>H[i] B[j]<=H[i]
            if j<0 or B[j]<H[i]:
                count=count+1
                B.append(H[i])
                M=M+1
    return count

 满分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值