content stringlengths 7 1.05M |
|---|
# 形態素の解析結果格納用
class Morph():
def __init__(self, m_id, line):
self.id = 0 # 形態素のid
self.surface = "" # 形態素の表層
self.pos = "" # 品詞,品詞細分類1,品詞細分類2,品詞細分類3
self.pos1 = ""
self.pos2 = ""
self.pos3 = ""
self.pos4 = ""
self.base = "" # 基本形
self.re... |
def insertShiftArray(arr, value):
mid = len(arr) // 2
new_arr = []
for i in range(0, mid):
new_arr.append(arr[i])
new_arr.append(value)
for i in range(mid, len(arr)):
new_arr.append(arr[i])
return new_arr
test = [1, 2, 3, 4, 5]
print(test)
print(insertSh... |
# Index:
# ----------------------
# 1. General options
# 2. School sites
# 1. General Options
# ======================================================
api_token = "" # the token you took from t.me/botfather
log_channel = "" # insert an id to send features, bugs or errors
super_us... |
"""
callfunc.py
The Frog Programming Language Operation & Keyword: call (func)
Development Leader: @RedoC
"""
class CALLFUNC:
"""
CALLFUNC is the multi class
>> example
run foo(boo)
run print("")
"""
def __init__(self, funcname: str, param: list):
self.funcname = funcname
... |
class Hamming:
def distance(self, first, second):
num_of_errors = 0
if type(first) != str or type(second) != str:
return "Wrong type of strands"
if len(first) != len(second):
return "Strands should be the same length"
for i in range(len(first)):
if... |
"""
2021/06/01 Jeong Choi
Weight, inferenced embedding 을 위한 Path 생성 및 parsing 관련 함수
"""
def parse_weight_path(_path):
print('Loading from :', _path)
weight_folder = _path.split('/')[-2]
weight_file = _path.split('/')[-1] # 'w_ep-%05d_l-%.6f' % (epoch, epoch_loss)
epoch_from = int(weight_file.split('... |
conditons = True
alcool = 0
gas = 0
disel = 0
while conditons :
T = int(input())
if T == 4:
conditons = False;
else:
if T == 1:
alcool +=1
if T == 2:
gas +=1
if T == 3:
disel +=1
print("MUITO OBRIGADO")
print(f"Alcool: {alcool}")
print(... |
def estimator(data):
output = {'data':data, 'impact': {}, 'severeImpact': {}}
output['impact']['currentlyInfected'] = data['reportedCases'] * 10
output['severeImpact']['currentlyInfected'] = data['reportedCases'] * 50
if data['periodType'] == 'weeks':
data['timeToElapse'] = data['timeToElapse'] ... |
# -*- coding: utf-8 -*-
"""Top-level package for Temp Monitor."""
__author__ = """Goncalo Magno"""
__email__ = 'goncalo@gmagno.dev'
__version__ = '0.4.0'
|
class TwitterSearchException(Exception):
"""
This class handles all exceptions directly based on TwitterSearch.
"""
# HTTP status codes are stored in TwitterSearch.exceptions due to possible on-the-fly modifications
_error_codes = {
1000 : 'Neither a list nor a string',
1001 : 'Not a... |
# -*- python -*-
load("@drake//tools/workspace:os.bzl", "determine_os")
def _impl(repository_ctx):
os_result = determine_os(repository_ctx)
if os_result.error != None:
fail(os_result.error)
if os_result.is_macos:
repository_ctx.symlink(
"/usr/local/opt/double-conversion/inclu... |
def linear_search(array, y):
for i in range(len(array)):
if array[i] == y:
return i
return -1
arrSize=int(input("Enter Array Size"))
array=[]
print("Enter Array Elements")
for i in range(arrSize):
array.append(int(input()))
y = int(input("Enter Number you want to find =:... |
name={
'Aaliyah':'',
'Aaron':'',
'Abby':'',
'Abigail':'',
'Ada':'',
'Adalee':'',
'Adaline':'',
'Adalyn':'',
'Adalynn':'',
'Addilyn':'',
'Addilynn':'',
'Addison':'',
'Addisyn':'',
'Addyson':'',
'Adela... |
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
n4 = int(input('Digite o quarto número: '))
n5 = int(input('Digite o quinto número: '))
n6 = int(input('Digite o sexto número: '))
n7 = int(input('Digite o sétimo número: '))
n8 = int... |
γ = 0.5
A -= γ * grad_A
b -= γ * grad_b
C -= γ * grad_C
d -= γ * grad_d
U = relu(A@x+b)
q = softmax(C@U+d)
L = - np.log(q[y])
print("after update, L=", L) |
""" Driver args """
data_path = '/Users/aa56927-admin/Desktop/NLP_Done_Right/sentiment_classification/data/Rotten_Tomatoes/'
output_path = 'test-blind.output.txt'
model = 'RNN' # RNN, FFNN
run_on_test_flag = True
run_on_manual_flag = True
seq_max_len = 60 # also can be computed more systematically looking at length... |
# https://atcoder.jp/contests/abc194/tasks/abc194_b
N = int(input())
job_list = []
a_min_idx, b_min_idx = 0, 0
a_2nd, b_2nd = 0, 0
for i in range(N):
a, b = list(map(int, input().split()))
job_list.append([a, b])
if job_list[a_min_idx][0] > a:
a_2nd = a_min_idx
a_min_idx = i
if job_list[... |
# https://practice.geeksforgeeks.org/problems/get-minimum-element-from-stack/1#
# Approach is to store an array containing stack elements and minEle in separate variable
# For push
# if minEle is None add element to s and assign minEle - element
# if minEle <= element add element to s
# else add 2*x-minEle in s ... |
class ListaMultimedia():
archivos = []
contar = 0
def __init__(self,archivos=[]):
self.archivos = archivos
def agregar(self,p):
self.archivos.append(p)
self.contar += 1
def mostrar(self):
for p in self.archivos:
print(p)
def cantidad(self):
return"""Total de objetos en la lista: {}""".fo... |
# MIT License
#
# Copyright (c) 2017 Matt Boyer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... |
def test_login_redirect(client):
"""
Test that all requests redirect to the login page
"""
URLS = [
"/web-ui/overview/",
"/web-ui/rq/create_sip",
"/api/list-frozen-objects"
]
for url in URLS:
result = client.get(url)
assert result.status_code == 302
... |
# #### We create a function cleanQ so we can do the cleaning and preperation of our data
# #### INPUT: String
# #### OUTPUT: Cleaned String
def cleanQ(query):
query = query.lower()
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(query)
stemmer=[ps.stem(i) for i in tokens]
filtered... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# OpneWinchPy : a library for controlling the Raspberry Pi's Winch
# Copyright (c) 2020 Mickael Gaillard <mick.gaillard@gmail.com>
__version__ = "0.1.0"
|
lst = []
count_of_elements = int(input("How many elements want to store in list?"))
for i in range(count_of_elements):
element = input("Enter the element:")
lst.append(element)
print(lst)
|
"""
ende nose tests
project : Ende
version : 0.1.0
status : development
modifydate : 2015-05-06 19:30:00 -0700
createdate : 2015-05-05 05:36:00 -0700
website : https://github.com/tmthydvnprt/ende
author : tmthydvnprt
email : tmthydvnprt@users.noreply.github.com
maintainer : tmthydvnprt
license ... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = []
one_hot = {}
for word in strs:
mapping = [0 for _ in range(26)]
for char in word:
representation = ord(char)
mapping[representation % 26] += 1
... |
# -*- coding: utf-8 -*-
__author__ = 'Tommy Stallings'
__email__ = 'tommy.stallings2@gmail.com'
__version__ = '1.0'
|
def GetChargeLevel():
return {'data': 42, 'error': 'NO_ERROR'}
def GetBatteryTemperature():
return {'data': 25.4, 'error': 'NO_ERROR'}
def GetBatteryVoltage():
return {'data': 3111, 'error': 'NO_ERROR'}
def GetBatteryCurrent():
return {'data': 800, 'error': 'NO_ERROR'}
def GetIoVoltage():
re... |
print ("Digite uma sequência de números terminada por zero.")
soma = 0
valor = 1
while valor != 0:
valor = int(input("Digite o valor a ser somado: "))
soma = soma + valor
print("A soma da sequência é ", soma) |
def message_replier(messages):
for message in messages:
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
return
if userid in messanger_list:
bot.reply_to(message, MESSANGER_LEAVE_MSG, parse_mode="Markdown")
messanger_lis... |
"""
import time
import redis
from flask import render_template, request, current_app, jsonify, redirect, session
from init import app
from utils.interceptors import loginOptional, jsonRequest, loginRequiredJSON
from utils.jsontools import *
from utils.logger import log
from scraper.video import dispatch... |
average = float(input('Média no semestre: '))
absence = int(input('Frequência no semestre: '))
diff_average = 6 - average
diff_absence = 75 - absence
if average >= 6 and absence >= 75:
print(f'Conceito: aprovado')
if average < 6 and absence >= 75:
print(f'Conceito: exame especial')
print(f'Justificativa: mé... |
# -*- coding: utf-8 -*-
info = {
"%spellout-cardinal-feminine": {
"0": "null;",
"1": "ein;",
"2": "tvær;",
"3": "tríggjar;",
"4": "fýre;",
"(5, 19)": "=%spellout-cardinal-masculine=;",
"(20, 29)": "tjúgo[>>];",
"(30, 39)": "tríati[>>];",
"(40... |
print("dame un número")
numero1=input()
print ("dame otro número")
numero2=input()
print (numero1,numero2)
print("dame tu nombre")
nombre=input()
print("dame tu apellido paterno")
apellidopaterno=input()
print("dame tu apellido materno")
apellidomaterno=input()
print(nombre,apellidopaterno,apellidomaterno)
print(nomb... |
def maior_E_menor(x, y):
if x > y:
return x, y
return y, x
x = int(input())
y = int(input())
if(x == y):
print("0")
else:
maior, menor = maior_E_menor(x, y)
soma = 0
menor +=1
while(menor < maior):
if menor % 2 != 0:
soma += menor
menor += 1
print(s... |
# TODO: Use a real tree structure
class ElsterXmlTreeNode(object):
"""
Our representation of the Elster XML data structure.
A Node can have a name and subelements.
Additionally, some nodes can be repeated and can be specific for one person.
"""
def __init__(self, name, sub_elements,... |
def match(key, value):
return {"match": {key: value}}
def exists(field):
return {"exists": {"field": field}}
def add_to_dict(dict, key, value):
dict.update({key: value})
def build_more_like_this_query(count, content, language):
query_body = {"size": count, "query": {"bool": {}}} # initial empty q... |
# Want to extract domain hotmail.com
data = 'From ritchie_ng@hotmail.com Tues May 31'
at_position = data.find('@')
print(at_position)
space_position = data.find(' ', at_position)
# Starting from at_position, where's the next space
print(space_position)
host = data[at_position + 1: space_position]
print(host) |
def stable_sorted_copy(alist, _indices=xrange(sys.maxint)):
# the 'decorate' step: make a list such that each item
# is the concatenation of sort-keys in order of decreasing
# significance -- we'll sort this auxiliary-list
decorated = zip(alist, _indices)
# the 'sort' step: just builtin-sort the au... |
def wellbracketed(s):
c=0
for i in range(0, len(s)):
if s[i] == "(":
c = c + 1
elif s[i] == ")":
c = c - 1
if c == 0:
return(True)
else:
return(False) |
INSERT_SQL = """
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', 'public', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_mess... |
class UCOMIMoniker:
""" Use System.Runtime.InteropServices.ComTypes.IMoniker instead. """
def BindToObject(self, pbc, pmkToLeft, riidResult, ppvResult):
"""
BindToObject(self: UCOMIMoniker,pbc: UCOMIBindCtx,pmkToLeft: UCOMIMoniker,riidResult: Guid) -> (Guid,object)
Uses the moniker t... |
medida = float(input("Uma distância em metros: "))
km = medida /1000
hm = medida /100
dam = medida /10
dm = medida *10
cm = medida*100
mm = medida *1000
print("A distância de {}m corresponde a\n {}km\n {}hm\n {}dam\n {}dm\n {}cm\n {}mm ".format(medida , km, hm, dam, dm, cm, mm))
|
score = int(input("성적을 입력하시오: "))
credit = 'F'
if score >= 90 :
credit = 'A'
elif score >= 80 :
credit = 'B'
elif score >= 70 :
credit = 'C'
elif score >= 60 :
credit = 'D'
print(f'{credit}학점입니다.') |
# https://www.tutorialspoint.com/python_data_structure/python_binary_tree.htm
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, data):
if self.data:
if data < self.data:
if not sel... |
#!/usr/bin/env python3
# Get superior triangular matrix a)
n = 3
A = [[1, 1/2, 1/3], [1/2, 1/3, 1/4], [1/3, 1/4, 1/5]]
b = [-1, 1, 1]
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i+1, n):
times = A[j][i]
b[j] -= times * b[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###
# Name: Benjamin Seeley
# Student ID: 2262810
# Email: seele105@mail.chapman.edu
# Course: PHYS220/MATH220/CPSC220 Fall 2018
# Assignment: CW03
###
"""Contains helper functions that return lists of sequences.
"""
def fibonacci(n):
"""Returns n fibonacci numbers
... |
class CustomerAddWebsitePermissionDenied(Exception):
pass
class ObjectDoesNotExist(Exception):
pass
|
soma = 0
vezes = 0
for c in range(1, 501):
if (c % 2 == 1):
if (c % 3 == 0):
soma += c
vezes += 1
print('A soma de todos os {} valores solicitados é {}'.format(vezes, soma))
|
"""
Handle
A wrapper meant to collect the python object belonging to a blizzard 'handle'.
"""
class Handle:
handles = {}
def __init__(self, handle):
# constructorfunc can be a function that returns a handle, or a handle directly
self._handle = handle
if Handle.get(handle) != N... |
#!/bin/python3
def main(person_list):
users = []
for name, email in person_list:
if email.endswith('@gmail.com'):
users.append(name)
print(*sorted(users), sep='\n')
if __name__ == '__main__':
N = int(input())
persons = []
for N_itr in range(N):
firstName, emailID ... |
# basic example
class MetaSpam(type):
# notice how the __new__ method has the same arguments
# as the type function we used earlier.
def __new__(metaclass, name, bases, namespace):
name = 'SpamCreateByMeta'
bases = (int,) + bases
namespace['eggs'] = 1
return type.__new... |
"""
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
... |
S = input()
for i in range(len(S)):
print(i + 1)
|
def c_to_f(c):
Farhenheite=(c*9/5)+32
return Farhenheite
n=int(input("Celcius="))
f=c_to_f(n)
print(f,"'F")
|
"""
Write a function that returns the lesser of two given numbers if both numbers are even,
but returns the greater if one or both numbers are odd.
Example 1:
lesser_of_two_evens(2, 4) output: 2
explanation:
the two parameters 2 and 4 are even numbers, therefore, we'll return the smallest even number
Example 2:
les... |
class QueueOverflow(BaseException):
pass
# Node of a doubly linkedlist
class Node:
# constructor
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
# method for setting the data field of the node
def setData(self, data):
self.data = d... |
#!/usr/bin/python
'''
Copyright 2016 Aaron Stephens <aaron@icebrg.io>, ICEBRG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by app... |
text = """
//------------------------------------------------------------------------------
// Explicit instantiation.
//------------------------------------------------------------------------------
#include "Geometry/Dimension.hh"
#include "GSPH/Limiters/SuperbeeLimiter.cc"
namespace Spheral {
template class Super... |
class ProfilePage:
BACK_TO_USERS = "Back to members"
EDIT_USER_BUTTON = "Change role"
USER_EMAIL = "Email"
USER_FIRST_NAME = "First name"
USER_LAST_NAME = "Last name"
USER_ROLE = "Role"
USER_STATUS = "Status"
USER_PENDING = "Pending"
USER_DEACTIVATE = "Deactivate member"
USER_REA... |
'''Program to find the factorial of a number using recursion'''
def factorial_of_a_number(n):
if n<=1:
return 1
else:
return n * factorial_of_a_number(n-1)
#Taking number from user and passing it to the function
n = int(input())
print(factorial_of_a_number(n)) |
class EN:
START_TEXT = """
Hello {},
I am ROBOT.
"""
|
def dec_to_bin(n):
if n < 0:
return bin(n * -1)[2:]
return bin(n)[2:]
def trim_to(number, length):
zeroes = ''
for i in range(int(length) - len(number)):
zeroes += '0'
return zeroes + number
def bit_not(number):
negated = ''
for bit in number:
if bit == '1':
negated += '... |
def printSet(set):
sorted(set)
print('{', end=" ")
for x in set :
print(x, end=" ")
print('}')
def main():
a = set("Hi There, Raghuram")
b = set("Hello, Nice to Meet you")
x = set('hello')
y = set('world')
printSet(a)
printSet(b)
printSet(x - y )
if __name__ == "__... |
with open('input.txt') as f:
lines = [int(i) for i in f.readlines()]
depth_increased = 0
for i in range(0, len(lines) - 3):
last_sum = sum(lines[i-1:i+2])
current_sum = sum(lines[i:i+3])
if (current_sum > last_sum):
depth_increased = depth_increased + ... |
"""
Datos de entrada
trabajador-->nombre-->str
horas trabajadas-->ht-->float
precio por hora-->ph-->float
horas extra-->hx-->float
precio hora extra-->phx-->float
Deducciones-->d-->float
paro forzoso->pf-->float
política habitacional-->polh-->float
caja de ahorro-->ch-->float
Asignaciones-->a-->float
actualización acad... |
# https://leetcode.com/problems/missing-number/description/
# Time: O(n) ~ O(n^2)
# Space: O(n)
# Given a string array words, find the maximum value of
# length(word[i]) * length(word[j]) where the two words
# do not share common letters. You may assume that each
# word will contain only lower case letters. If no such... |
class Bye:
def __init__(self):
self.foo = 'bar'
def is_hello(self):
return type(self) == Hello
class Hello:
def __init__(self):
self.value = 'foobar'
print(Bye().is_hello())
|
# Leetcode 70. Climbing Stairs
#
# Link: https://leetcode.com/problems/climbing-stairs/
# Difficulty: Easy
# Solution using DP
# Complexity:
# O(N) time | where N represent the number of steps of the staircase
# O(1) space
class Solution:
def climbStairs(self, n: int) -> int:
one, two = 1, 1
... |
## Set to display confirmation dialog on exit. You can always use 'exit' or
# 'quit', to force a direct exit without any confirmation.
c.JupyterConsoleApp.confirm_exit = False
## Whether to display a banner upon starting the QtConsole.
c.JupyterQtConsoleApp.display_banner = False
## Start the console window with the... |
#66: Compute a Grade Point Average
a={'A+':4.0,'A':4.0,'A-':3.7,'B+':3.3,'B':3.0,'B-':2.7,'C+':2.3,'C':2.0,'C-':1.7,'D+':1.3,'D':1.0,'F':0}
add=lambda x,y:x+y
c=0
d=0
while True:
b=input("Enter the grade:")
if b=="":
break
c=add(c,a[b])
d+=1
print("Average grade point:",c/d)
|
"""
Given two arrays, write a function to compute their intersection.
Note:
- Each element in the result must be unique.
- The result can be in any order.
link: https://leetcode.com/problems/intersection-of-two-arrays/
"""
class Solution(object):
def intersection(self, nums1, nums2):
"""
F... |
def test_mining_property_tester(web3_tester):
web3 = web3_tester
assert web3.eth.mining is False
def test_mining_property_ipc_and_rpc(web3_empty, wait_for_miner_start,
skip_if_testrpc):
web3 = web3_empty
skip_if_testrpc(web3)
wait_for_miner_start(web3)
a... |
# #072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
# # Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
# n = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'oze', 'tr... |
class Solution:
def checkIfExist(self, arr):
exists = {}
for num in arr:
if (num * 2) in exists or ((num / 2) in exists and num % 2 == 0):
return True
exists[num] = True
return False |
#input
# 637 3371 327 67 924 968 2 6 6 77 5464 21813 70 5 67 74225 46 2 310 6156 50 4 623 87675 1702 3947 4927 9628 7 510 31 65 3321 23993 8406 88 -1
array = [int(x) for x in input().split()]
array.remove(-1)
swaps = 0
for i in range(0, len(array) - 1):
if array[i] > array[i+1]:
swaps += 1
t = array[i]
... |
DEBUG = True
|
# Write a program that reads a word and prints the number of syllables in the word.
# For this exercise, assume that syllables are determined as follows: Each sequence of
# adjacent vowels a e i o u y , except for the last e in a word, is a syllable. However, if
# that algorithm yields a count of 0, change it to 1. F... |
# Maximum number of images to keep in the database
MAX_FILES = 20
# Size of a JPEG minimum coded unit (MCU)
BLOCK_SIZE = 16
# Images will be resized to this width
IMAGE_WIDTH = 1200
# Image aspect ratio
ASPECT_RATIO = 3
|
# Source: https://leetcode.com/problems/contains-duplicate-iii/
# Better approach; Current time complexity: O(n * k)
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t == 0 and len(set(nums)) == len(nums):
return False
for i i... |
response = sm.sendAskYesNo("Are you sure you want to leave?")
# sm.sendSay("Response was " + str(response) + "\r\rAnswer was " + str(answer))
if response:
sm.clearPartyInfo(401060000)
sm.dispose()
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class IndexingPolicy(object):
"""Implementation of the 'IndexingPolicy' model.
Specifies settings for indexing files found in an Object
(such as a VM) so these files can be searched and recovered.
This also specifies inclusion and exclusion rule... |
VISIT_DETAIL_FORM_CONSTANTS = {
'visit_date':{
'max_length': 100,
"data-dojo-type": "dijit.form.DateTextBox",
"data-dojo-props": r"'required' :true"
},
'op_surgeon':{
'max_length': 100,
"data-dojo-type": "dijit.form.Select",
... |
def _merge_mro(seqs):
res = []
i = 0
while 1:
nonemptyseqs = [seq for seq in seqs if seq]
if not nonemptyseqs:
return res
i += 1
for seq in nonemptyseqs:
cand = seq[0]
nothead = [s for s in nonemptyseqs if cand in s[1:]]
if nothead:
cand = None
else:
break
if not ca... |
def Skew(Genome):
res = [0]
for nuc in Genome:
to_app = res[-1]
if nuc == 'C':
to_app -= 1
elif nuc == 'G':
to_app += 1
res.append(to_app)
return res
def MinimumSkew(Genome):
min_val = 0
current_val = 0
min_pos = [0]
for i, nuc in enumerate(Genome):
if nuc == 'C':
current_val -= 1
elif nuc ... |
load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path", "action_config", "tool")
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
def _impl(ctx):
tool_paths = [
tool_path(
name = "gcc",
path = "wrapper_cc.sh",
),
tool_path(
... |
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from source")
for node in range(self.V):
print(node, "\t", dist[node])
... |
# Colors.
white = '\033[97m'
green = '\033[92m'
red = '\033[91m'
yellow = '\033[93m'
# Symbols.
info = '\033[93m[!]\033[0m'
failure = '\033[91m[x]\033[0m'
success = '\033[92m[✓]\033[0m'
# Text modifiers.
def bold(t):
return str('\033[1m%s\033[0m' % t)
def italics(t):
return str('\033[3m%s\033[0m' % t)
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 02. 文字列を交互に呼び出して結合する
p = "パトカー"
t = "タクシー"
print("".join([a + b for a, b in zip(p, t)]))
|
def setup_animation():
init_figure()
for line in lines:
self.line = self.mplCanvas.canvas.ax.plot([], [], [])
self.stopped = False |
def count_substring(string, sub_string):
# Init counter
counter = 0
# Find first index
ind = string.find(sub_string)
# Iterate over string
for i in string:
# If not found, return counter
if ind == -1:
return counter
else:
# Increment counter
... |
# MIT License
#
# Copyright (c) 2021 [FacuFalcone]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... |
def main() :
lstFriends = ("sharjeel", "GOPESH PANDEY", "Rupak")
print(lstFriends)
#Return the item in position 1
print(lstFriends[1])
#Tuples are unchangeabl: Once a tuple is created, you cannot change its values.
#lstFriends[1] = "AFFAN"
# The values will remain the same:
print(lstFriends)
#Use For l... |
s = input()
if s[0:3] == 'KIH':
s = 'A'+s
elif s[0:4] != 'AKIH':
print('NO')
exit(0)
if s[4:5] == 'B':
s = s[0:4]+'A'+s[4:]
elif s[4:6] != 'AB':
print('NO')
exit(0)
if s[5:7] == 'BR':
s = s[0:6]+'A'+s[6:]
elif s[5:7] != 'BA':
print('NO')
exit(0)
if (s[7:9] == 'RA' and len(s) == 9... |
def main():
file = open('6.txt')
banks = []
for line in file:
cells = [int(i) for i in line.split()]
banks.extend(cells)
all_banks = []
while banks not in all_banks:
all_banks.append(banks.copy())
i, m = max(enumerate(banks), key=lambda x: x[1])
banks[i] = 0
... |
def get_key(x, y):
return str(x)+"-"+str(y)
#input_line = input("Enter input:\n")
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
x = 0
y = 0
present_locations = {}
present_locations[get_key(x,y)]=1
for c in input_line:
if c == ">":
x += 1
elif c == "<":
x -= 1
elif c ==... |
class PersegiPanjang(object) :
def __init__(self,p,l) :
self.panjang = p
self.lebar = l
def hitungLuas(self) :
return self.panjang * self.lebar
def cetakLuas(self) :
print('Panjang : ',self.panjang)
print('Lebar : ',self.lebar)
print('Luas : ',self.hitungLuas())
def main() :
test = Per... |
#this code gives the numbers of integers, floats, and strings present in the list
a= ['Hello',35,'b',45.5,'world',60]
i=f=s=0
for j in a:
if isinstance(j,int):
i=i+1
elif isinstance(j,float):
f=f+1
else:
s=s+1
print('Number of integers are:',i)
print('Number of Floats are:',f)
prin... |
while True:
a, b = map(int, input().split())
if a == 0 and b == 0: break
print("Yes" if (a > b) else "No")
|
# initialize the compass points
NORTH, EAST, SOUTH, WEST = range(4)
class CompassPoints(object):
"""
initialize the class to have a default compass bearing of NORTH
left method subtracts a 'co-ordinate' point from the x axis
right method moves the robot +1 co-ordinate along the x-axis
"""
com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.