예제 #1
0
def each_case():
    N = int(stdin.readline())
    adj_list = {n:{} for n in xrange(1, N+1)}
    adj_list[0] = {n:1 for n in xrange(1, N+1)}
    for i in xrange(N-1):
        X, Y = map(int, stdin.readline().split())
	adj_list[X][Y] = 1
	adj_list[Y][X] = 1

    update = True
    while update:
#    for i in xrange(N):   # maybe N/2 ?
        update = False
        for v, edges in adj_list.iteritems():
            for v1 in edges:
                #if len(adj_list[v1]) >= (3 if v else 2):
                max1, max2 = 0, 0
                for v2, score in adj_list[v1].iteritems():
                    if v2 != v and max2 < score:
                        if score < max1:
                            max2 = score
                        else:
                            max1, max2 = score, max1
                if max2:
                    maxTree = max1 + max2 + 1
                    if edges[v1] != maxTree:
                        edges[v1] = maxTree
                        update = True

    return N - max(adj_list[0].itervalues())
예제 #2
0
def run():
    _realA, _imagA = [float(x) for x in stdin.readline().split(" ")]
    _realB, _imagB = [float(x) for x in stdin.readline().split(" ")]
    ans = sumComplexNumbers(_realA, _imagA, _realB, _imagB)
    '''
    # https://pyformat.info/
    # https://docs.python.org/3.1/library/string.html
    http://stackoverflow.com/questions/7746143/formating-complex-numbers-in-python
    '''
    
    msg = '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = minusComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = mulComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = divComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = modComplexNumber(_realA, _imagA)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = modComplexNumber(_realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    stdout.write(msg)
예제 #3
0
def main():
   l=int(sin.readline())
   B = BOX(l)
   for i in range(l):
      line = sin.readline().rstrip().split(" ")
      B.addbox({'l':int(line[0]),'w':int(line[1]),'h':int(line[2]), 'k':i})
   B.process()
예제 #4
0
def main():
    n = int(stdin.readline())
    nabomatrise = [None for i in xrange(n)]
    for i in xrange(n):
        nabomatrise[i] = [False] * n
        linje = stdin.readline()
        for j in xrange(n):
            nabomatrise[i][j] = (linje[j] == '1')
    for linje in stdin:
        start = int(linje)

        h_n = {start}
        utraversert = [start]

        while utraversert:
            rad = nabomatrise[utraversert.pop()]
            for i in xrange(n):
                if rad[i] and i not in h_n:
                    h_n.add(i)
                    utraversert.append(i)

        nrn = {i for i in xrange(n)} - h_n

        e = 0
        for node in nrn:
            row = nabomatrise[node]
            for i in xrange(n):
                if row[i] and i in nrn:
                    e += 1
        v = float(len(nrn))
        print "%.3f" % ((e / v**2 if v != 0 else 0) + 1E-12)
예제 #5
0
    def make_end_user_authorize_token(self, credentials, request_token):
        """Have the end-user authorize the token in their browser."""

        authorization_url = self.authorization_url(request_token)
        self.output(self.WAITING_FOR_USER % authorization_url)
        self.output(self.TIMEOUT_MESSAGE % self.TIMEOUT)
        # Wait a little time before attempting to launch browser,
        # give users the chance to press a key to skip it anyway.
        rlist, _, _ = select([stdin], [], [], self.TIMEOUT)
        if rlist:
            stdin.readline()
        self.output(self.WAITING_FOR_LAUNCHPAD)
        webbrowser.open(authorization_url)
        while credentials.access_token is None:
            time.sleep(access_token_poll_time)
            try:
                credentials.exchange_request_token_for_access_token(
                    self.web_root)
                break
            except HTTPError, e:
                if e.response.status == 403:
                    # The user decided not to authorize this
                    # application.
                    raise EndUserDeclinedAuthorization(e.content)
                elif e.response.status == 401:
                    # The user has not made a decision yet.
                    pass
                else:
                    # There was an error accessing the server.
                    print "Unexpected response from Launchpad:"
                    print e
예제 #6
0
def main():
    
    n=0
    p=[0,0,0,0,0]
    co=[0,4,30,50,30,6]
    inv = 441666668
    tst= int(stdin.readline())
    while(tst>0):
        tst-=1
        ai=int(stdin.readline())
        i=1
        p.insert(0,1)
        while(i<=5):
            p[i]=mod(ai*int(p[i-1]))
            i+=1
        j=1
        while(j<=5):
            p[j]=mod(int(co[j])*int(p[j]))
            j+=1
        k=1
        sums=0
        while(k<=5):
            sums=mod(sums+int(p[k]))
            k+=1
        sums=mod(sums*inv)
        print(sums)
    return 0
예제 #7
0
파일: shell.py 프로젝트: OEHC/web
def read_emails_loop():
    from mftutor.settings import YEAR
    from sys import stdin
    while True:
        print('Enter student number:')
        studentnumber = stdin.readline().strip()
        if not studentnumber:
            print('Bye')
            break
        try:
            prof = TutorProfile.objects.get(studentnumber=studentnumber)
        except TutorProfile.DoesNotExist:
            print('Not found')
            continue
        print(prof)
        print(u'Groups: %s' %
              u', '.join(tg.name
                         for tg in TutorGroup.objects.filter(
                             tutor__profile=prof, tutor__year__exact=YEAR)
                         .order_by('-visible', 'name')))
        print(prof.email)
        print('Enter new email address:')
        email = stdin.readline().strip()
        if not email:
            print('No change')
            continue
        prof.email = email
        prof.save()
        print('Saved')
