content stringlengths 7 1.05M |
|---|
def iter(n):
sum = 0
sum1 = 0
for i in range(0,n,1):
sum += 7*pow(10,i)
for j in range(1,n,1):
sum1 = (pow(10,j+1)-10-(9*j))/81
x = sum + sum1
return x |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: mo-mo-
#
# Created: 25/08/2018
# Copyright: (c) mo-mo- 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
# -*- coding: utf-8 -*-
"""
app.views.user
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module for initialising app user API package.
:copyright: (c)2020 by rico0821
""" |
pasta = "tomato, basil, garlic, salt, pasta, olive oil"
apple_pie = "apple, sugar, salt, cinnamon, flour, egg, butter"
ratatouille = "aubergine, carrot, onion, tomato, garlic, olive oil, pepper, salt"
chocolate_cake = "chocolate, sugar, salt, flour, coffee, butter"
omelette = "egg, milk, bacon, tomato, salt, pepper"
wo... |
num1 = 1
num2 = 1
num3 = 200
num100 = 000000
num2 = 100
num4 = 000
num33 = 9998
age = 12
age1 = 123
hahah = 1320389
|
# -*- coding: utf-8 -*-
__author__ = 'Sumeet Kumar'
__email__ = 'kr.sumeet@gmail.com'
__version__ = '1.0.0'
|
def title(txt):
return txt[0].upper() + txt[1:]
def show_title(txt):
print(txt[0].upper() + txt[1:])
# return None
# msg = 'месяц'
# # print(title(msg))
# # show_title(msg)
# print(show_title(msg))
students = ['иван', 'мария', 'сергей']
students_upd = []
for el in students:
students_upd.append(titl... |
N = int(input())
A = list(map(int, input().split()))
ans = 0
for i in range(N):
if A[A[i]-1] == (i+1):
ans += 1
print(ans//2)
|
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
ans=""
temp=""
for i in range(0,len(s)-1):
temp+=s[i]
if len(s)%len(temp)==0 and temp*int((len(s)/len(temp)))==s:
print(temp)
return 1
... |
# GYP file to build unit tests.
{
'includes': [
'apptype_console.gypi',
],
'targets': [
{
'target_name': 'pathops_unittest',
'type': 'executable',
'suppress_wildcard': '1',
'include_dirs' : [
'../src/core',
'../src/effects',
'../src/lazy',
'../src/pa... |
# =============================================================================
#
# =============================================================================
x =[1,2,5]+ [3,4]
x.sort()
# =============================================================================
#
# ===========================================... |
# значения операторов сравнения
print("2 > 1: ", 2 > 1)
print("2 < 1: ", 2 < 1)
print("2 == 1: ", 2 == 1)
print("2 == 2: ", 2 == 2)
print("2 != 2: ", 2 != 2)
print("2 != 1: ", 2 != 1)
result = 7 > 5
print(result)
# сравнение строк
print("Я" > "А")
print("Кот" > "Код")
print("Я" > "А")
print("Я" > "А")
|
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: 15-02-While.py
@time: 18-7-1 下午10:42
@version: v1.0
"""
i = 0
while i <= 10:
print("This {i} time execute!".format(i=i))
i += 1
else:
print("I'm else!") # 执行玩循环体退出后执行
|
class Solution:
def groupAnagrams(self, strs: list) -> list:
hashmap = {}
for s in strs:
key = ''.join(sorted(s))
if key in hashmap:
hashmap[key] += [s]
else:
hashmap[key] = [s]
return hashmap.values()
v = Solution().group... |
def plus_minus(arr):
positive, negative, zero = 0, 0, 0
for index in arr:
if index > 0:
positive += 1
elif index < 0:
negative += 1
else:
zero += 1
print(positive/len(arr))
print(negative/len(arr))
print(zero/len(arr))
arr = [-4, 3, -9, 0,... |
#!/usr/bin/python
# arithmetic.py
a = 10
b = 11
c = 12
add = a + b + c
sub = c - a
mult = a * b
div = c / 3
power = (a ** 2)
print (add, sub, mult, div)
print (power)
|
"""P7E2 VICTORIA PEÑAS
Escribe un programa que lea el nombre y los dos apellidos de una
persona (en tres cadenas de caracteres diferentes), los pase como
parámetros a una función, y ésta debe unirlos y devolver una única
cadena. La cadena final la imprimirá el programa por pantalla."""
def mostrarNombre(nom,ape1,ape2):... |
#
# LeetCode
#
# Problem - 206
# URL - https://leetcode.com/problems/reverse-linked-list/
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
an... |
def ExtensoToInteiro(extenso):
NumDict = {}
MilharDict = {}
NumDict["zero"] = 0
NumDict["um"] = 1
NumDict["dois"] = 2
NumDict["três"] = 3
NumDict["quatro"] = 4
NumDict["cinco"] = 5
NumDict["seis"] = 6
NumDict["sete"] = 7
NumDict["oito"] = 8
NumDict["nove"] =... |
#
# PySNMP MIB module ARISTA-NEXTHOP-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARISTA-NEXTHOP-GROUP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:25:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
class Message:
def __init__(self, chat_id=""):
self.chat_id = chat_id
def set_text(self, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None):
self.text = text
self.content_type = "text"
se... |
"""
Distributed under the MIT License. See LICENSE.txt for more info.
"""
# seconds after email verification will expire
EMAIL_VERIFICATION_EXPIRY = 48 * 60 * 60 |
# -*- coding: utf-8 -*-
__email__ = '{{ cookiecutter.author_email }}'
__author__ = '{{ cookiecutter.author_name }}'
__version__ = '0.0.1'
|
'''
Negatives, Zeros and Positives
На вход программе подается натуральное число n, а затем n целых чисел. Напишите программу, которая сначала выводит все отрицательные числа, затем нули, а затем все положительные числа, каждое на отдельной строке. Числа должны быть выведены в том же порядке, в котором они были введены.... |
#x = "awesome"
def myfunc():
print("Python is " + x)
#myfunc()
''''''''''''''''''''''''''''''''''''
x = "awesome"
def myfunc2():
x = "fantastic"
print("Python is " + x)
myfunc2()
print("Python is " + x) |
#!/usr/bin/env python
array = [
{
'fips': '01',
'abbr': 'AL',
'name': 'Alabama',
},
{
'fips': '02',
'abbr': 'AK',
'name': 'Alaska',
},
{
'fips': '04',
'abbr': 'AZ',
'name': 'Arizona',
},
{
'fips': '05',
'abbr': 'AR',
'name': 'Arkansas',
},
{
'fips': '06',
'abbr': 'CA',
'name': 'C... |
def checkstyle(name, srcs=[],
checkstyle_xml="//tools/config/src/main/resources:harness_checks.xml",):
# checkstyle_suppressions="@com_github_mihaibojin_bazel_java_rules//checkstyle:checkstyle-suppressions.xml",
# checkstyle_xpath_suppressions="@com_github_mihaibojin_bazel_jav... |
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i, w in enumerate(sentence.split(" ")):
if w.startswith(searchWord):
return i + 1
return -1
|
print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"
print("Hello ME".replace("ME", "world"))
#prints "Hello world"
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
print("This is a sentence.".upper())
# prints "THIS IS... |
# Write redmonster output files
#
# Tim Hutchinson, , University of Utah, April 2014
# t.hutchinson@utah.edu
#
# July 2014 - now probably defunct, replaced by redmonster.datamgr.io.py
class Output:
def __init__(self, spec=None):
if spec: self.set_filenames()
def set_filenames(self):
self.zall... |
class SplitterNotifier:
def __init__(self, notifiers=None):
if notifiers is None:
notifiers = []
self.notifiers = notifiers
def notify(self, notification, text, options=None):
if options is None:
options = {}
for notifier in self.notifiers:
no... |
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
1. Find the first pos i from right such that nums[i] < nums[i+1]
2. Swap nums[i] with the smallest element larger than nums[i]
3. Sort nums[i+1:]
... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class DiskPartition(object):
"""Implementation of the 'Disk Partition.' model.
Specifies information about each partition in a physical disk.
Attributes:
length_bytes (long|int): Specifies the length of the block in bytes.
number (l... |
"""
Global Tusclient exception and warning classes.
"""
class TusCommunicationError(Exception):
"""
Should be raised when communications with tus-server behaves
unexpectedly.
:Attributes:
- message (str):
Main message of the exception
- status_code (int):
Statu... |
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
is_same = [a == b for a,b in zip(nums,sorted(nums))]
return 0 if all(is_same) else len(nums) - is_same[:... |
number = 10
decimal = 2.3
string = "Hello there." # ≡
array = [2.3, 'Hello there.', [1, 2], {"a": 1, 'b': 2}]
dictionary = {"number": 2.3, 'list': [1, 2], "values": {'a': 1, "b": 2}}
print(string) # Hello there. ≡
string = "Goodbye!" # ≡
print(string) # Goodbye! ≡ |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 15:19:12 2021
@author: alef
"""
"""
boolean é uma especialização do tipo inteiro. veraddeiro é True e igual a 1,
enquanto o falso é chamado de False e é ogual a zero.
São considerados falsos:
- False (falso)
- None (nulo)
- 0 (zero)
- ''(string... |
x=2
def increment(number):
return number + 1
|
"""**TODO**
.. autosummary::
:toctree:
Bifunctor
"""
class Bifunctor():
"""**TODO**"""
|
LOGIN_PHASES = [
'WaitingForAuthentication',
'WaitingForEula',
'Done',
'Disabled',
'Login',
'',
]
WAIT_FOR_LAUNCH_PHASES = [
'WaitForLaunch',
]
SUCCESS_PHASES = [
'WaitForSessionExit',
]
EULA_PHASES = [
'Eula',
]
CONSENT_REQUIRED_PHASES = [
'AgeRestriction',
]
BANNED_PHASES ... |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# -------------------------------------------------------------------------
# Copyright (C) 2014 by Mathijs Dumon <mathijs dot dumon at gmail dot com>
#
# mvc is a framework derived from the original pygtkmvc framework
# hosted at: <http://sourceforge.net/projects/pygtkmvc/>
#
# ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
Class Parser parses clingo output
'''
class Parser:
next_line_facts = False
def process_facts(self, facts):
facts = facts.split(" ")
facts.sort()
return facts
def process_line(self, line, model):
line = line.replace("\n", "")
... |
def turn_right():
turn_left()
turn_left()
turn_left()
def jump():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
while not at_goal():
jump()
|
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftANDORleftPLUSMINUSleftTIMESDIVIDErightUMINUSleftLPARENRPARENAND DIVIDE FLOAT GE GT ID IE IN LE LIST LPAREN LT MINUS NE NONE NOT NUMBER OR PLUS RPAREN STR TIMES\n ... |
DEFINITIONS={
"cc_clone_detection_big_clone_bench": {
"class_name": "CodeXGlueCCCloneDetectionBigCloneBench",
"data_dir_name": "dataset",
"dataset_type": "Code-Code",
"description": "CodeXGLUE Clone-detection-BigCloneBench dataset, available at https://github.com/microsoft/CodeXGLUE/... |
"""
"""
def get_daily_quote():
return 'q:gdq'
|
##################################
# import_file.json #
##################################
attributes = {
"type": "array",
"items": {
"type": "object",
"properties": {"id": {"type": "integer"}, "groupId": {"type": "integer"}},
"required": ["id", "groupId"],
},
}
bbox ... |
s = list(map(int, input().split()))
for i in range(1, len(s)):
if s[i] > s[i - 1]:
print(s[i], end=' ')
|
class Solution:
def climbStairs(self, n: int) -> int:
if(n==1):
return 1
dp = [0] * (n+1)
dp[1] = 1
dp[2] = 2
for i in range(3,n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
|
# -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
num1 = int(input("Please input num1: "))
num2 = int(input("Please input num2: "))
num3 = int(input("Please input num3: "))
num4 = int(input("Please input num4: "))
num5 = int(input("Please input num5: "))
num6 = int(input("Please input num6: "))
s = num1 + num2 + num3 + num4 + num5 + num6
print("sum: {}".forma... |
q=int(input())
if(1>q or q>10):
exit
def isAnagram(par1,par2):
par1.sort()
par2.sort()
# print(len(par1))
for i in range(len(par1)):
if(par1[i]!=par2[i]):
return False
return True
def init():
strings=[]
count=0
q=int(globals()['q'])
while(q!=0):
st... |
"""
Написать декоратор instances_counter, который применяется к любому классу
и добавляет ему 2 метода:
get_created_instances - возвращает количество созданых экземпляров класса
reset_instances_counter - сбросить счетчик экземпляров,
возвращает значение до сброса
Имя декоратора и методов не менять
Ниже пример использо... |
# B_R_R
# M_S_A_W
"""
Coding Problem on Exception Handling:
How to raise Error
Using try and except
"""
class DogNameError(Exception):
def __init__(self, *args,**kwargs):
Exception.__init__(self, *args,**kwargs)
try:
user_input=input("What is your dog name: ")
if any(i.isdigit()for i in user_... |
_base_ = [
'../_base_/datasets/icip.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'
]
# model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='ResNetV1c',
depth=50,
n... |
#
# PySNMP MIB module CISCO-ENTITY-SENSOR-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-SENSOR-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:
# - IMC abaixo de 18,5: Abaixo do Peso
# - Entre 18,5 e 25: Peso Ideal
# - 25 até 30: Sobrepeso
# - 30 até 40: Obesidade
# - Acima de 40: Obesidade Mórbida
pr... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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... |
def binary_search(array, target):
start_index = 0
end_index = len(array) - 1
while start_index <= end_index:
mid_index = (start_index + end_index) // 2 # integer division in Python 3
mid_element = array[mid_index]
if target == mid_element: # we have found the element
... |
#!/usr/bin/python3
# code_generator.py
def add_layers(layers):
return_string = '''model = tf.keras.Sequential()\n'''
for layer in layers:
if layer['type'] == 'dense':
if layer['activation_function'] is not None:
return_string += '''model.add(tf.keras.layers.Dense(units={uni... |
# Break Statements in Python in While loops
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
# The break statement in for
'''‘break’ is used to come out of the loop when encountered.
It instructs the program to – Exit the loop now. '''
# Example:
for i in range(10):
print(i)
if i==5: #bre... |
#Iris Data sorted into columns
#Hugh O'Reilly 04/03/18
with open("data/iris.csv") as f: #Opens Iris data set csv file in data folder
for line in f:# loops through each line
line = line.replace(',', ' ') #replaces comma with space, code from Mohamed Noor
line = line.rstrip() #Removes nextline code o... |
#Euler Problem 5 Lowest common multiple
# Michael Garvey
# credits: https://gist.github.com/PEZ/47534
i = 1
for k in (range(1, 21)): #using range to test numbers 1 to 20
if i % k > 0:
for j in range(1, 21):
if (i*j) % k == 0:
i *= j
break
print (i) |
'''teste = list()
teste.append('Bruno')
teste.append('26')
galera = list()
galera.append(teste[:])
teste[0] = 'Larissa'
teste[1] = 23
galera.append(teste[:])
print(galera)
print('\033[34mparte 1\033[m')
pessoas = [['joao',19],['ana',33],['joaquim',13],['maria',45]]
print(pessoas[0][0])
print(pessoas[1][1])
print(pesso... |
def mergeSort(array):
print(f"Splitting the array {array}")
if len(array)>1:
mid = len(array)//2
lefthalf = array[:mid]
righthalf = array[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
... |
class Solution:
def storeProfit(self, profit):
print(self.profits, profit)
store_idx = -1
min = None
print(self.profits)
for i, val in enumerate(self.profits):
if min is None:
min = val
store_idx = i
if ... |
"""craigslist - A Discord bot to facilitate playing Millenial Apartment Hunters"""
__version__ = '0.1.0'
__author__ = 'Rose Davidson <rose@metaclassical.com>'
__all__ = []
|
# def add(num1, num2):
# # just put these initial values down to the length
# x = len(str(num1))
# y = len(str(num2))
# z = 0
# if x >= y :
# for k in range(0,x):
# z = z + int(num1/(10**x)) + int(num2/(10**x))
# else:
# for k in range(0,y):
# z = z + i... |
"""
shortcut to run docker remove commands
"""
def get_rmi_command(info_list):
"""
JUST USE: docker rmi $(docker images -f "dangling=true" -q)
<none> <none> 591446e60492 4 days ago 796MB
<none> <none> f2f37f4e35fa 4 days ago ... |
def _render(template, context, app):
"""Renders the template and fires the signal"""
before_render_template.send(app, template=template, context=context)
rv = template.render(context)
template_rendered.send(app, template=template, context=context)
return rv
|
class HTTP404(Exception):
def __init__(self):
super(HTTP404, self).__init__()
self.code = 404
def __str__(self):
return "404: Page Not Found"
def __repr__(self):
return self.__str__()
|
#Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
#
#For example:
#Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
#return its zigzag level order traversal as:
... |
version=''
commithash='64db13864cb1b377c8a9ab7c08e4688d3d1f94ef'
gittag_short=''
gittag_long='64db138-dirty'
git_lastmod='Mon, 15 May 2017 14:34:53 +0200'
github_url='https://github.com/plasmodic/ecto'
breathe_default_project = 'ecto'
breathe_projects = dict(ecto='/home/arnaud.duhamel/qidata/python-ecto/build/temp.lin... |
# This problem was recently asked by Apple:
# You are given a binary tree representation of an arithmetic expression.
# In this tree, each leaf is an integer value,, and a non-leaf node is one of the four operations: '+', '-', '*', or '/'.
# Write a function that takes this tree and evaluates the expression.
class No... |
image = io.imread('../img/skimage-logo.png')
# --- assign each color channel to a different variable ---
r = image[:, :, 0]
g = image[:, :, 1]
b = image[:, :, 2]
|
#
# PySNMP MIB module MGMT-SECURITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MGMT-SECURITY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:11:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
#!/usr/bin/env python
# coding=utf-8
# 二手房信息的数据结构
class SecondHand(object):
def __init__(self, district, area, name, price, desc):
self.district = district
self.area = area
self.price = price
self.name = name
self.desc = desc
def text(self):
return self.distric... |
# Copyright 2019 Graphcore Ltd.
class NullContextManager(object):
def __enter__(self):
pass
def __exit__(self, *args):
pass
|
#Global parameters module
N = 1024
K = 16
Q = 12289
POLY_BYTES = 1792
NEWHOPE_SEEDBYTES = 32
NEWHOPE_RECBYTES = 256
NEWHOPE_SENDABYTES = POLY_BYTES + NEWHOPE_SEEDBYTES
NEWHOPE_SENDBBYTES = POLY_BYTES + NEWHOPE_RECBYTES
|
# Hacked from winnt.h
DELETE = (65536)
READ_CONTROL = (131072)
WRITE_DAC = (262144)
WRITE_OWNER = (524288)
SYNCHRONIZE = (1048576)
STANDARD_RIGHTS_REQUIRED = (983040)
STANDARD_RIGHTS_READ = (READ_CONTROL)
STANDARD_RIGHTS_WRITE = (READ_CONTROL)
STANDARD_RIGHTS_EXECUTE = (READ_CONTROL)
STANDARD_RIGHTS_ALL = (2031616)
SP... |
data_de_nascimento = input('Qual a sua data de nascimento? (Ex: 14 09 2004) ').split()
dia = data_de_nascimento[0]
mes = data_de_nascimento[1]
ano = data_de_nascimento[2]
print(f'Você nasceu no dia {dia} do mês {mes} no ano de {ano}.') |
#Challenge 1
num = 1
while num < 11:
print(num)
num += 1
#Challenge 2
chosenNum = input('Enter a number: ')
modifier = 1
chosenNum = int(chosenNum)
for count in range(1, chosenNum, 1):
chosenNum += count
print (chosenNum)
#Challenge 3
for count in range(1500, 2701, 1):
if (count % 7 == 0 and ... |
#! /home/nsanthony/anaconda3/bin/python
num_of_primes = 10000
prime_num_count = 0
primes = [0]*num_of_primes
i = 1 #starting prime
while prime_num_count < num_of_primes:
i += 1
divisible = 1
k = 0
while k < prime_num_count:
if(i % primes[k] == 0): #modulus
divisible = 0
... |
"""
Prime Numbers I
"""
# Check if a number input by a user is prime or not. If it is NOT a prime number, print out that it is not a prime number. If it IS a prime number, print out that it is a prime number and give an example of two of its factors. Hint: Prime numbers must be greater than 1.
# Example of output for... |
"Dylan Murphy"
"2018-07-13"
'Dylan Murphy 2018-07-03'
"""This Program cross checks addresses from the Petroleum spill database with addresses listed in
the PLUTO csv file. these addresses have been edited and formatted in order to properly match.
It uses a binary search algorithms to search for matching address... |
string = input().upper()
if string.count('AUGUST')>=1:
print('NOU')
else:
string = ''.join(reversed(string)).replace('A','S')
print(string) |
"""
Inline tokenizer for mistletoe.
"""
def tokenize(string, token_types):
*token_types, fallback_token = token_types
tokens = find_tokens(string, token_types, fallback_token)
token_buffer = []
if tokens:
prev = tokens[0]
for curr in tokens[1:]:
prev = eval_tokens(prev, cur... |
n_odds = -1
for i in range(0, 14, 2):
# Check for the value of i in each iteration
breakpoint()
# Bad condition
if i % 1 == 0:
n_odds += 0
print(n_odds) |
class PublicClass:
pass
class _PrivateClass:
pass
def public_function():
pass
def _private_function():
pass
|
test_image = plt.imread(os.path.join('test_images', 'test4.jpg'))
undistorted_img = cv2.undistort(test_image, mtx, dist)
thresh_binary = func(image)
img_size = (thresh_binary.shape[1], thresh_binary.shape[0])
width, height = img_size
offset = 200
src = np.float32([
[ 588, 446 ],
[ 691, 446 ],
[ 112... |
age = 3
admission_fee = (0,25,40)
if age < 4:
print(f"Your admission fee is ${admission_fee[0]}, welcome to the park!")
elif age < 18:
print(f"Your admission fee is ${admission_fee[1]}, welcome to the park!")
else:
print(f"You're a senior so your fee is ${admission_fee[2]}, Welcome!!")
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
@author: syenpark
Python Version: 3.6
"""
decimal = int(input('Enter an integer number: '))
sign = ''
digits = []
binary = ''
if decimal < 0:
decimal *= -1
sign = '-'
while decimal:
digits.insert(0, str(decimal % 2))
decimal //= 2
print(sign + bina... |
# Copyright (c) 2019 Pavel Vavruska
# 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, publish, d... |
dict={11:"th", 12:"th", 13:"th", 1:"st", 2:"nd", 3:"rd"}
def what_century(year):
year=str(year)
century=int(year[:2])+1 if year[-2:]!="00" else int(year[:2])
if century in dict:
return f"{century}{dict[century]}"
elif century%10 in dict:
return f"{century}{dict[century%10]}"
return f... |
"""
@author: Maneesh D
@date: May 15, 2017
@interpreter: Python 3.6.1
Fahrenheit to Celcius Converter
"""
fahren = float(input("Enter the temperature in Fahrenheit: "))
celcius = ((fahren - 32) * 5) / 9
print("%.2f in Degree Celcius is %.2f" % (fahren, celcius))
|
class EdgeType(Enum):
"""Enumeration of different causal edges.
Categories
----------
bidirected : str
Signifies edge is part of a "<->" edge.
arrow : str
Signifies ">", or "<" edge. That is a normal
directed edge.
circle : str
Signifies "o" endpoint. That is an... |
class common(object):
"""description of class"""
def generateData(dat):
updateDic = {
"Cartisian.position.x":dat['Cartisian[position][x]'],
"Cartisian.position.y":dat['Cartisian[position][y]'],
"Cartisian.position.z":dat['Cartisian[position][z]'],
"Cartisia... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
h_pos = 0
v_pos = 0
for move in moves:
if move == 'U':
v_pos += 1
elif move == 'D':
v_pos -= 1
elif move == 'L':
h_pos -= 1
elif... |
morning = {'Java', 'C', 'Ruby', 'Lisp', 'C#'}
afternoon = {'Python', 'C#', 'Java', 'C', 'Ruby'}
print(morning ^ afternoon)
print(morning.symmetric_difference(afternoon))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.