content stringlengths 7 1.05M |
|---|
# Copyright (c) 2017 Chao Ji
# 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, distribute, ... |
"""Kata: Equal sides of an array sum to the same value."""
def find_even_index(arr):
"""."""
for idx, num in enumerate(arr):
if sum(arr[:idx]) == sum(arr[idx + 1:]):
return idx
return '-1'
|
num = int(input())
bonus = 0
if num <= 100:
bonus = 5
elif 1000 >= num > 100:
bonus = num * 20 / 100
else:
bonus = num * 10 / 100
if num % 2 == 0:
bonus = bonus + 1
elif num % 5 == 0:
bonus = bonus + 2
print(bonus)
print(bonus + num)
|
# Copyright (C) 2020 Atsushi Togo
# All rights reserved.
#
# This file is part of phonopy.
#
# 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
# notic... |
a=0
while a>=0:
a=int(input('enter a number '))
print(a)
if a%2==0:
print('this is evan')
else:
print('this is odd') |
def calc_best_match(encrypted_text):
best_score=0
best_cipher_letter=None
# [a-z]
for cipher_letter in range(97, 123):
score = 0
for encrypted_char in encrypted_text:
decrypted_char = (encrypted_char ^ cipher_letter)
# [a-zA-Z ]
if 96 < decrypted_char... |
#The power of two. For a given integer N,
#find the greatest integer x where 2 power x is less than or equal to N. Print the exponent value and the result of the expression 2powerx.
N = int(input())
x = 0
while ((2**x) <= N ):
x += 1
print("exponent value is:", (x-1), " and value of 2 power x is:", (2**(x-1)) )
... |
name = 'hdert'
age = 13
loop = ('FALSE')
while loop == 'FALSE':
print(name + ' is\nawesome and also')
print(age)
print('years old')
print()
name = 'hdert'
age = 14
print('now ' + name + '\nis')
print(age)
print('years old and\nstill awesome')
loop = ('TRUE')
|
DEBUG = True
SECRET_KEY = '\xd3q\xf9\xb7r\xad\x03Ip$\xfe\x8fd\x17\x1f\xbd\xe8\xd4\xa8\xe7\x99V\xf7\x22'
LDAP_SERVER = 'localhost'
LDAP_ADMIN = 'cn=admin,dc=example,dc=com'
LDAP_PASSWD = 'yay'
LDAP_BASEDN = 'dc=example,dc=com'
|
'''
Bitcoin Core version last tested
with Blockchain Backup.
Copyright 2020 DeNova
Last modified: 2020-11-03
'''
CORE_VERSION = '0.20.1'
|
#
# PySNMP MIB module HUAWEI-QINQ-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-QINQ-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:48:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
"""HealthcareAIError
This is the error to communicate things to non technical users.
"""
class HealthcareAIError(Exception):
"""This is the error that should be thrown to help communicate problems to users in a nice way."""
def __init__(self, message):
"""Instantiate the error with a given message""... |
"""
Algorithms to find connected components in the graph considering
only dovetails overlaps.
Adapted using the networkx connected module:
networkx/networkx/algorithms/components/connected.py
"""
# Copyright (C) 2011-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swa... |
class TeamData():
""" Manage premier league team data """
def __init__(self):
pass
def read_pl_teams_info(self, teams):
# Get the information of all players
assert teams, '"teams" variable is NULL'
self._teams = teams
@property
def pl_teams_lookup_info_df(self):
... |
my_list = []
nr=int(input())
for i in range(nr):
my_list.append(input())
print(my_list)
|
#!/usr/bin/env python3
for r in range(1, 5):
with open('conf-part7-r%d.conf' % r, 'w') as f:
for i in range(1, 3):
for j in range(0, 256):
f.write('route 10.%d.%d.0/24 via "veth-R%d-PC%d";\n' % (i+r*2-2, j, r, r))
|
"""
y_cable_base.py
Base class for implementing Y-Cable specific functionality in SONiC.
This is the base class of sonic_y_cable implentation. A vendor-specific
implementation of a 'YCable' class needs to inherit from this class.
Classes derived from this class provide the ability to interact
w... |
# class representing a field or field group
class AbstractField:
def __init__(self,level:int,name:str):
self.level = level
self.name = name
self.start_pos:int = 0
self.length:int = 0
def __repr__(self):
return f"name: {self.name}"
def _rename_with_suffix(self,suffi... |
def minValue(root):
##Your code here
if root is None:
return -1
temp=root
while temp.left!=None:
temp=temp.left
return temp.data
|
t = int(input('Digite o valor para saber a tabuada:' ))
u = t * 1
d = t * 2
tre = t * 3
q = t * 4
c = t * 5
s = t * 6
set = t * 7
oi = t * 8
no = t * 9
dez = t *10
print('Tabuada de {}\n {} x 1 = {} \n {} x 2 = {}\n {} x 3 = {} \n {} x 4 = {} \n {} x 5 = {} \n {} x 6 = {} \n {} x 7 = {} \n {} x 8 = {} \... |
# int(input("Enter number:"))
# def factorial():
# f = 1
# for i in range(1,21):
# f = i * f
# print(f)
# factorial()
def factorial_20(n):
f = 1
for i in range(n,1,-1):
f = i * f
return f
for i in range(1,21):
print(f"{i} is {factorial_20(i)}")
fac... |
def last_element(lst):
"""Return last item in list (None if list is empty.
>>> last_element([1, 2, 3])
3
>>> last_element([]) is None
True
"""
if len(lst) != 0:
return lst[-1]
return None
print(F"last_element.py: last_element([1, 2, 3]) = `3` ... |
"""
Capital
Write a program that takes a string as input,
makes every other letter capital, sets the rest
of the characters to be lowercase, and displays
the new string.
Hint: Make sure you don't count non-alphabetic
characters.
Example input: I love Zee the Cat.
Example output: I lOvE zEe ThE cAt.
"""
str = input(... |
while True:
a = []
x = int(input())
if (x == 0):
break
for i in range(x):
b = input()
if (type(b) is str):
a.append(b)
a.sort(key=lambda x: x[:2])
print(*a, sep='\n')
|
class Student(object):
def __init__(self) -> None:
# 私有属性
self.__age = 0
def get_age(self):
print("获取属性")
return self.__age
def set_age(self, new_age):
print("设置属性")
self.__age = new_age
# property关键字,是一个类,传参依次是获取、设置、删除
age = property(get_age, set_ag... |
def checkValue(sudoku, value, x, y):
lstx = []
lsty = []
lstr = []
if x > 5:
xlimU = 5
xlimA = 9
elif x > 2:
xlimU = 2
xlimA = 6
else:
xlimU = -1
xlimA = 3
if y > 5:
ylimU = 5
ylimA = 9
elif y > 2:
ylimU = 2
... |
# n, m = map(int,input().split())
# pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
# print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
def get_vals():
height, width = map(int, input().split())
assert height % 2 == 1 # Make sure to follow the constraints
assert width... |
class ConfigurationError(Exception):
"""Exception class to raise if a Configurable object has an issue."""
pass
class NotFoundError(Exception):
"""Exception class to raise if a file was not found."""
pass
class EstimatorNotTrainedError(Exception):
"""Exception class to raise if estimator is used... |
def get_movies_from_keywords(keywords):
movies = [
{
"ASIN": "B003AI2VGA",
"match": .8,
},
{
"ASIN": "B00006HAXW",
"match": .7
},
{
"ASIN": "B00004CQT3",
"match": .6
},
{
"ASIN... |
#
# @lc app=leetcode id=7 lang=python3
#
# [7] Reverse Integer
#
# @lc code=start
class Solution:
def reverse(self, x: int) -> int:
# [-2147483648, 2147483647]
if x == 0:
return 0
arr = []
tmp = 0
if x > 0:
tmp = x // 10
arr.append(x % 10)... |
"""Constants for the solax integration."""
DOMAIN = "solax"
MANUFACTURER = "SolaX Power"
|
"""
Fichero para practicar la impartación de módulos
"""
c = 3
d = 4
|
def beginning(a_list):
i = 0
while i < len(a_list):
if a_list[i] == 'bye':
if i == 0:
return []
elif i < 10:
return a_list[:i]
else:
break
i += 1
return a_list[:10]
|
def main(state):
print("foo:", state["foo"])
print("foo2:", state["foo2"])
print("foo3:", state["foo3"])
print("foo4:", state["foo4"])
def register(mf):
mf.register_defaults({
"foo": lambda state, event: state["bar"] if "bar" in state else 0,
"foo2": lambda state, event: state["ba... |
a = input('Digite o nome do aluno: ')
n1 = int(input('Digite a nota da primeira prova: '))
n2 = int(input('Digite a nota da segunda prova: '))
print(f'A média do aluno {a} é {(n1+n2)/2}')
|
try:
x = 0
y = x/x
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
|
match x:
case 1 | 2:
pass
case (1 | 2):
pass
case (1 | 2) | 3:
pass
case 1 | (2 | 3):
pass
|
"""
Check that send will not block in different situations...
"""
#pragma repy restrictions.twoports
localip = "127.0.0.1"
localport = 12345
targetip = "127.0.0.1"
targetport = 12346
timeout = 1.0
tcpserversocket = listenforconnection(targetip, targetport)
conn = openconnection(targetip, targetport, localip, localpo... |
def full_ticker_list():
"""
List of all the popular tickers identified. Add more to the list if you wish to
"""
list_of_tickers = ["AMC", "BB", "CLOV", "UWMC", "NIO", "TSLA", "AAPL", "SPY", "NOK", "AMD", "NVDA", "MSFT", "GME",
"RBLX", "F", "PLTR", "COIN", "RKT", "MVIS", "FUBO", "D... |
def try_config(config, heading, key):
"""Attempt to extract config[heading][key], with error handling.
This function wraps config access with a try-catch to print out informative
error messages and then exit."""
try:
section = config[heading]
except KeyError:
exit("Missing config se... |
# Copyright (c) 2015 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
"""
This file defines a custom admin page for any models defined
in models.py.
A ... |
# Apresentação
print('Programa para calcular estatísticas dos números e um vetor')
print()
# Solicita os 18 valores
valores = list()
for i in range(18):
valores.append(float(input('Informe um número: ')))
# Calcula a média dos valores (somatório de todos os
# valores dividido pela quantidade de valores existentes... |
load("@rules_jvm_external//:specs.bzl", "maven")
LIFECYCLE_VERSION = "2.2.0-rc03"
ROOM_VERSION = "2.2.3"
ROOM_WORDS_SAMPLE_MAVEN_ARTIFACTS = [
"androidx.annotation:annotation:1.1.0",
"androidx.appcompat:appcompat:1.1.0",
"androidx.constraintlayout:constraintlayout:1.1.3",
"androidx.fragment:fragment:1... |
# *******************************
# |docname| - routinng for web2py
# *******************************
# Provide a default application, so that accessing "https://my-site-name.edu" works, instead of requiring "https://my-site-name.edu/runestone".
#
# See the `web2py manual <http://web2py.com/books/default/chapter/29/04/... |
# Convenience utilities for printing
def p(n, duration):
print('{:2d}: {:6.3f} seconds'.format(n, duration))
|
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Education, obj[4]: Occupation, obj[5]: Bar, obj[6]: Coffeehouse, obj[7]: Restaurant20to50, obj[8]: Direction_same, obj[9]: Distance
# {"feature": "Occupation", "instances": 34, "metric_value": 0.9367, "depth": 1}
if obj[4]<=14:
# {"fea... |
def private_function(name):
"""private_function is a docstring().
:meta private:
"""
def _public_function(name):
"""public_function is a docstring().
:meta public:
"""
PRIVATE_CONSTANT = None #: :meta private:
_PUBLIC_CONSTANT = None #: :meta public:
|
# -*- coding:utf8 -*-
'''
The model for PDA
'''
class Energy(object):
'''
the Energy model
'''
def __init__(self, name, energy):
'''
The construction funtion
'''
self._name = name
self._energy = energy
@property
def name(self):
'''
the ... |
def add(x, y):
return x + y
class Calculator:
def __init__(self):
self.current = 0
self.total = 0
def set(self, value):
self.current = value
def add(self):
self.total += self.current
def sub(self):
self.total -= self.current
def total(self):
... |
def not_none(obj, msg="parameter must not be None"):
if obj is None:
raise ValueError(msg)
else:
return obj
def safe_get(a_list, index):
if index < 0 or index > len(a_list)-1:
raise IndexError("index {} is out of range for {}".format(index, a_list))
else:
return a_list[... |
"""
!/usr/bin/env python3
-*- coding: utf-8 -*-
----------------------------------------------------------------------
Copyright 2021 CFS Engineering
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... |
hellos = [
"Hello",
"Tungjatjeta",
"Grüßgott",
"Вiтаю",
"dobrý den",
"hyvää päivää",
"你好",
"早上好"
]
for x in hellos:
print(x, 'World')
|
class _UNDEFINED(object):pass
class BaseOperatorFactory(object):
def simple_selector(self, func, arg=_UNDEFINED()):
return SimpleSelector(func, arg)
def filter_selector(self, func, arg):
return FilterSelector(func, arg)
def filter_operator(self, op1, op2):
return FilterOperator(o... |
"""
leo_cloud.py - synchronize Leo subtrees with remote central server
Terry N. Brown, terrynbrown@gmail.com, Fri Sep 22 10:34:10 2017
(this is the server half, see also leo_cloud.py for the Leo plugin)
This file is a *stub* for a Leo aware LeoCloudIOLeoServer which allows more
granular and real-time synchronization... |
# Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores ‘M’ ou ‘F’. Caso esteja errado, peça a digitação novamente até ter um valor correto.
sexo = str(input('Digite o sexo [M/F]: ')).strip().upper()[0]
while sexo not in 'MF':
sexo = str(input('Opção inválida, Digite o sexo [M/F]: ')).strip().up... |
class NoteGroup :
def __init__(self, noteList) :
self._noteList = noteList
def clone(self) :
other = NoteGroup([])
for note in self._noteList :
other._noteList.append(note.clone())
return other
def getNoteList(self) :
return self._noteList
def increaseOctave(self, delta) :
for note in self._noteLi... |
print('')
senha = int(input('Qual sua senha: '))
print('')
t = 0
while t != senha:
t=int(input('Digite a senha novamente: '))
print('')
if t != senha:
print('Senha incorreta. Tente novamente')
print('')
print('Senha confirmada com sucesso!')
print('')
|
# coding=utf-8
crawler_start = object()
crawler_shutdown = object()
request_scheduled = object()
request_ignored = object()
response_received = object()
item_scraped = object()
item_ignored = object()
|
class Persona:
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
def calcular(self):
if self.edad>18:
print(f'{self.nombre} eres mayor de edad')
else:
print(f'{self.nombre} eres un crio aun')
obj1 = Persona('Haroun',12)
obj1.calcu... |
def convert_matrix_to_image(m, shape):
"""Convert a column matrix of pixels to a 3D image given by shape.
The number of channels is taken from m, not shape. If shape has
length 2, the matrix is returned unchanged. This is the inverse
of convert_image_to_matrix:
im == convert_matrix_to_image(conve... |
n=int(input("Enter the year"))
if n%4==0:
print("Leap year")
if n%100==0:
print("Not Leap Year")
if n%400==0:
print("Leap year")
else:
print("Not Leap year")
|
class Session(object):
def __init__(self):
self.start = None
self.end = None
self.scenarios = {}
def add_run(self, run):
if run.details_loaded and run.score == 0:
# When a run is exited early via the "Restart Challenge" or
# "Cancel Challenge" menu item i... |
def binarySearch(list, item):
""" Verifica se um item está em um lista ordenada """
first = 0
last = len(list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if list[midpoint] == item:
found = True
else:
if item ... |
# 1493. Longest Subarray of 1's After Deleting One Element
# User Accepted:3497
# User Tried:3867
# Total Accepted:3616
# Total Submissions:6849
# Difficulty:Medium
# Given a binary array nums, you should delete one element from it.
# Return the size of the longest non-empty subarray containing only 1's in the resultin... |
def solve():
s = input()
cpos = s.find('C')
if cpos < 0:
print('No')
return
fpos = s[cpos:].find('F')
if fpos >= 0:
print('Yes')
else:
print('No')
solve()
|
args_get = {
'filter_all': {'type': int, 'choices': [0, 1]}
}
args_put_or_post = {
'user_id': {'type': int},
'username': {'type': str}
}
|
#weights dictionary having all weights of any layer as a value..preloaded
#relu is a function return max(input_data,0).means relu is an activation function..
def predict_with_network(input_data):
# Calculate node 0 in the first hidden layer
node_0_0_input = (input_data * weights["node_0_0"]).sum()
node_0_0_... |
#!/usr/bin/env python3
class Shape(object):
LIZT = []
def __init__(self):
Shape.LIZT.append(self)
def __str__(self):
return('SHAPE:from __str__: {}'.format(Shape.LIZT))
def __repr__(self):
return('SHAPE: from __repr__: {} {}'.format(self,Shape.LIZT))
class Circle(Shape):
... |
# -*- coding: utf-8 -*-
"""
979. Distribute Coins in Binary Tree
Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.
In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or fro... |
def clean_line(line):
instruction, argument = line.strip().split()
return instruction, int(argument)
with open('in') as f:
data = list(map(clean_line, f.readlines()))
def exec_code(program):
acc = 0
index = 0
executed = [False] * len(data)
while not executed[index]:
executed[in... |
inputs = [1.2, 5.1, 2.1]
weights = [3.1, 2.1, 8.7]
bias = 3
output = inputs[0]*weights[0] + inputs[1]*weights[1] + inputs[2]*weights[2] + bias
print(output) |
"""Support module for looking up drivers by name
The driver model (see ``docs/driver-model.rst``) requires us to be able
to resolve driver names to classes; this module provides support for
building and querying lookup tables for this.
Any class which wishes to be exposed via this interface should:
1. Inherit, direc... |
# Function to find and list all substrings in a string
def find_all(string, x):
index_list = []
start = 0
while True:
index = string.find(x, start)
if index != -1:
index_list.append(index)
start = index+1
else:
if start==0:
return -... |
# -*- coding: utf-8 -*-
USER_AGENT_LIST = [ \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", \
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", \
"Mozilla/5.0 (Windows NT 6.1; WO... |
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
class GeneratorFunctions:
def __init__(self):
print('no this i... |
# coding: utf-8
debit_occurrences = {
'101': 'Cheque Compensado',
'102': 'Encargos',
'103': 'Estornos',
'104': 'Lançamento Avisado',
'105': 'Tarifas',
'106': 'Aplicação',
'107': 'Empréstimo / Financiamento',
'108': 'Câmbio',
'109': 'CPMF',
'110': 'IOF',
'111': 'Imposto de Re... |
__author__ = 'Harsh Gupta'
__email__ = 'working@example.com'
__version__ = '0.0.1'
__version_info__ = tuple(__version__.split('.'))
|
score = input("Enter score:")
s = float(score)
if s < 0.6:
print("F")
elif s >= 0.6:
if s < 0.7:
print("E")
elif s >= 0.7:
if s < 0.8:
print("C")
elif s >= 0.8:
if s < 0.9:
print("B")
elif s >= 0.9:
print("A")
|
t = int(input())
answer = []
ans = []
counter = 0
for a in range(t):
counter = 0
n = int(input())
ans = [0 for d in range(n)]
line = list(input())
for b in range(len(line)-n+1):
current = [line[c] for c in range(b, b+n)]
#print(current)
check = int(ans[counter])|int(current[c... |
"""
Dada uma String "str", retorne uma nova com um "not" no início, exceto se ela já
começar com, nesse caso retorne a string sem alteração.
"""
def not_string(str):
if str.startswith('not'):
return str
else:
return 'not ' + str
# OUTRO JEITO DE SE FAZER
def not_string_2(str):
if len(str... |
numbers = [5, 6, 7, 12, 29]
med = 0
out = None
if(len(numbers) != 0):
for n in numbers:
med += n
out = med/len(numbers) |
# Define a class Employee having members id, name, department, salary. Create a subclass called manager with member bonus. Define methods accept and display in both the classes. Create n objects of the manager class and display the details of the manager having the maximum total salary (salary+bonus).
class Employee:... |
class Transform(object,IComparable[Transform],IEquatable[Transform]):
""" Transform(diagonalValue: float) """
@staticmethod
def ChangeBasis(*__args):
"""
ChangeBasis(initialBasisX: Vector3d,initialBasisY: Vector3d,initialBasisZ: Vector3d,finalBasisX: Vector3d,finalBasisY: Vector3d,finalBasisZ: Vector3d) -> ... |
class NodoAVL:
def __init__(self, element):
self.__element = element
self.__right = None
self.__left = None
self.__factor = 1
def set_left(self, left):
self.__left = left
def get_left(self):
return self.__left
def set_right(self, right):
self.__... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
__license__ = "BSD"
__credits__ = ["Stephone White"]
__version__ = "0.1.0"
__status__ = "development"
def main():
"""Entry point for the application script"""
print("Call your main application code here")
|
#
# PySNMP MIB module SUNSTORAGEAGENT-NOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUNSTORAGEAGENT-NOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:04:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
INSTALLED_APPS += [
'userservice',
'rc_django'
]
MIDDLEWARE += [
'userservice.user.UserServiceMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors... |
#data transformer boolean
# 非0數字 回傳 True
print(bool(True)) # True
print(bool(1)) # True
# 0值回傳 False
print(bool(0)) # False |
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
count = 0
isMajority = False
whatIsMajority = 0
for index in xrange(0,len(num)):
if not isMajority:
whatIsMajority = num[index]
... |
n=input()
k=input().strip()
count=0
for i in range(len(n)):
if(n[i]==k):
count=count+1
print(count)
|
def fib(n):
"""
Returns a list of all the even terms in the Fibonacci sequence that are less than n.
"""
ls = []
a, b = 0, 1
while b < n:
if b % 2 == 0:
ls.append(b)
a, b = b, a+b
return ls
if __name__ == '__main__':
n = int(input("Enter max numb... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@project:Explaining-and-Harnessing-Adversarial-Examples
@author: Kevin Leung
@file:model.py
@interpreter: Python3.6
@ide:PyCharm
@time:2019-02-20 16:57:12
"""
|
# -*- encoding:utf-8 -*-
"""
Author: Yijie.Wu
Email: 1694517106@qq.com
Date: 2020/5/16 15:17
"""
|
# import pandas as pd
# results=[]
# draft1=pd.read_table('sample.tsv')
# print(draft1)
# for row in draft1:
# results.append(row)
# print(results)
l = 'https://github.com/msirrele/dc-metro-proxy'
a=l.split('/')
print(a[-1])
|
"""
[2017-06-29] Challenge #321 [Intermediate] Affine Cipher Solver
https://www.reddit.com/r/dailyprogrammer/comments/6k123x/20170629_challenge_321_intermediate_affine_cipher/
#Description
You are to output what you think is the solution to a given [Affine
Cipher](https://en.wikipedia.org/wiki/Affine_cipher). In shor... |
class Vertex(object):
def __init__(self, key):
self.id = key
self.connectedTo = {}
def addNeighbor(self, nbr, w):
self.connectedTo[nbr] = w
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self, nbr):
... |
#!/usr/bin/env python3
"""
Module Docstring
"""
__author__ = "Your Name"
__version__ = "0.1.0"
__license__ = "MIT"
def read_profile(infile):
"""
Reads contents of an airfoil definition file such as the
ones found here:
http://m-selig.ae.illinois.edu/ads/coord_database.html
Many have an airfo... |
n = int(input())
pos = []
for i in range(n):
x, y = map(int, input().split())
pos.append((x, y))
pos.sort(key=lambda x:(x[0], x[1]))
for p in pos:
print(p[0], p[1]) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
owner_users = {'email': 'prozorroytenderowner@gmail.com',
'password': '123456'}
provider_users = {'prozorroyprovider1@gmail.com': '123456',
'prozorroyprovider2@gmail.com': '123456',
'uaceseller1@mail.ru': 'andriy85',
... |
def binary_search(l,x,start,end):
if start==end:
if l[start]==x:
return start
else:
return -1
else:
mid=int((start+end)/2)
if l[mid]==x:
return mid
elif l[mid]>x:
return binary_search(l,x,start,mid-1)
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.