예제 #8
0
def solution():
    while True:
        try:
            line = stdin.readline().strip()
            if not line:
                break
            if(line.endswith('#')):
                line = line[:len(line)-1]
            else:
                while True:
                    #ch = stdin.read(1)
                    line2 = stdin.readline().strip()
                    '''
                    for ch in stdin.readline().strip():
                        if ch == '#':
                            break
                        if ch != '\n':
                            #line.append(ch)
                            line += ch
                    '''
                    line += line2
                    if(line.endswith('#')):
                        line = line[:len(line)-1]
                        break
            #line = ''.join(line)
            anyBaseToDec(line, 2)
        #except OSError as err:
        except EOFError:
            #print("Error: %s\n " % (err))
            break
def main():
	T = int(raw_input())
	result = []
	if T == 0:
		result.append("NO")
	for i in range(0,T):
		
		array = []
		flag = 1
		result.append('NO')
		temp_result = 0

		n,k = map(int,stdin.readline().split())
		array.extend(stdin.readline().rstrip())
		[array.pop(array.index(x)) for x in array if x==' ']

		if len(array) > n:
			flag = 0
		if len(array) != len(set(array)):
			flag = 0
		
		for emnt in array:
			if ((int(emnt)%2 == 0 or k == 0) and int(emnt)!=0) and flag == 1:
				temp_result+=1 
				if temp_result >= k or k == 0:
					result[i] = "YES"
 				else: 
					result[i] = "NO"
			else:
				temp_result = 0
	for i in result:
		print i		
예제 #10
0
def main():
    print("X-Y Plotter: {}".format(argv))
    if len(argv) < 3:
        raise Exception('>>> ERROR! Please supply a plotting interval and two quantities to plot <<<')
    interval = int(argv[1])
    coordinate1 = argv[2]
    coordinate2 = argv[3]
    line = stdin.readline()
    ax1 = pyplot.figure().add_subplot(111)
    pyplot.grid(b=True, color='0.25', linestyle='-')
    ax1.set_xlabel(coordinate1, color='b')
    ax1.set_ylabel(coordinate2, color='b')
    # ax1.set_xlim(-1.0, 2.0)
    # ax1.set_ylim(-1.0, 2.0)
    n = 0
    x = []
    y = []
    while line:
        p = loads(line)
        if n % interval == 0:
            x.append(p[coordinate1])
            y.append(p[coordinate2])
        line = stdin.readline()
        n += 1
    ax1.plot(x, y, 'bo:', markersize=3)
    pyplot.show()
예제 #11
0
def main():
    from sys import stdin

    maxint = 3500
    testcases = int(stdin.readline())
    for test in range(testcases):
        byer = int(stdin.readline())
        rekkefolge = map(int, stdin.readline().split())
        rekkefolge.append(rekkefolge[0])
        nabomatrise = [map(lambda x: maxint if x == '-1' else int(x), stdin.readline().split()) for _ in range(byer)]

        for k in range(byer):
            for i in range(byer):
                for j in range(byer):
                    nabomatrise[i][j] = min(nabomatrise[i][j], nabomatrise[i][k] + nabomatrise[k][j])
        rute = 0
        current = rekkefolge[0]
        umulig = False
        for by in rekkefolge[1:]:
            vei = nabomatrise[current][by]
            if vei == maxint:
                umulig = True
                break
            rute += vei
            current = by
        if umulig:
            print 'umulig'
        else:
            print rute
def main():
    from itertools import combinations
    from sys import stdin,stdout    
    def ch(n):
        c=0
        for i in range(len(n)-1):
            if n[i]==n[i+1]:
                c=1
                break
        if c==0:
            return True        
    s_len = int(stdin.readline().strip())
    s = stdin.readline().strip()
    l=list(s)
    n=list(set(l))
    if len(n)>=2:
        a=list(combinations(n,2))    
        m=[]    
        for i in a:
            s=''
            for j in l:
                if j in i:
                    s+=j
            m.append(s)        
        z=[]
        for i in m:
            if ch(i)==True:
                z.append(len(i))
        if len(z)>0:
            stdout.write(str(max(z))+'\n')
        else:
            stdout.write('0\n')
    else:
        stdout.write('0\n')
def main():
    from math import log
    from sys import stdin,stdout
    from itertools import tee 
    from functools import reduce
    def pairwise(iterable):    
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)   
    T = int(stdin.readline().strip())
    d = dict()
    while(T>0):
        N=int(stdin.readline().strip())
        L = set(map(int, stdin.readline().strip().split(' ')))
        if N==1: print("NO")
        else:
            sim = False
            key = ''
            for i in range(1,N+1):
                for a in pairwise(L):
                    key = ''.join(map(str,a))
                    if not d.__contains__(key):                              
                        r = reduce(lambda x,y: x&y,a)
                        if r>0 and log(r,2).is_integer(): 
                            sim = True                                                   
                            d[key]="YES"
                            break
                        else: d[key]="NO"
                    else: break                    
                if sim: break                
            stdout.write(d[key]+'\n')            
        T-=1
예제 #14
0
def main():
    syslog.openlog("update-hub-overlay", 0, syslog.LOG_LOCAL5)

    # get useful paths
    install_root = path.dirname(path.dirname(path.abspath(sys.argv[0])))
    opt_root = path.dirname(install_root)
    opt_inveneo = path.join(opt_root, "inveneo")

    stdout.write("\nUpdating: " + install_root + "...\n")
    svn_update(install_root)

    stdout.write("\nUpdating: " + opt_inveneo + "...\n")
    svn_update(opt_inveneo)

    stdout.write("\nInstalling any new packages...\n")
    sp.call([path.join(install_root, "bin", "install-packages.py"), path.join(install_root, "package.d")])

    stdout.write("\nReinstalling overlay...\n")
    sp.call([path.join(install_root, "bin", "install-hub-overlay.py")])

    stdout.write("\nRepopulating Samba...\n")
    sp.call([path.join(install_root, "bin", "populate-hub-ldap.py")])

    stdout.write("\nDone. Press enter/return key to reboot...\n")
    stdin.readline()
    os.system("reboot")

    return 0
