content stringlengths 7 1.05M |
|---|
""" First class definition"""
class Cat:
pass
class RaceCar:
pass
cat1 = Cat()
cat2 = Cat()
cat3 = Cat() |
# We can transition on native options using this
# //command_line_option:<option-name> syntax
_BUILD_SETTING = "//command_line_option:test_arg"
def _test_arg_transition_impl(settings, attr):
_ignore = (settings, attr)
return {_BUILD_SETTING: ["new arg"]}
_test_arg_transition = transition(
implementation ... |
balance = 700
papers=[100, 50, 10, 5,4,3,2,1]
def withdraw(balance, request):
if balance < request :
print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance))
else:
print ('your balance >>', balance)
orgnal_request = request
while request > ... |
x = float(input('Qual o valor da casa que quer comprar? '))
y = int(input("em quantos anos quer comprar a casa? "))
z = int(input("Qual seu salario? "))
w = y*12
if x / w > (z/100)*30:
print("Voce não pode comprar a casa")
else:
print('Voce pode comprar a casa a parcela é de {:.2f}'.format(x/y))
|
"""Top-level package for Feature Flag Server SDK."""
__author__ = """Enver Bisevac"""
__email__ = "enver@bisevac.com"
__version__ = "0.1.0"
|
arr_1 = ["1","2","3","4","5","6","7"]
arr_2 = []
for n in arr_1:
arr_2.insert(0,n)
print(arr_2)
|
"""Top-level package for z2z Metadata analysis."""
__author__ = """Isthmus // Mitchell P. Krawiec-Thayer"""
__email__ = 'project_z2z_metadata@mitchellpkt.com'
__version__ = '0.0.1'
|
class Player(object):
"""Player class
Attributes:
name (str): Player name
"""
def __init__(self, name):
"""Initialize player
Args:
name (str): Player name
"""
self.name = name
def place_troops(self, board, n_troops):
"""Plac... |
n=int(input("Nhap vao mot so:"))
d=dict()
for i in range(1, n+1):
d[i]=i*i
print(d) |
#!/usr/bin/env python
# Copyright 2008-2010 Isaac Gouy
# Copyright (c) 2013, 2014, Regents of the University of California
# Copyright (c) 2017, 2018, Oracle and/or its affiliates.
# All rights reserved.
#
# Revised BSD license
#
# This is a specific instance of the Open Source Initiative (OSI) BSD license
# template h... |
# Problem: Student Attendance Record I
# Difficulty: Easy
# Category: String
# Leetcode 551: https://leetcode.com/problems/student-attendance-record-i/#/description
# Description:
"""
You are given a string representing an attendance record for a student.
The record only contains the following three characters:
'A' : ... |
#2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
time = int(input("Введите время в секундах "))
hours = time // 3600
minutes = (time - hours * 3600) // 60
seconds = time - (hours * 3600 + minutes * 60)
print... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: missingdata.py
#
# Tests: missing data
#
# Programmer: Brad Whitlock
# Date: Thu Jan 19 09:49:15 PST 2012
#
# Modifications:
#
# ------------------------------------------------------------... |
n1 = int(input('Digite um número entre 0 e 9999: '))
u = n1 // 1 % 10
d = n1 // 10 % 10
c = n1 // 100 % 10
m = n1 // 1000 % 10
print(f'Analisando o número {n1}')
print(f'unidade: {u}')
print(f'dezena: {d}')
print(f'centena: {c}')
print(f'milhar: {m}')
|
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
# %%
class Solution:
def twoSum(self, nums, target):
S = set(nums)
for num in S:
pre = ... |
class SerialNumber:
def __init__(self, serialNumber):
if not (len(serialNumber) == 6):
raise ValueError('Serial Number must be 6 digits long')
self._serialNumber = serialNumber
def __str__(self):
return 'S/N: {}'.format(self._serialNumber)
def __repr__(self):
... |
#
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2012 Intel Corporation
#
# Authored by Shane Wang <shane.wang@intel.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundat... |
'''input
4 8 3
4
5
6
7
8
3 8 2
3
4
7
8
2 9 100
2
3
4
5
6
7
8
9
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == '__main__':
a, b, k = list(map(int, input().split()))
if (b - a + 1) <= 2 * k:
for i in range(a, b + 1):
... |
class Authenticator(object):
def authenticate(self, credentials):
raise NotImplementedError()
|
class Node():
def __init__(self, id: int, value = None, right: 'Node' = None, left: 'Node' = None):
self.id = id
self.value = value
self.right = right
self.left = left
self.parent: 'Node' = None
def add(self, node: 'Node'):
if not node:
raise ValueE... |
"""Module docstring!"""
a = 1
b = 2
@bleh
@blah
def greet(
name: str,
age: int,
*args,
test='oh yeah',
**kwargs
) -> ({a: 1, b: 2}
):
"""Generic short description
Longer description of this function that does nothing
:param arg1: Desc for arg1
:type arg1: arg1_type
:r... |
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] + [2 ** 31 - 1] * amount
for i in xrange(1, amount + 1):
for coin in coins:
if i >= coin and dp[i - c... |
# -*- coding: utf-8 -*-
__author__ = 'lundberg'
class EduIDGroupDBError(Exception):
pass
class VersionMismatch(EduIDGroupDBError):
pass
class MultipleReturnedError(EduIDGroupDBError):
pass
class MultipleUsersReturned(MultipleReturnedError):
pass
class MultipleGroupsReturned(MultipleReturnedEr... |
"""
Basic type definitions.
"""
|
""" Ingest Package Config """
# The list of entities that will be loaded into the target service. These
# should be class_name values of your target API config's target entity
# classes.
target_service_entities = [
"family",
"participant",
"diagnosis",
"phenotype",
"outcome",
"biospecimen",
... |
string_input = "amazing"
vowels = "aeiou"
answer = [char for char in string_input if char not in vowels]
print(answer)
|
class Nodo:
elemento = None
Siguiente = None
def __init__(self, elemento, siguiente):
self.elemento = elemento
self.Siguiente = siguiente
class Pila:
tamano = 0
top = None
def apilar(self, elemento):
"""
Agrega un elemento al tope de la pila
:param e... |
class Solution(object):
def deleteDuplicates(self, head):
initial = head
while head:
if head.next and head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
head = initial
return head
|
# set random number generator
np.random.seed(2020)
# initialize step_end and v
step_end = int(t_max / dt)
v = el
t = 0
with plt.xkcd():
# initialize the figure
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel(r'$V_m$ (V)')
# loop for step_end steps
for step in range(s... |
#author SANKALP SAXENA
def arrays(arr):
arr.reverse()
l = numpy.array(arr, float)
return l
|
def get_ts_struct(ts):
y=ts&0x3f
ts=ts>>6
m=ts&0xf
ts=ts>>4
d=ts&0x1f
ts=ts>>5
hh=ts&0x1f
ts=ts>>5
mm=ts&0x3f
ts=ts>>6
ss=ts&0x3f
ts=ts>>6
wd=ts&0x8
ts=ts>>3
yd=ts&0x1ff
ts=ts>>9
ms=ts&0x3ff
ts=ts>>10
pid=ts&0x3ff
return y,m,d,hh,mm,ss,wd,yd,ms,pid
|
class DispositivoEntrada:
def __init__(self, marca, tipo_entrada):
self._marca = marca
self.tipo_entrada = tipo_entrada
|
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... |
c = float(input("Enter Amount Between 0-99 :"))
print(c // 20, "Twenties")
c = c % 20
print(c // 10, "Tens")
c = c % 10
print(c // 5, "Fives")
c = c % 5
print(c // 1, "Ones")
c = c % 1
print(c // 0.25, "Quarters")
c = c % 0.25
print(c // 0.1, "Dimes")
c = c % 0.1
print(c // 0.05, "Nickles")
c = c % 0.05
print(c // 0.01... |
class Cita:
def __init__(self,id,solicitante,fecha,hora,motivo,estado,doctor):
self.id = id
self.solicitante = solicitante
self.fecha = fecha
self.hora = hora
self.motivo = motivo
self.estado = estado
self.doctor = doctor
def getId(self):
... |
#! /usr/bin/env python
# Copyright (c) 2017, Cuichaowen. All rights reserved.
# -*- coding: utf-8 -*-
# ops helper dictionary
class Dictionary(object):
"""
Dictionary for op param which needs to be combined
"""
def __init__(self):
self.__dict__ = {}
def set_attr(self, **kwargs):
... |
"""Kata: Find the Duplicated Number in a Consecutive Unsorted List - Finds and returns
the duplicated number from the list
#1 Best Practices Solution by SquishyStrawberry
def find_dup(arr):
return (i for i in arr if arr.count(i) > 1).next()
"""
def find_dup(arr):
"""This will find the duplicated int in the ... |
class Calculator:
def add(self,a,b):
return a+b
def subtract(self,a,b):
return a-b
def multiply(self,a,b):
return a*b
def divide(self,a,b):
return a/b
|
"""
This package contains modules built specifically for the project in question.
Below are decribed the modules and packages used in the notebooks of this project.
Modules
-----------
polynomials:
| This module groups functions and classes for generating polynomials
| whether fitting data or directly ortogonal ... |
start = '''You wake up one morning and find yourself in a big crisis.
Trouble has arised and your worst fears have come true. Zoom is out to destroy
the world for good. However, a castrophe has happened and now the love of
your life is in danger. Which do you decide to save today?'''
print(start)
done = False
... |
{'application':{'type':'Application',
'name':'codeEditor',
'backgrounds': [
{'type':'Background',
'name':'bgCodeEditor',
'title':'Code Editor R PythonCard Application',
'size':(400, 300),
'statusBar':1,
'visible':0,
'style':['resizeable'],
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class TimexRelativeConvert:
@staticmethod
def convert_timex_to_string_relative(timex):
return ''
|
#!/bin/python3
h = 0
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
if n%2 == 1:
h = 2 ** (int(n/2) + 2) - 2
elif n%2 == 0:
h = 2 ** (int(n/2) + 1) - 1
print(h) |
#print ("Hello World")
#counties=["Arapahoes","Denver","Jefferson"]
#if counties[1]=='Denver':
# print(counties[1])
#counties = ["Arapahoe","Denver","Jefferson"]
#if "El Paso" in counties:
# print("El Paso is in the list of counties.")
#else:
# print("El Paso is not the list of counties.")
#if "Arapahoe" in ... |
#first exercise
#This code asks the user for hours and rate for hour, calculate total pay and print it.
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
pay = float(hrs) * float(rate)
print("Pay:", pay)
#second exercise
#This code asks the user for hours and rate for hour, calculate total pay and print... |
ANGULAR_PACKAGES_CONFIG = [
("@angular/animations", struct(entry_points = ["browser"])),
("@angular/common", struct(entry_points = ["http/testing", "http", "testing"])),
("@angular/compiler", struct(entry_points = ["testing"])),
("@angular/core", struct(entry_points = ["testing"])),
("@angular/forms... |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[] ,enemy_description=[] ):
self.number = number
self.name = name
self.worl... |
"""
Utility functions.
"""
def load_tf_names(path):
"""
:param path: the path of the transcription factor list file.
:return: a list of transcription factor names read from the file.
"""
with open(path) as file:
tfs_in_file = [line.strip() for line in file.readlines()]
return tfs_in_... |
class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self,tUsername,iUsername,email,sUsername):
self.tUsername=tUsername
self.iUsername=iUsername
self.email=email
self.sUsername=sUsername
def save_user(self):
Us... |
# faça um programa que mostre a tabuada de varios numeros
# um de cada vez, para cada valor digitado
# o programa sera interrompido quando for solicityado um numero negativo
while True:
multiplicado = int(input('Digite um numero para ver sua tabuada: '))
for tab in range(1, 11):
print(f'{multiplicado}x... |
#多分支结构
score=int(input('请输入成绩'))
#判断
if score>=90 and score<=100:
print('A')
elif score>=80 and score<=89:
print('B')
elif score>=70 and score<=79:
print('C')
elif score>=60 and score<=69:
print('D')
elif score>=0 and score<=59:
print('E')
else:
print('无效') |
# -*- coding: utf-8 -*-
r"""
================================================================
Morphing source estimates: Moving data from one brain to another
================================================================
Morphing refers to the operation of transferring
:ref:`source estimates <sphx_glr_auto_tutorial... |
load("//flatbuffers/internal:string_utils.bzl", "capitalize_first_char")
def _include_args_from_depset(includes_depset):
# Always include the workspace root.
include_args = ["-I", "."]
for include in includes_depset.to_list():
include_args.append("-I")
include_args.append(include)
retur... |
"""Top-level package for Calendário dos Vestibulares do Brasil."""
__author__ = """Ana_Isaac_Marina"""
__email__ = 'marinalara170303@gmail.com'
__version__ = '0.0.1'
|
# node class for develping linked list
class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_pointer(self, pointer):
... |
print("hello")
while True:
print("Infinite loop")
|
# This file is automatically generated
__version__ = '0.10.3.2'
__comments__ = """too many spaces :/
Merge pull request #1848 from swryan/work"""
__date__ = '2014-11-15 09:50:34 -0500'
__commit__ = '97c66aaecfad3451bc6a0b1cae1fce4c0595037a'
|
"""
文件名:hachina.py.
演示程序,三行代码创建一个新设备.
"""
def setup(hass, config):
"""HomeAssistant在配置文件中发现hachina域的配置后,会自动调用hachina.py文件中的setup函数."""
# 设置实体hachina.Hello_World的状态。
# 注意1:实体并不需要被创建,只要设置了实体的状态,实体就自然存在了
# 注意2:实体的状态可以是任何字符串
hass.states.set("hachina.hello_world", "太棒了!")
# 返回True代表... |
def division(a, b):
b = float(b)
if b == 0:
c = 0
print('Cannot divide by 0.')
return c
else:
a = float(a)
c = round(a / b, 9)
return c
|
""" aula sobre lista 18 repare como as listas podem ser incluidas dentro de uma lista. """
teste = []
teste.append('Álamo')
teste.append(26)
galera = []
galera.append(teste[:]) # é preciso fazer uma cópia com [:] para o sistema não duplicar
teste[0] = 'Francielli'
teste[1] = 22
galera.append(teste)
print(galera[:])
... |
wordle = open("Wordle.txt", "r")
wordList = []
for line in wordle:
stripped_line = line.strip()
wordList.append(stripped_line)
mutableList = []
outcomeList = []
def blackLetter(letter, list):
for word in list:
if letter in word:
list.remove(word)
def greenLetter(letter, ... |
weight = []
diff = 0
n = int(input())
for i in range(n):
q, c = map(int, input().split())
if c == 2:
q *= -1
weight.append(q)
diff += q
min_diff = abs(diff)
for i in range(n):
if abs(diff - 2*weight[i]) < min_diff:
min_diff = abs(diff - 2*weight[i])
for j in range(i+1, n):
... |
"""
In HiCal, a meeting is stored as tuples of integers (start_time, end_time). /
These integers represent the number of 30-minute blocks past 9:00am. /
For example: /
(2, 3) # meeting from 10:00 - 10:30 am /
(6, 9) # meeting from 12:00 - 1:30 pm /
Write a function merge_ranges() that /
takes a list of meeting time ran... |
def counting_sort(arr):
# Find min and max values
min_value = min(arr)
max_value = max(arr)
counting_arr = [0]*(max_value-min_value+1)
for num in arr:
counting_arr[num-min_value] += 1
index = 0
for i, count in enumerate(counting_arr):
for _ in range(count):
... |
# [8 kyu] Grasshopper - Terminal Game Move Function
#
# Author: Hsins
# Date: 2019/12/20
def move(position, roll):
return position + 2 * roll
|
# Go to new line using \n
print('-------------------------------------------------------')
print("My name is\nMaurizio Petrelli")
# Inserting characters using octal values
print('-------------------------------------------------------')
print("\100 \136 \137 \077 \176")
# Inserting characters using hex values
print('... |
class RetryOptions:
def __init__(self, firstRetry: int, maxNumber: int):
self.backoffCoefficient: int
self.maxRetryIntervalInMilliseconds: int
self.retryTimeoutInMilliseconds: int
self.firstRetryIntervalInMilliseconds: int = firstRetry
self.maxNumberOfAttempts: int = maxNumb... |
"""
This Code is Contributed by Arpit Bhushan Sharma
Codechef-@koderarpit
Github - @arpit1920
Kaggle - arpit3043
Mail - arpit3043@gmail.com
Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B.
Input
The first line contains an integer T, total number of testcases.
Then follow T... |
def rotations(l):
out = []
for i in range(len(l)):
a = shift(l, i)
out += [a]
return out
def shift(l, n):
return l[n:] + l[:n]
if __name__ == '__main__':
l = [0,1,2,3,4]
for x in rotations(l):
print(x) |
class GitrackException(Exception):
"""
General giTrack's exception
"""
pass
class ConfigException(GitrackException):
"""
Exception related to Config functionality.
"""
pass
class InitializedRepoException(GitrackException):
"""
Raised when user tries to initialized repo that ... |
def make_cut(l):
smallest = min(l)
return [
x - smallest
for x
in l
if x - smallest > 0
]
length = int(input())
current = list(
map(
int,
input().split()
)
)
while current:
print(len(current))
current = make_cut(current)
|
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1023/A
def f(ll):
n,k = ll #1e14
f = k//2 + 1
e = min(k-1,n)
return max(0,e-f+1)
l = list(map(int,input().split()))
print(f(l))
|
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7/0014/80C4285C-779E-DD11-9889-001617E30CA4.root',
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deno_repository():
# Get Deno archive
http_archive(
name = "deno-amd64",
build_file = "//ext/deno:BUILD",
sha256 = "7b883e3c638d21dd1875f0108819f2f13647b866ff24965135e679c743013f46",
type = "zip",
u... |
# 127. Word Ladder
# ttungl@gmail.com
# Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that beginWord i... |
class Allergies(object):
ALLERGY_SCORES = {
'eggs': 1,
'peanuts': 2,
'shellfish': 4,
'strawberries': 8,
'tomatoes': 16,
'chocolate': 32,
'pollen': 64,
'cats': 128
}
def __init__(self, score):
if score is None or not isinstance(score, i... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def libevent():
http_archive(
name = "libevent",
build_fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 08:20:55 2021
@author: silasjimmy
"""
def count_words(s, n):
s = s.split(' ')
counted_words = [(w, s.count((w))) for w in set(s)]
counted_words.sort(key = lambda x: (-x[1], x[0]))
top_n = counted_words[:n]
return top_n
def t... |
# jumlah segitiga
n = 123
# panjang alas sebuah segitiga
alas = 30
# tinggi sebuah segitiga
tinggi = 18
# hitung luas sebuah segitiga
luas = alas * tinggi * 1/2
# hitung luas total
luastotal = n * luas
print('luas total : ', luastotal,'satuan luas') |
# 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 writing, software
# distributed under the Li... |
# http://codingbat.com/prob/p193507
def string_times(str, n):
result = ""
for i in range(0, n):
result += str
return result
|
def alternate_case(s):
# Like a Giga Chad
return "".join([char.lower() if char.isupper() else char.upper() for char in s])
# Like a Beta Male
# return s.swapcase()
# EXAMPLE AND TESTING #
input = ["Hello World", "cODEwARS"]
for item in input:
print("\nInput: {0}\nAlternate Case: {1}".format(item,... |
"""A json-like master list of workflows and steps."""
# NOTE: Create a json-like dictionary in the form of:
# WF_STEPS = {
# env1: {
# 1st condition defined in next_steps: {
# 2nd condition defined in next_steps: (Workflow Name, Step Name),
# },
# },
# }
WF_STEPS = {}
|
#!/usr/bin/python3
list = ["Armitage", "Backdoor Factory", "BeEF","cisco-auditing-tool",
"cisco-global-exploiter","cisco-ocs","cisco-torch","Commix","crackle",
"exploitdb","jboss-autopwn","Linux Exploit Suggester","Maltego Teeth",
"Metasploit Framework","MSFPC","RouterSploit","SET","ShellNoob","sqlmap",
"THC-IPV6","Ye... |
def get_max_coins_helper(matrix, crow, ccol, rows, cols):
cval = matrix[crow][ccol]
if crow == rows - 1 and ccol == cols - 1:
return cval
down, right = cval, cval
if crow < rows - 1:
down += get_max_coins_helper(
matrix, crow + 1, ccol, rows, cols)
if ccol < cols - 1:
... |
class NEC:
def __init__( self ):
self.prompt = '(.*)'
self.timeout = 60
def show(self, *options, **def_args ):
'''Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-s... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'CwT'
# document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post">
# <input type="hidden" name="q" value="a"></form>';
# document.getElementById("dynForm").submit();
POST_JS = '<form id=\\"dynamicform\\" action=\\"%s\\" met... |
# data hiding - encapsulation
# this can be achieve by making the attribute or method private
# python doesn't have private keyword so precede
# the attribute/method identifier with an underscore or a double
# this is more effective if object in import or used as a module
# it isn't that effective
# no underscore = pu... |
# Instruksi:
# Buatlah komentar di garis pertama,
# Buat variabel bernama jumlah_pacar yang isinya angka (bukan desimal),
# Buat variabel bernama lagi_galau yang isinya boolean,
# Buat variabel dengan nama terserah anda dan gunakan salah satu dari operator matematika yang telah kita pelajari.
#variabel untuk menyimpan... |
# About: Implementation of the accumulator program
# in python 3 specialization
# ask to enter string
phrase = input("Enter a string: ")
# initialize total variable with zero
tot = 0
# iterate through the string
for char in phrase :
if char != " " :
tot += 1
# print the result
print(tot) |
class MapHash:
def __init__(self, maxsize=6):
self.maxsize = maxsize # Real scenario 64.
self.hash = [None] * self.maxsize # Will be a 2D list
def _get_hash_key(self, key):
hash = sum(ord(k) for k in key)
return hash % self.maxsize
def add(self, key, value)... |
#Refer AlexNet implementation code, returns last fully connected layer
fc7 = AlexNet(resized, feature_extract=True)
shape = (fc7.get_shape().as_list()[-1], 43)
fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=1e-2))
fc8_b = tf.Variable(tf.zeros(43))
logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b)
probs = tf.... |
def isSubsetSum(arr, n, sum):
'''
Returns true if there exists a subset
with given sum in arr[]
'''
# The value of subset[i%2][j] will be true
# if there exists a subset of sum j in
# arr[0, 1, ...., i-1]
subset = [[False for j in range(sum + 1)] for i in range(3)]
for i in range(n... |
tup = ('a','b',1,2,3)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
|
"""Exercício Python 64:
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final, mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag (999))."""
q = 0
s = 0
print('[Digit... |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
final = list()
# ----------------------------------------------------
if len(nums)==1:
return [[],nums]
if len(nums)==0:
return []
# ----------------------------------------------------... |
metros = float(input('Quantos metros de piso vc deseja? '))
preco = 70
total = metros*preco
print('O preço total do pedido é: R$ %.2f' % (total))
|
# -*- coding: utf-8 -*-
# @Time: 2020/7/3 10:21
# @Author: GraceKoo
# @File: interview_33.py
# @Desc: https://leetcode-cn.com/problems/chou-shu-lcof/
class Solution:
def nthUglyNumber(self, n: int) -> int:
if n <= 0:
return 0
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):... |
# Solution for the SafeCracker 50 Puzzle from Creative Crafthouse
# By: Eric Pollinger
# 9/11/2016
#
# Function to handle the addition of a given slice
def add(slice):
if row1Outer[(index1 + slice) % 16] != -1:
valRow1 = row1Outer[(index1 + slice) % 16]
else:
valRow1 = row0Inner[slice]
... |
# test __getattr__ on module
# ensure that does_not_exist doesn't exist to start with
this = __import__(__name__)
try:
this.does_not_exist
assert False
except AttributeError:
pass
# define __getattr__
def __getattr__(attr):
if attr == 'does_not_exist':
return False
raise AttributeError
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.