content stringlengths 7 1.05M |
|---|
def read_matrix():
(rows, columns) = map(int, input().split(" "))
matrix = []
for r in range(rows):
row = input().split(" ")
matrix.append(row)
return matrix, rows, columns
def subsqares_count(matrix,subsquare, rows, columns):
count = 0
for r in range(rows - (subsquare - 1)):
... |
DEBUG = True
APP_DIR = '/home/harish/django_projects/cinepura/'
STATIC_MEDIA_PREFIX = '/static_media/cinepura' |
"""
'pass' or '...' (ellipsis) works as a placeholder for the programmer to write something later
"""
valor = True
if valor:
pass
else:
print('Bye')
print()
if valor:
...
else:
print('Bye')
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:104 ms, 在所有 Python3 提交中击败了64.10% 的用户
内存消耗:14.4 MB, 在所有 Python3 提交中击败了79.35% 的用户
解题思路:
具体实现见代码注释
"""
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
def find(root1, root2): # 两棵树的对应节点
if root1 and root2: # 如果节点都存... |
# MYSQL数据库配置
# 通常在不同环境下配置是不一样的,根据实际情况进行修改
MYSQL_CFG = {
'HOST': '172.17.0.1',
'PORT': 3306,
'USERNAME': 'username',
'PASSWORD': 'password',
'DATABASE': 'database_name'
}
|
def reverse_num(x: int) -> int :
if x == 0:
return 0
else:
num_temp = str(x)
tam = len(num_temp)
num_zeros = 0
if num_temp[0] == "-":
if num_temp[tam - 1] == "0":
dici = {"0": 0}
for value in num_temp[:1:-1]:
... |
class BasicPagination:
items_per_page = 1
max_items_per_page = 100
def __init__(self,
pagination: dict = None,
items_per_page: int = None,
max_items_per_page: int = None):
pagination = pagination or {}
self.page = pagination.get('page', 0)
... |
'''
This problem was recently asked by Apple:
You are given two singly linked lists. The lists intersect at some node. Find, and return the node. Note: the lists are non-cyclical.
Example:
A = 1 -> 2 -> 3 -> 4
B = 6 -> 3 -> 4
This should return 3 (you may assume that any nodes with the same value are the same nod... |
class Solution:
def climbStairs(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
"""
Approach #1:
- use a dp array and a helper function
- pretty intuitive
"""
dp = [-1 for _... |
WELCOME_DIALOG_TEXT = (
"Welcome to NVDA dialog Welcome to NVDA! Most commands for controlling NVDA require you to hold "
"down the NVDA key while pressing other keys. By default, the numpad Insert and main Insert keys "
"may both be used as the NVDA key. You can also configure NVDA to use the Caps Lock as the ... |
# -*- coding: utf-8 -*-
# @Author: Zengjq
# @Date: 2019-02-21 10:16:00
# @Last Modified by: Zengjq
# @Last Modified time: 2019-02-21 10:40:43
# 93%
# 教程 https://time.geekbang.org/course/detail/130-42708
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNo... |
__author__ = "NuoDB, Inc."
__copyright__ = "(C) Copyright NuoDB, Inc. 2019"
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "NuoDB Drivers"
__email__ = "drivers@nuodb.com"
__status__ = "Production"
|
class CurrentChangedEventManager(WeakEventManager):
""" Provides a System.Windows.WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the System.ComponentModel.ICollectionView.CurrentChanged event. """
@staticmethod
def AddHandler(source,handler):
""" A... |
class Color(object):
""" Represents an ARGB (alpha,red,green,blue) color. """
def Equals(self,obj):
"""
Equals(self: Color,obj: object) -> bool
Tests whether the specified object is a System.Drawing.Color structure and is equivalent to this
System.Drawing.Color structure.
... |
class Jaro:
def similarity(self, s, t):
if not s and not t:
return 1
if not s or not t:
return 0
if len(s) > len(t):
s, t = t, s
max_dist = (len(t) // 2) - 1
s_matched = []
t_matched = []
... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Escribe un programa que solicite dos números enteros al usuario y
muestre por pantalla la suma de todos los números enteros que hay
entre los dos números (ambos números incluidos).
Ejemplo:
Introduce el número de inicio: 4
Introduce el número de fin: 8
El... |
class Smartphone:
def gallary(self):
print("Gallary")
def browser(self):
print("Browser")
def app_store(self):
print("App Store")
x = Smartphone()
x.gallary()
x.browser()
x.gallary()
|
class Solution:
"""
@param nums: The number array
@return: Return the single number
"""
def getSingleNumber(self, nums):
n = len(nums)
if n == 1:
return nums[0]
if nums[n // 2] == nums[n - n // 2]:
if n // 2 % 2 == 0:
return se... |
'''
@file ion/core/__init__.py
@mainpage Overview
@section intro Introduction
This is the repository that defines the COI services.
@note Initially, all ION services are defined here and later moved to
subsystem repositories.
COI services are intended to be deployed as part of the ION system launch.
Services are d... |
PATH_IMAGE = "img"
BACKGROUND_IMAGE = 'background'
LOOT_IMAGE = 'point_5'
GHOST_RED_IMAGE = 'ghost_red_30'
GHOST_BLUE_IMAGE = 'ghost_blue_30'
GHOST_PINK_IMAGE = 'ghost_pink_30'
GHOST_ORANGE_IMAGE = 'ghost_orange_30'
FONT_REGULAR = 'couriernew_regular.ttf'
FONT_BOLD = 'couriernew_bold.ttf'
PACMAN_SIZE = (30... |
'''ESTRUTURA DE REPETIÇÃO WHILE, LAÇOS DE REPETIÇÃO (PARTE 2)'''
print('*' * 40, '\nEquanto c < 10 faça:')
c = 0
while c < 10: #Enquanto c < 10 faça:
print(c, end=' ')
c += 1
print('END')
print('*' * 40, '\nEnquanto o valor digitado NÃO for 0 faça:')
n = 1
while n != 0: #condição de PARADA
n = int(input('D... |
"""
# @Time : 2020/9/17
# @Author : Jimou Chen
"""
def T(n):
if n == 1:
return 4
elif n > 1:
return 3 * T(n - 1)
def T(n):
if n == 1:
return 1
elif n > 1:
return 2 * T(n // 3) + n
print(T(5))
|
def v1(ss):
"""
soma de variavel, mas já está declarada
"""
ss += 1
if ss == 100:
try:
input(f"Atingiu {ss} vez!")
# yield ss
return 0
except KeyboardInterrupt:
print('\nObrigado por usar nosso programa teste!')
return -... |
'''
Created on Sat 04/04/2020 11:55:38
99 Bottles of Beer
@author: MarsCandyBars
'''
class BottlesOfBeer():
def __init__(self):
'''
Description:
This method provides attributes for the main lyrics
of the song to make looping cleaner.
Args:
None.
... |
class Library:
def __init__(self, id, books, signup_days, book_p_day):
self.id = id
self.books = books
self.signup_days = signup_days
self.book_p_day = book_p_day
def score(self, books_so_far):
possible_reward = sum([self.books[id] for id in self.books.keys() if id not ... |
#Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values
#and produce an output as shown below. Do ... |
'''
'''
__version__ = '0.1-dev'
device_config_name = 'Devices'
exp_config_name = 'experiment'
|
#
# Copyright 2015 Tickle Labs, Inc.
#
# 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 applicable law or agreed to in w... |
# Python code to demonstrate naive
# method to compute gcd ( Euclidean algo )
def computeGCD(x, y):
while(y):
x, y = y, x % y
return x
a = 60
b= 48
# prints 12
print ("The gcd of 60 and 48 is : ",end="")
print (computeGCD(60,48))
|
__all__ = ['LEAGUE_IDS']
LEAGUE_IDS ={
"BSA": 444,
"PL": 445,
"ELC": 446,
"EL1": 447,
"EL2": 448,
"DED": 449,
"FL1": 450,
"FL2": 451,
"BL1": 452,
"BL2": 453,
"PD": 455,
"SA": 456,
"PPL": 457,
"DFB": 458,
"SB": 459,
"CL": 464,
"AAL": 466
}
"""
更新当前赛季... |
#criando uma classe "Pessoa", que posteriormente será importada ,no
#arquivo "main"
#aonde tem o if deve ser usado soemnte o retun e msg que está escrita
#pois deve haver um método #get para os outros métoods que vão conter ações ou valores
class Pessoa:
#cridndo método connstrutor,e passando parametros para ele ... |
#1.soru
print("katma deger ciro hesaplama")
tsm=int(input("toplam satis miktarinizi giriniz:"))
hm=int(input("hammadde maliyetinizi giriniz:"))
bog=int(input("bakim onarim maliyetinizi giriniz:"))
sg=int(input("sevkiyat giderlerinizi giriniz:"))
sahg=int(input("satin alinan hizmet giderlerinizi giriniz:"))
def k... |
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
if __name__ == '__main__':
solution = Solution()
print(solution.intersection([1, 2,... |
#Programa que diz se ano é bissexto ou não:
ano = int(input('Digite um ano: '))
if ano // 400 and ano % 4 == 0 and ano % 100 != 0 :
print('{} é bissexto'.format(ano))
else:
print('{} não é ano bissexto.'.format(ano))
|
"""Blank file for Python transversal.
This can be deleted or renamed to store the source code of your project.
"""
|
# URI Online Judge 2787
L = int(input())
C = int(input())
if L % 2 == 0:
if C % 2 == 0:
print(1)
else:
print(0)
else:
if C % 2 == 0:
print(0)
else:
print(1) |
'''
Clase que modela una entidad de recomendación, contiene la informacion de automoviles y perfil
'''
class Recommendation:
def __init__(self, id, arrAutomobiles, profile):
self.__id=id
self.__arrAutomobiles=arrAutomobiles
self.__profile=profile
def get_recommendation(self):
da... |
def convert_string_to_int(list_a):
new_list = []
for item in list_a:
num = int(item)
new_list.append(num)
return new_list
str_num_list = input().split(",")
rotate_times = int(input())
int_list = convert_string_to_int(str_num_list)
len_of_list = len(int_list)
val = rotate_times % len_of... |
class User():
"""存储用户信息"""
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print("Hi Welcome "+self.first_name+self.last_name)
def greet_user(self):
print('Welcome ')
my_user = User('he','mm')
my_user.describe_user()
my_user.greet_u... |
class Publisher:
def __init__(self):
self.observers = []
def add(self, observer):
if observer not in self.observers:
self.observers.append(observer)
else:
print('Failed to add: {}'.format(observer))
def remove(self, observer):
try:
self.o... |
Version = "5.6.5"
if __name__ == "__main__":
print (Version)
|
a = int(input('Digite um número para saber sua tabuada :'))
n1 = a*1
n2 = a*2
n3 = a*3
n4 = a*4
n5 = a*5
n6 = a*6
n7 = a*7
n8 = a*8
n9 = a*9
n10 = a*10
print('A sua tabuada é')
print('{} x 1 = {}'.format(a, n1))
print('{} x 2 = {}'.format(a, n2))
print('{} x 3 = {}'.format(a, n3))
print('{} x 4 = {}'.format(a, n4))
pri... |
'''Implements /src/Resource/index.ts'''
class Resource:
''' Enum implemenation '''
class Types:
WOOD = 'wood'
COAL = 'coal'
URANIUM = 'uranium'
def __init__(self, type, amount) -> None:
self.type = type
self.amount = amount
|
class RNNConfig(object):
"""
Holds logistic regression model hyperparams.
:param height: image height
:type heights: int
:param width: image width
:type width: int
:param channels: image channels
:type channels: int
:param batch_size: batch size for training
:type batch_size: in... |
t = int(input())
i=0
while i < t:
st = str(input())
length = len(st)
j = 0
cnt = 0
while j < length:
num = int(st[j])
#print(num)
if num == 4:
cnt = cnt + 1
j=j+1
print(cnt)
i=i+1 |
#
# @lc app=leetcode id=693 lang=python3
#
# [693] Binary Number with Alternating Bits
#
# https://leetcode.com/problems/binary-number-with-alternating-bits/description/
#
# algorithms
# Easy (58.47%)
# Likes: 359
# Dislikes: 74
# Total Accepted: 52.4K
# Total Submissions: 89.1K
# Testcase Example: '5'
#
# Given... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'memconsumer',
'type': 'none',
'dependencies': [
'memconsumer_apk',
],
},
{
... |
# https://leetcode.com/problems/contains-duplicate
class Solution:
def containsDuplicate(self, nums):
hs = set()
for num in nums:
hs.add(num)
return len(hs) != len(nums)
|
class Emitter:
"""This class implements a simple event emitter.
Args:
emitterIsEnabled: enable callbacks execution?
Example usage::
callback = lambda message: print(message)
event = Emitter()
event.on('ready', callback)
event.emit('ready', 'Finished!')
"""
d... |
""" Class to count the inversion count using merge sort"""
class InversionCount:
def count(self, A: [int]) -> [int]:
""" Count and return the array containing the count of each element """
index_array = []
rc_arr = []
for ind in range(0, len(A)):
index_array.append(ind... |
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
class CommentStreamA:
def __init__(self):
self.data = None
@staticmethod
def parse(dir, buff):
csa = CommentStreamA()
buff.seek(dir.Location.Rva)
csa.data = buff.read(dir.Location.DataSize).decode()
return csa
def __str__(self):
return 'Co... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:20:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ... |
for i in range(1,101) :
if(i % 2 != 0):
pass
else:
print(i,"is even number") |
class PriorityQueueBase:
''' abstract base class for a priority queue '''
class _Item:
__slots_ = '_key', '_value'
def __init__(self, k, v):
self._key = k
self._value = v
def __lt__(self, other):
return self._key < other._key
def is_empty(self... |
## Added by Brian Blaylock
## September 30, 2021
"""
! Experimental
This is a special case template for GRIB2 model data that is stored on
your local machine rather than retrieving data from remote sources.
Index files are assumed to be in the same directory as the file with
".idx" appended to the file name. If you d... |
class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# write your code here
l, r = 0, len(A) - 1
while l <= r:
m = (l + r) / 2
if A[m] == target:
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"example_func": "00_core.ipynb",
"process_data": "01_cli.ipynb",
"train": "01_cli.ipynb",
"evaluate": "01_cli.ipynb",
"reproduce": "01_cli.ipynb"}
modules = ["core.py",
... |
class RPGinfo():
author = 'BigBoi'
def __init__(self,name):
self.title = name
def welcome(self):
print("Welcome to " + self.title)
@staticmethod
def info():
print("Made using my amazing powers and Raseberry Pi's awesome team")
@classmethod
def credits(c... |
def previous_answer():
#1.
num1 = int(input("Please enter your number!"))
if num1 % 2 == 0:
print("Your number is EVEN number!")
else:
print("Your number is ODD number!")
#2.
num2 = int(input("Please enter second number!"))
num3 = int(input("Please enter third number!"))
... |
merge_tags = {
"StudyDate": 0x00080020,
"StudyTime": 0x00080030,
"AccessionNumber": 0x00080050,
"ReferringPhysicianName": 0x00080090,
"StudyInstanceUID": 0x0020000D,
"StudyID": 0x00200010,
"Modality": 0x00080060,
# "ModalitiesInStudy": ,
"SeriesInstanceUID": 0x0020000E,
"SeriesNu... |
#!/usr/bin/env python
# encoding: utf-8
"""
entity_list.py
Created by William Makley on 2008-04-02.
Copyright (c) 2008 Tritanium Enterprises. All rights reserved.
"""
def compare_elist(e1, e2):
"""Comparison function for entities."""
sp1 = e1.sorting_priority
sp2 = e2.sorting_priority
if sp1 > sp2:
... |
class Solution:
def find132pattern(self, nums: list) -> bool:
self.nums = nums
self.dp = [[0] * len(nums) for _ in range(len(nums))]
for i in range(len(nums)):
for j in range(len(nums)):
if j >= i + 2:
self.dp[i][j] = -1
return bool(sel... |
"""
This module collects all solvent subclasses for python file and information management with gromos
"""
class Solvent():
"""Solvent
This class is giving the needed solvent infofmation for gromos in an obj.
#TODO: CONFs & TOPO in data
"""
name:str = None
coord_file_path:str = Non... |
APP_V1 = '1.0'
APP_V2 = '2.0'
MAJOR_RELEASE_TO_VERSION = {
"1": APP_V1,
"2": APP_V2,
}
CAREPLAN_GOAL = 'careplan_goal'
CAREPLAN_TASK = 'careplan_task'
CAREPLAN_CASE_NAMES = {
CAREPLAN_GOAL: 'Goal',
CAREPLAN_TASK: 'Task'
}
CT_REQUISITION_MODE_3 = '3-step'
CT_REQUISITION_MODE_4 = '4-step'
CT_REQUISITION... |
'''4. Write a Python program to concatenate elements of a list. '''
num = ['1', '2', '3', '4', '5']
print('-'.join(num))
print(''.join(num)) |
print ("Hello World")
n = int(input("numero: "))
print(type(n))
print(bin(3)) |
def f(arr, t):
# print(t)
N = len(arr)
x0,v0 = arr[0]
l,r = x0 - t*v0, x0 + t*v0
for i in range(1, N):
xi,vi = arr[i]
l1, r1 = xi - t*vi, xi + t*vi
if l1 < l:
(l,r), (l1,r1) = (l1,r1), (l,r)
if l1 > r:
return False
l,r = max(... |
d, m = map(int, input().split())
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday']
sumOfMonths = 0
for i in range(m - 1):
sumOfMonths += month[i]
result = sumOfMonths + d - 1
print(days[result % 7])
|
#
# PySNMP MIB module HM2-PLATFORM-SWITCHING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-PLATFORM-SWITCHING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:19:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
"""3-1. Names: Store the names of a few of your friends in a list called names. Print
each person’s name by accessing each element in the list, one at a time."""
names = ['Reynaldo', 'Horacio', 'Pablo', 'Genesis', 'Angelica']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4]) |
def pytest_addoption(parser):
# Where to find curl-impersonate's binaries
parser.addoption("--install-dir", action="store", default="/usr/local")
parser.addoption("--capture-interface", action="store", default="eth0")
|
#INPUT
lines = open('input.txt').read().split()
dummy = ['forward', '5', 'down', '5', 'forward', '8', 'up', '3', 'down', '8', 'forward', '2']
#FIRST PROBLEM
def problemPart1(data):
horizontal = 0
depth = 0
for i in range(0, len(data), 2):
if data[i] == 'down':
depth += int(data[i+1])
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class HlsColor:
def __init__(self, hue, luminance, saturation):
self.hue = hue
self.luminance = luminance
self.saturation = saturation
def Lighten(self, percent):
self.luminance *= (1.0 + percent)
... |
class DataFile:
def __init__(self, datetime, chart, datafile):
self.Datetime = datetime
self.Chart = chart
self.Datafile = datafile
return |
# -*- coding: utf-8 -*-
def test_get_billing_key(iamport):
invalid_customer_uid = 'invalid_key'
try:
iamport.get_billing_key(invalid_customer_uid)
except iamport.HttpError as e:
assert e.code == 404
assert e.reason == 'Not Found'
valid_customer_uid = 'customer_1234'
res ... |
entries = [
{
'env-title': 'atari-alien',
'env-variant': 'No-op start',
'score': 3166,
},
{
'env-title': 'atari-amidar',
'env-variant': 'No-op start',
'score': 1735,
},
{
'env-title': 'atari-assault',
'env-variant': 'No-op start',
... |
class XMLDeclStrip:
"""
Strip "<?xml" declarations from a stream of data.
This is an ugly work around for several problems.
1. The XML stream comes over TCP, and may be arbitrarily broken up at any
point in time.
2. The Android ATAK client sends every COT Event as a complete XML document
... |
def first_last6(nums):
if nums[0] == 6 or nums[-1] == 6:
return True
else:
return False
def same_first_last(nums):
if len(nums) >= 1 and nums[0] == nums[-1]:
return True
else:
return False
def make_pi():
return [3, 1, 4]
def common_end(a, b):
if a[-1] == b[-1] or a[0] == b[0]:
return ... |
# MenuTitle: Fix Component Order
# -*- coding: utf-8 -*-
__doc__ = """
Searches all glyphs for any component of type 'Mark' at index 0 in the components list, and moves it to the end if found.
"""
Glyphs.clearLog()
Glyphs.font.disableUpdateInterface()
def reportCorrectedComponents(gylyphName, layerName, componentNa... |
data_set = []
# UNix time stamp
PHASE_1 = 1341214200 # before 02-07-2012 01:00:00 PM
PHASE_2 = 1341253799 # After PHASE_1 till 02-07-2012 11:59:59 PM
PHASE_3 = 1341368999 # After PHASE_2 till 04-07-2012 07:59:59 AM
file1 = 0
file2 = 0
file3 = 0
file4 = 0
def extract_in_list():
with open("/home/darkmatter/Do... |
class Solution:
def oddCells(self, n, m, indices):
rows, cols = {}, {}
for r, c in indices:
if r in rows:
rows[r] += 1
else:
rows[r] = 1
if c in cols:
cols[c] += 1
else:
cols[c] = 1
... |
class ZabbixError(Exception):
"""
Base zabbix error
"""
pass
|
# puzzle easy // https://www.codingame.com/ide/puzzle/object-insertion
# needed values
obj, grid, start, sol= [], [], [], []
count_star = 0
# game input()
row_all, cal_all = [int(i) for i in input().split()]
for i in range(row_all): obj.append(input())
c, d = [int(i) for i in input().split()]
for i in range(c): gr... |
def bfs(graph, s):
explored = []
q = [s]
while q:
u = q.pop(0)
for (v, w) in [(v, w) for (v, w) in graph if v == u and w not in explored]:
explored.append(w)
q.append(w)
print(explored)
if __name__ == '__main__':
graph = [('s', 'a'), ('s', 'b'), ('a', 'c'),... |
class Statistics:
def __init__(self):
self.stat={
'python':0,
'sql': 0,
'django': 0,
'rest': 0,
'c++': 0,
'linux': 0,
'api': 0,
'http': 0,
'flask': 0,
'java': 0,
'git': 0,
... |
# 19) 역순 연결 리스트2 (P.237) - leetcode(92)
# 인덱스 m에서 n까지를 역순으로 만들어라. 인덱스 m은 1부터 시작한다.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# 반복 구조로 노드 뒤집기
def reverseBetween(self, head: ListNode, left: int,... |
v1 = int(input('Digite um valor:'))
v2 = int(input('Digite outro valor:'))
re = (v1+v2)
print ('O valor da soma entre {} e {} tem o resultado {}!'.format(v1,v2,re))
|
class Player(object):
"""
Base class for players
"""
def __init__(self, name):
"""
:param name: player's name (str)
"""
self.name = name
def play(self, state):
"""
Human player is asked to choose a move, AI player
decides which move to play.
:param state: Current state of the game (GameState)
"... |
# Generate random rewards for each treatment
if self.action["treatment"] == "1":
self.reward["value"] = np.random.binomial(1,0.5)
else: #Treatment = 2
self.reward["value"] = np.random.binomial(1,0.3)
|
def create_matrix(size):
matrix = []
for _ in range(size):
matrix.append([x for x in input().split()])
return matrix
def find_start(matrix, size):
for r in range(size):
for c in range(size):
if matrix[r][c] == 's':
return r, c
def get_coals_count(matrix, s... |
"""09. Run an object detection model on your webcam
==================================================
This article will shows how to play with pre-trained object detection models by running
them directly on your webcam video stream.
.. note::
- This tutorial has only been tested in a MacOS environment
- Pyt... |
# -*- coding: utf-8 -*-
def main():
a, s = map(int, input().split())
if a >= s:
print('Congratulations!')
else:
print('Enjoy another semester...')
if __name__ == '__main__':
main()
|
'''
Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter
key to indicate that he or she is finished providing inputs. After the user presses the enter key,
the program should print:
The sum of the numbers
The average of the numbers
An example of the pr... |
# you will learn more about superclass and subclass
print("Hello let's start the class")
class parents:
var1 = "one"
var2 = "two"
class child(parents):
# var1 = "one"
# var2 = "two"
var2 = "three"
obj = parents()
cobj = child()
print(obj.var1)
print(obj.var2)
print(cobj.var1)
pri... |
def cal(n):
k=0
while n>0:
k+=(n%10)**5
n//=10
return k
sum=0
for i in range(2,1000000):
if cal(i)==i:
sum+=i
print(sum) |
books_file = 'books.txt'
def create_book_table():
with open(books_file, 'w') as file:
pass # just to make sure the file is there
def get_all_books():
with open(books_file, 'r') as file:
lines = [line.strip().split(',') for line in file.readlines()]
return [
{'name': line[0], 'a... |
def entrance_light(payload):
jval = json.loads(payload)
if("click" in jval and jval["click"] == "single"):
if(lights["Entrance White 1"].on):
lights["Entrance White 1"].on = False
lights["Entrance White 2"].on = False
log.debug("entrance_light> off")
else:
... |
class Solution:
def maxWidthRamp(self, A):
result = 0
if not A:
return result
stack = []
for i, num in enumerate(A):
if not stack or A[stack[-1]] > num:
stack.append(i)
for j in reversed(range(len(A))):
while stack and A[sta... |
# my_list=['honda','honda','bmw','mercedes','bugatti']
# print(my_list.index('honda'))
# print(my_list[0])
# print(my_list.count('honda'))
# my_list.sort()
# print(my_list)
# my_list.pop()
# print(my_list)
# my_list=['honda','honda','bmw','mercedes','bugatti']
# copy_my_list=my_list.copy()
# print(copy_my_list)
# l... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
s = input()
points = [(0, 0)]
x = y = 0
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.