예제 #15
0
def mapper():
    t = None
    n = None
    line_errors = 0

    parse_line = re.compile('(\d+)\t(.*)')
    line = stdin.readline()
    while line:
        m = parse_line.match(line)
        if m:
            node = int(m.group(1))
            data = json.loads(m.group(2))
            # Do we have our metadata (load once)
            if not n:
                n = data['m'][0]
            if not t:
                t = data['m'][1]
                t_by_n = float(t) / n

            # Calculate our new PR
            data['p'] = t_by_n + (1 - t) * \
                sum(
                    i[1] / i[2] for i in data['s']
                )

            # Emit (with value pickled for size/efficiency)
            stdout.write("%s\t%s\n" %(node, json.dumps(data, 2)))
        else:
            line_errors += 1

        line = stdin.readline()
예제 #16
0
파일: cli.py 프로젝트: aperezdc/omni
def cmd_change_password(omni_app, realm_or_store, username, opt_stdin=False):
    """
    Usage: omni change-password <realm-or-store> <username>

    Options:

      -i, --stdin  Read passwords from standard input. The first line must
                   be the existing password, and the second line the new
                   password.
      -h, --help   Show this help message.
    """
    from getpass import getpass
    try:
        db = omni_app.get_realm_or_store(realm_or_store)
    except KeyError:
        return "{}: invalid realm/store".format(realm_or_store)

    if opt_stdin:
        from sys import stdin
        old_pw = stdin.readline().strip()
        if not db.authenticate(username, old_pw):
            return "Incorrect password"
        new_pw = stdin.readline().strip()
    else:
        old_pw = getpass("old password for {}: ".format(username))
        if not db.authenticate(username, old_pw):
            return "Incorrect password"
        old_pw = getpass("new password for {}: ".format(username))
        new_pw = getpass("new password for {} (again): ".format(username))
        if old_pw != new_pw:
            return "Passwords do not match"
    db.set_password(username, new_pw)
예제 #17
0
def main():
    time0 = datetime.now()
    userinput = int(stdin.readline())
    while userinput!=0:
         if print_debug:
            print('\nInput = %s\n' % userinput)
         v = factorize(userinput)
         s = len(v)
         if s > 0:
             current = v[0]
             exp = 0
             it = 1
             for f in v:
                 if f == current:
                     exp += 1
                 else:
                     print('%d^%d' % (current, exp)),
                     current = f
                     exp = 1
                 if it == s:
                     print('%d^%d' % (current, exp))
                 it += 1
         userinput = int(stdin.readline())
    elapsed_time_function("main", time0)
    return 0
예제 #18
0
파일: 129b.py 프로젝트: dk00/old-stuff
def main():
  l = stdin.readline().split()
  n, m = int(l[0]), int(l[1])
  adj = [[] for i in range(n)]
  for k in range(m):
    l = stdin.readline().split()
    i, j = int(l[0])-1, int(l[1])-1
    adj[i].append(j)
    adj[j].append(i)
  q = []
  count = []
  for i in range(n):
    count.append(len(adj[i]))
    if count[-1] == 1:
      q.append(i)
  m = 0
  q1 = []
  while len(q) > 0:
    i = q[0]
    count[i] = 0
    del q[0]
    for j in adj[i]:
      count[j] -= 1

    if len(q) < 1:
      m += 1
      for i in range(n):
        if count[i] == 1:
          q.append(i)
  print m
예제 #19
0
def run():
    cases = int(stdin.readline())
    while cases > 0:
        number  = int(stdin.readline())
        msg     = 'The streak is broken!' if ((number % 21) == 0 or hasSubNumber(number, 21)) else 'The streak lives still in our heart!'
        stdout.write("%s\n" % (msg))
        cases -= 1
예제 #20
0
파일: task1.py 프로젝트: antofik/Python
def task():
    try:
        count = int(stdin.readline())
        if count <= 0 or count > 1000:
            raise Exception("Invalid count")
        sessions = stdin.readline().split(' ')
        if count != len(sessions):
            raise Exception("Count doesn't match actual amount of sessions")

        one = set()
        two = set()
        for session in sessions:
            i = int(session)
            #print 'analyzing %s' % i
            if i == 0:
                #print 'skipping'
                continue
            if i in two:
                #print 'triple - raising exception'
                raise Exception("Conference is not allowed")
            if i in one:
                #print 'moving to two'
                one.remove(i)
                two.add(i)
            else:
                #print 'adding to one'
                one.add(i)

                #print 'one=%s\ntwo=%s' % (one, two)

        print len(two)
    except Exception, e:
        #print str(e)
        print -1
예제 #21
0
def mapper():
    """
    Pairs mapper function

    Reads stdin, (emits w1 w2 : n=1) on stdout
    """
    previous_word = None
    line = stdin.readline()
    while line:
        if len(line) != 0:
            # Make everything lower case
            line = line.lower().strip()
            # Strip non word/whitespace characters
            line = re.sub(r"[^\w\s]", "", line)
            # Replace any whitespace with a single space
            line = re.sub(r"\s+", " ", line)
            # Loop though words on line
            for word in line.split(" "):
                this_word = word
                # Is this a new pair? (following a paragraph)
                if previous_word:
                    # Emit
                    stdout.write("%s %s: %d\n" % (previous_word, this_word, 1))
                # current word is previous word now
                previous_word = this_word
        else:
            # There was a new paragraph
            last_word = None
        line = stdin.readline()
예제 #22
0
파일: slides.py 프로젝트: mebubo/codejam
def main():
    T = int(stdin.readline())
    cases = []
    for t in range(T):
        bffs = map(int, stdin.readline().split())
        cases.append(bffs)
    solveAll(cases)
예제 #23
0
def main():
    setrecursionlimit(100000)
    # skapar en liten liten sköldpadda
    leonardo = Leonardo()
    q = LinkedQ()
    # stdin = open("firstsample.in")

    rad = stdin.readline()

    row = 1

    while rad:
        rad = rad.split("%", 1)[0] # Ta bort kommentarer.

        for tkn in rad.split():
            buildTokens(q, tkn, row)   # Lägg till tokens.

        row =row +1
        rad = stdin.readline() # Läs in ny rad.

    try:    # Skriv ut alla linjer
        match(q, leonardo)
        for i in range(0, len(leonardo.printout)): # Skriv ut allt när vi är klara.
            print(leonardo.printout[i])

    # Såvida det inte failar. Då skriver vi ut syntaxfel.
    except Syntaxfel as felet:
        print(felet)
예제 #24
0
def main():
	case = 1
	while True:
		n, m = map(lambda x: int(x), stdin.readline().split())
		if n == 0:
			break
		names = []
		distance = [[1000 for j in range(n)] for i in range(n)]
		for x in range(n):
			distance[x][x] = 0
		for x in range(n):
			names.append(stdin.readline().strip())
		for x in range(m):
			i, j, k = map(lambda x: int(x), stdin.readline().split())
			i -= 1
			j -= 1
			distance[i][j] = distance[j][i] = k
		for k in range(n):
			for i in range(n):
				for j in range(n):
					if distance[i][j] > (distance[i][k] + distance[k][j]):
						distance[i][j] = distance[i][k] + distance[k][j]
		min = 100000
		name = names[0]
		for i in range(n):
			s = sum(distance[i])
			if s < min:
				min = s
				name = names[i]
		print("Case #%d : %s" % (case, name))
		case += 1
예제 #25
0
파일: annoying.py 프로젝트: HectorDD/ADAT5
def main ():
    line = stdin.readline()
    b = line.split()
    while b[0]!='0' and b[1]!='0'and b[2]!='0' and b[3]!='0':
        n=int(b[0])
        m=int(b[1])
        c=int(b[2])
        #print ("el c es: ", c)
        r=int(b[3])
        #print ("el r es: ", r)
        paint=[]
        mypaint=[]
        for j in range(n):
            l=[]
            l1 = stdin.readline() 
            l1=l1[:-1]
            lisnum=[]
            for t in l1:
                lisnum.append(int(t))
                l.append(0)
            paint.append(lisnum)
            mypaint.append(l)
        #imprimirpint(paint)
        print(solve(n,m,c,r,paint,mypaint))
        line = stdin.readline() 
        b = line.split()              
예제 #26
0
def main():
    print("Enter number of players")
    player_count = stdin.readline()

    all_actions = Coup.get_all_actions()  # general actions and character actions

    Coup.set_players(2)
    Coup.init_coup()

    print("Please enter the action you would like to take: 1-7")
    selection = stdin.readline()

    #  request block from the player who is targeted
    #  if no block is issued take the action
    #  if no challenge is issued take the action

    current_player = Coup.get_player_turn()

    #  check to see if action requires an affected player

    current_player.coins = 9
    if int(selection) in all_actions:
        influence = all_actions[int(selection)].effect(current_player, Coup.players[-1])
        Coup.remove_influence(Coup.players[-1], influence[-1])

        [print(c) for c in Coup.players[-1].influence]
    else:
        print("Invalid action chosen.")

    return
예제 #27
0
def main():
    print "Potential Plotter: {}".format(argv)
    if len(argv) == 5:
        r_min = float(argv[1])
        r_max = float(argv[2])
        th_min = float(argv[3])
        th_max = float(argv[4])
    elif len(argv) == 1:
        r_min = th_min = -30
        r_max = th_max = 30
    else:
        raise Exception('>>> ERROR! Please enter either zero or four parameters <<<')
    line = stdin.readline()
    ax1 = pyplot.figure().add_subplot(111)
    pyplot.grid(b=True, which='major', color='0.25', linestyle='-')
    ax1.set_xlabel('r, theta', color='0.20')
    ax1.set_ylabel('R(r)', color='b')
    ax1.set_ylim(r_min, r_max)
    ax2 = ax1.twinx()
    ax2.set_ylabel('THETA(theta)', color='r')
    ax2.set_ylim(th_min, th_max)
    n = 0
    while line:
        p = loads(line)
        ax1.plot(p['x'], p['R'], 'b.', markersize=2)
        ax2.plot(p['x'], p['THETA'], 'r.', markersize=2)
        line = stdin.readline()
        n += 1
    try:
        pyplot.show()
    except AttributeError as e:
        print('ATTRIBUTE ERROR: ' + str(argv[0]) + ': ' + str(e))
        exit(-1)
예제 #28
0
def main():
    t = int(stdin.readline())
    while t > 0:
        t -= 1
        ans = 0
        n = int(stdin.readline())
        e = stdin.readline()
        e = list(e)
        x = stdin.readline().split()
        x = [int(i) for i in x]
        io = [i for i in range(0, n) if e[i] == '1']
        if len(io) == 1:
            ans = x[n - 1] - 1
        else:
            ans += 
            for i in range(0, len(io) - 1):
                if io[i] + 1 == io[i + 1]:
                    continue
                else:
                    minans = 32768
                    f = 0
                    for j in range(io[i], io[i + 1]):
                        d1 = x[j] - x[io[i]]
                        d2 = x[io[i + 1]] - x[j + 1]
                        f = d1 + d2
                        minans = min(f, minans)
                    ans += minans

        print ans
예제 #29
0
파일: idmovie.py 프로젝트: vasc/couchee
def main():
    db = pymongo.Connection().usenet
    print "Search movies without id:"
    s = stdin.readline()
    nzbs = [nzb for nzb in db.nzbs.find({'stages.movieid': {'$ne': True}, 'stages.uploaded': True, 'tags': '#a.b.moovee@EFNet', 'rlsname': re.compile('%s' % s.rstrip(), re.I)})]
    for i in range(0, len(nzbs)):
        if 'error' in nzbs[i] and not nzbs[i]['error']['value'] in [421, 422, 423]: print 'ERROR', nzbs[i]['rlsname']; continue
        print str(i) + ':', nzbs[i]['rlsname']
        
    print
    while True:
        print 'Id movie: [num] [imdbid (ex. tt0123456)] or "exit"'
        s = stdin.readline()
        if s == 'exit\n': return
        m = re.match(r"(\d+)\s(tt\d{7})\n", s)
        m2 = re.match(r"^p\s+(\d+)\n", s)
        if m:
            i = int(m.group(1))
            nzb = nzbs[i]
            print 'Ided', nzb['rlsname'], 'as', 'http://www.imdb.com/title/' + m.group(2) + '/'
            print 'Are you sure (y/N)?'
            s = stdin.readline()
            if not s or not s[0] == 'y': continue
            del nzb['error']
            del nzb['stages']['error']
            nzb['link'] = 'http://www.imdb.com/title/' + m.group(2) + '/'
            nzb['movieid'] = m.group(2)
            nzb['stage'] = 3
            nzb['stages']['movieid'] = True
            db.nzbs.save(nzb)
            #print nzb
        elif m2:
            i = int(m2.group(1))
            nzb = nzbs[i]
            print nzb
예제 #30
0
def main():
    def sieve(n):
        numbers = [True]*n
        primes = []
        for x in range(2, n):
            if numbers[x]:
                primes.append(x)
                for y in range(2*x, n, x):
                    numbers[y] = False
        return primes

    primes = sieve(1001)
    stdin.readline()
    for n in map(int, stdin.readlines()):
        mc = float('-inf')
        for x in primes:
            if n == 1 or x >= n:
                break
            c = 0
            while n % x == 0:
                c += 1
                n /= x
            mc = max(c, mc)
        if n != 1:
            mc = max(1, mc)

        print(mc)
예제 #31
0
def li():
    return list(map(int, stdin.readline().split()))
# https://codeup.kr/problem.php?id=1366

# readline을 사용하기 위해 import합니다.
from sys import stdin

# 사각형의 크기 n을 입력합니다.
# 3 <= n <= 99, n은 홀수입니다.
# int형으로 변환합니다.
n = int(stdin.readline())
# 사각형의 공백이 있는 한 줄에서 공백 개수의 절반을 저장할 변수를 선언합니다.
one_side_blank_cnt = (n - 5) // 2

# 사각형의 첫 번째 줄인 별 *을 n개만큼 출력합니다.
print('*' * n)

# 사각형의 첫 번째 줄과 가운데 줄 사이를 출력하는 부분입니다.
# 줄의 개수는 한 줄에서 공백 개수의 절반에 1을 더한 값입니다.
# 한 줄에서 첫 번째 별과 두 번째 별 사이 공백의 개수를 0 ~ one_side_blank_cnt까지 반복합니다.
for blank_cnt in range(one_side_blank_cnt + 1):
    # 별 하나를 출력하고, 다음 줄로 내리지 않습니다.
    print('*', end='')
    # 공백을 현재 숫자인 blank_cnt만큼 출력하고, 다음 줄로 내리지 않습니다.
    print(' ' * blank_cnt, end='')
    # 별 하나를 출력하고, 다음 줄로 내리지 않습니다.
    print('*', end='')
    # 공백을 one_side_blank_cnt에서 현재 숫자인 blank_cnt를 뺀 값만큼 출력하고, 다음 줄로 내리지 않습니다.
    print(' ' * (one_side_blank_cnt - blank_cnt), end='')
    # 별 하나를 출력하고, 다음 줄로 내리지 않습니다.
    print('*', end='')
    # 공백을 one_side_blank_cnt에서 현재 숫자인 blank_cnt를 뺀 값만큼 출력하고, 다음 줄로 내리지 않습니다.
    print(' ' * (one_side_blank_cnt - blank_cnt), end='')
예제 #33
0
#!/usr/env/python

from sys import stdin


def resolv():
    input = [float(i) for i in stdin.readline().strip().split()]
    time_passed = 0
    production = 2.0
    farm_price = input[0]
    farm_prod = input[1]
    target = input[2]
    while True:
        time_without_farm = target / production
        farm_cost = farm_price / production
        time_with_farm = farm_cost + (target / (production + farm_prod))
        if time_without_farm > time_with_farm:
            time_passed = time_passed + farm_cost
            production = production + farm_prod
        else:
            return time_passed + time_without_farm


nb = int(stdin.readline().strip())
for i in range(1, nb + 1):
    print('Case #{}: {}'.format(i, resolv()))
예제 #34
0
from sys import stdin, stdout
# Accepted
# I Can Guess the Data Structure! UVA - 11995
for line in stdin:
    cases = int(line.strip())
    stack = []
    isStack = 1
    queue = []
    isQueue = 1
    priority = []
    isPriority = 1
    for case in range(cases):
        operation = stdin.readline().strip().split()
        if (int(operation[0]) == 1):
            #Into the bag
            stack.append(int(operation[1]))
            queue.append(int(operation[1]))
            priority.append(int(operation[1]))
        else:
            #Take out from the bag
            outElement = int(operation[1])
            if (isStack):
                if (stack and stack[len(stack) - 1] == outElement):
                    stack.pop()
                else:
                    isStack = 0
            if (isQueue):
                if (queue and queue[0] == outElement):
                    queue.pop(0)
                else:
                    isQueue = 0
예제 #35
0
from sys import stdin


def generate_table(num):
    # t[n] = 2*t[n-1]+t[n-2]+t[n-3]
    t = [0, 2, 5, 13]
    for n in range(4, num + 1):
        t.append(2 * t[n - 1] + t[n - 2] + t[n - 3])
    return t


if __name__ == '__main__':

    TABLE = generate_table(1000)

    while True:
        line = stdin.readline()
        if not line:
            break

        print(TABLE[int(line)])
예제 #36
0
def closest(A, i, high):
    l = 100000
    closest = i
    for x in A:
        if high and x >= i:
            diff = x - i
            if diff <= l and diff >= 0:
                l = diff
                closest = x
        elif not (high) and x <= i:
            diff = i - x
            if diff <= l and diff >= 0:
                l = diff
                closest = x
    return closest


liste = []
for x in stdin.readline().split():
    liste.append(int(x))

sortert = sorter(liste)
#print(sortert)
for linje in stdin:
    ord = linje.split()
    minst = int(ord[0])
    maks = int(ord[1])
    resultat = finn(sortert, minst, maks)
    print str(resultat[0]) + " " + str(resultat[1])
예제 #37
0
def mp():
    return map(int, stdin.readline().split())
예제 #38
0
def st():
    return list(stdin.readline().strip())
예제 #39
0
        for j in range(N):
            exclude_i = rand()%(t) ##### generate random number
            count_profile = profile_sub(dna, count_profile, k, exclude_i, motifs[exclude_i], t-1)
            motifs.pop(exclude_i)
            k_mer = profile_rand_generate_k_mer(dna, count_profile, exclude_i, t+3, n, k)
            count_profile = profile_add(dna, count_profile, k, exclude_i, k_mer, t-1)
            motifs.insert(exclude_i,k_mer)
            score_motifs = score(dna, k, t+4, count_profile)
            if score_motifs<score_bestmotifs:
                best_motif = copy.copy(motifs)
                score_bestmotifs = score_motifs
    
    return best_motif, score_bestmotifs


import copy
from sys import stdin, stdout  
ktn = list(map(int, input().rstrip().split()))
k = ktn[0]
t = ktn[1]
N = ktn[2]
rseed = 0
RAND_MAX = (1 << 31) - 1
DNA = []
for i in range(t):
    dna = str(stdin.readline())
    DNA.append(dna.split('\n')[0])

best_motif, score_bestmotifs = GIBBSSAMPLER(DNA, k, t, N)
for i in range(t):
    stdout.write(str(DNA[i][best_motif[i]:best_motif[i]+k] + '\n'))
예제 #40
0
def inp():
    return int(stdin.readline())
예제 #41
0
from sys import stdin

N = int(stdin.readline())
li = list(map(int, stdin.readline().split()))
li = sorted(li)
S = int(stdin.readline())

first, last = 0, len(li) - 1
answer = 0

while first < last:
    ob = li[first] + li[last]
    if ob == S:
        answer += 1
        first += 1
    elif ob < S:
        first += 1
    else:
        last -= 1

print(answer)
예제 #42
0
    return eq.solve(field,
                    t_range=tfinal,
                    dt=0.1,
                    tracker=storage.tracker(0.1)).data


# Process arguments
if len(argv) != 2:
    stderr.write("Incorrect number of arguments\n".format(argv[0]))
    exit(1)

datafile = str(argv[1])

# Read epsilon and parameters from stdin
#stderr.write("Enter epsilon\n");
epsilon = float(stdin.readline())
ux, udiff, dummy1, dummy2 = [float(num) for num in stdin.readline().split()]

# Run simulation
I = np.zeros(200)  #set the initial condition
I[95:105] = 1.0

simulated50 = integrate(50, ux, udiff, I)
simulated100 = integrate(50, ux, udiff, simulated50)
simulated150 = integrate(50, ux, udiff, simulated100)
simulated200 = integrate(50, ux, udiff, simulated150)
simulated250 = integrate(50, ux, udiff, simulated200)

# Read datafile for observed number of heads
observed = np.loadtxt(datafile)
예제 #43
0
#!/usr/bin/python3

from sys import stdin

for _ in range(3):
    A, B = map(int, stdin.readline().rstrip().split())

    X = A * B

    # greatest_common_divisor
    if A < B:
        tmp = B
        B = A
        A = tmp

    r = A % B
    while r != 0:
        A = B
        B = r
        r = A % B

    print(int(X / B))
예제 #44
0
파일: main.py 프로젝트: ag502/Algorithm
from sys import stdin, setrecursionlimit
setrecursionlimit(10**4)

stdin = open("./input.txt", "r")
num_of_friends, num_of_relations = map(int, stdin.readline().split())
graph = {}
answer = 0

for person in range(num_of_friends):
    graph[person] = []

for _ in range(num_of_relations):
    start, finish = map(int, stdin.readline().split())
    graph[start].append(finish)
    graph[finish].append(start)


def dfs(cur_person, visited, depth):
    visited[cur_person] = True
    global answer

    for next_person in graph[cur_person]:
        if not visited[next_person]:
            dfs(next_person, visited, depth + 1)
        if answer == 1:
            return
    visited[cur_person] = False

    if depth >= 5:
        answer = 1
        return
예제 #45
0
#             cursor -= 1
#             if cursor < 0:
#                 cursor = 0
#         elif ch == '>':
#             cursor += 1
#             if cursor > len(stack):
#                 cursor = len(stack)
#         else:
#             stack.insert(cursor, ch)
#             cursor += 1
#
#     print(''.join(stack))

from sys import stdin

test_case = int(stdin.readline())

for _ in range(test_case):
    L = stdin.readline().strip()
    left = []
    right = []

    for ch in L:
        if ch == '<':
            if left:
                right.append(left.pop())
        elif ch == '>':
            if right:
                left.append(right.pop())
        elif ch == '-':
            if left:
예제 #46
0
파일: 2667.py 프로젝트: MyunDev/Algorithm
from sys import stdin
n = int(input())
# 데이터 저장용 공간 matrix 아파트 있는지 여부를 나타냄
matrix = [[0]*n for _ in range(n)]
# 방문 내역 저장용 visited 같은 0으로 채워진 인접행렬을 만들어서 방문 여부를 판단하는 행렬로 쓰인다.
visited = [[0]*n for _ in range(n)]

# matrix에 아파트 유무 0과 1을 입력해준다.
for i in range(n):
    line = stdin.readline().strip()  #strip은 문자열 제거 함수 파라미터 안에 있는 것을 제거해준다.
    for j, b in enumerate(line):
        matrix[i][j] = int(b)

# 방향 확인용 좌표 dx와 dy
# 중앙을 기준으로 좌/우/위/아래
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
nums = 0 

# DFS 함수 정의
def dfs(x, y, c):
    visited[x][y] = 1   # 방문 여부 표시 방문했음을 visited 매트릭스에 저장해준다.
    global nums           # 아파트 단지 수를 세기위한 변수
    # 아파트가 있으면 숫자를 세어줍니다.
    if matrix[x][y] == 1:
        nums += 1
    # 해당 위치에서 좌/우/위/아래 방향의 좌표를 확인해서 dfs 적용
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < n and 0 <= ny < n: #nx와 ny가 matrix의 범위 내인지 확인 
예제 #47
0
# 출처: https://www.acmicpc.net/problem/2630
# 문제: 색종이 만들기

from sys import stdin

board = [list(map(int, stdin.readline().split())) for _ in range(int(stdin.readline()))]
white = 0
blue = 0


def divide(board):
    global white, blue
    sum_board = sum(sum(board, []))
    size = len(board)
    print(board)
    if size == 1:
        if board[0][0] == 0:
            white += 1
            print('white: ', white)
        else:
            blue += 1
            print('blue: ', blue)
        return
    if sum_board == size ** 2:
        blue += 1
        print('blue: ', blue)
        return
    elif sum_board == 0:
        white += 1
        print('white: ', white)
        return
예제 #48
0
    flyCount = len(flies)
    vecAvg = [float(x) / float(flyCount) for x in vecAvg]
    x1 = vecAvg[0:3]
    x2 = vecAvg[3:]

    #num = vecDot(x1,x1) * vecDot(x2,x2) - vecDot(x1, x2)**2
    #denom = vecDot(x2,x2)

    speedSqr = vecDot(x2, x2)
    if speedSqr == 0:
        t = 0
    else:
        t = -vecDot(x1, x2) / vecDot(x2, x2)
    if t < 0:
        t = 0
    diffv = vecAdd(x1, vecScale(x2, t))
    d = math.sqrt(vecDot(diffv, diffv))

    return (d, t)


cases = int(stdin.readline())

for caseNo in xrange(1, cases + 1):
    flyCount = int(stdin.readline())
    flies = []
    for flyNo in xrange(0, flyCount):
        flies.append([int(x) for x in stdin.readline().strip().split()])
    d, t = compute(flies)
    print "Case #%d: %.8f %.8f" % (caseNo, d, t)
예제 #49
0
from sys import stdin

TestN = int(input())

for _ in range(TestN):
    a, b = map(int, stdin.readline().split())
    print(a + b)
예제 #50
0
파일: 1743.py 프로젝트: jihongeek/Algo

def bfs(row, col):
    visited[row][col] = True
    trash = 1
    q = deque()
    q.append((row, col))
    while len(q) > 0:
        location = q.popleft()
        for newLocation in getLocationsToMove(location):
            newRow, newCol = newLocation
            if not visited[newRow][newCol] and way[newRow][newCol]:
                visited[newRow][newCol] = True
                trash += 1
                q.append((newRow, newCol))
    return trash


h, w, k = map(int, stdin.readline().strip().split())
way = [[False] * w for _ in range(h)]
visited = [[False] * w for _ in range(h)]
trashMax = 0
for _ in range(k):
    trashRow, trashCol = map(int, stdin.readline().strip().split())
    way[trashRow - 1][trashCol - 1] = True
for row in range(h):
    for col in range(w):
        if not visited[row][col] and way[row][col]:
            trashMax = max(trashMax, bfs(row, col))
print(trashMax)
예제 #51
0
# CCC 2010 Senior Problem 3: Firehose
# https://www.cemc.uwaterloo.ca/contests/computing/2010/stage1/seniorEn.pdf

from sys import stdin, stdout

h = int(stdin.readline())
houses = []

for i in range(h):
    houses.append(int(stdin.readline()))

houses.sort()

k = int(stdin.readline())


def hydrants(hoselength, houses):
    diameter = hoselength * 2

    currentHouse = houses[0]
    lastHouse = houses[len(houses) - 1]

    hoseCount1 = 1

    i = 0
    while i < len(houses):
        if houses[i] > diameter + currentHouse and houses[i] <= lastHouse:
            if currentHouse == houses[0]:
                j = len(houses) - 1
                while (1000000 - houses[j]) + houses[i - 1] <= diameter:
                    j -= 1
예제 #52
0
def ask_prompt(text):
    print(text, end=" ", file=stderr)
    stderr.flush()
    reply = stdin.readline().rstrip()
    print("", file=stderr)
    return reply
예제 #53
0
from sys import stdin, stdout

for t in range(int(stdin.readline())):
    c, f, x = map(float, stdin.readline().split())
    m = 0
    time_taken = (x / 2)
    current_rate = 2
    s = 0
    next_possible_time_taken = round((round((c / current_rate), 7) + round(
        (x / (current_rate + f)), 7)), 7)

    #print(next_possible_time_taken)

    while (next_possible_time_taken < time_taken):
        time_taken = next_possible_time_taken
        s += round((c / current_rate), 7)

        current_rate = round(current_rate + f, 7)
        next_possible_time_taken = round(
            s + (round((c / current_rate), 7) + round(
                (x / (current_rate + f)), 7)), 7)
        #print(next_possible_time_taken)

    print('Case #' + str(t + 1) + ': ' + str(time_taken))
예제 #54
0
파일: 4897644.py 프로젝트: qifanyyy/CLCDSA
from functools import reduce
from operator import mul
from sys import stdin
n = int(stdin.readline().rstrip())
al = [int(_) for _ in stdin.readline().rstrip().split()]
m = reduce(mul, al)-1
print(sum(m%a for a in al))
예제 #55
0
def ttf_farm(C, F, X, c, rate):
    t = 0

    if c >= C:
        c -= C
    else:
        t += ttf_no_farm(C, c, rate)
        c = 0

    t += (X - c) / (rate + F)

    return t


T = int(stdin.readline())

for k in xrange(T):
    C, F, X = map(float, stdin.readline().split())

    rate = 2
    time = 0
    cookies = 0

    while cookies < X:
        no_farm = ttf_no_farm(X, cookies, rate)
        farm = ttf_farm(C, F, X, cookies, rate)

        if no_farm <= farm:
            time += no_farm
            cookies = X
예제 #56
0
Output
Number of ways in which you can make given array beautiful.

Input
5
1 4 3 2 5

OUTPUT
10

Total number of ways are (5,1),(4,1),(3,1),(2,1),(5,2),(4,2),(3,2),(5,3),(4,3),(5,4). First number in above pair is A[1] and second number is A[N].Note that two ways are considered same if A[1] and A[N] are same in resulting array after swaps.

"""

from sys import stdin, stdout
n = int(stdin.readline())
arr = [int(x) for x in stdin.readline().rstrip().split()]
q = max(arr)
p = min(arr)
c = []
count = 0
for x in range(0, q + 1):
    c.append(0)
for x in arr:
    if (c[x] == 0):
        count = count + 1
    c[x] = c[x] + 1
sum = 0
for x in range(1, count):
    sum = sum + x
print(sum)
예제 #57
0
#!python3

from sys import stdin, stdout

n = int(stdin.readline())

total = 0
for _ in range(n):
    x = sum(map(int, stdin.readline().strip().split(' ')))
    if x >= 2:
        total += 1
stdout.write(f'{total}\n')
예제 #58
0
from sys import stdin
from jetbot import Robot
import time

robot = Robot()
N, M = map(int, stdin.readline().split())
# matrix 배열
matrix = [stdin.readline().rstrip() for _ in range(N)]
# 방문경로 배열
visited = [[0]*M for _ in range(N)]
# UP/DOWN/LEFT/RIGHT
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
INF = 500
global mindist
mindist = INF
chardir = ['UP', 'DOWN', 'LEFT', 'RIGHT']
# DFS 경로 탐색

# dir : 0, 1, 2, 3
path = []							# Temp path
Track = []							# Real Path
info = []
result = INF
# 0 : 현재 방향 그대로
# 1 : 왼쪽 방향으로 틀기
# 2 : 오른쪽 방향으로 틀기
# 3 : 뒤로 가기
Changedir = [ [0, 3, 1, 2],	[3, 0, 2, 1],[2, 1, 0, 3],[1, 2, 3, 0]]

curdir = 1
예제 #59
0
from sys import stdin

N = int(stdin.readline())
S = [0] + list(map(int, stdin.readline().split()))

# D[i] : S[i]가 마지막인 가장 긴 증가하는 부분 수열의 길이
D = [0 for _ in range(N + 1)]

D[1] = 1

for i in range(2, N + 1):
    D[i] = 1
    for j in range(1, i):
        if S[j] < S[i] and D[j] + 1 > D[i]:
            D[i] = D[j] + 1

print(max(D[1:]))
예제 #60
0
from sys import stdin

d = [0 for _ in range(100000)]

n = int(stdin.readline())
num = list(map(int, stdin.readline().split()))

d[0] = num[0]
ans = d[0]

for i in range(1, n):
    if i == 8:
        here = 0
    if d[i - 1] + num[i] < num[i]:
        d[i] = num[i]
    else:
        d[i] = d[i - 1] + num[i]
    if ans < d[i]:
        ans = d[i]

print(ans)