content stringlengths 7 1.05M |
|---|
def encode(valeur,base):
""" int*int -->String
hyp valeur >=0
hypothèse : base maxi = 16
"""
chaine=""
if valeur>255 or valeur<0 :
return ""
for n in range (1,9) :
calcul = valeur % base
if (calcul)>9:
if calcul==10:
bit='A'
if... |
class hash_list():
def __init__(self):
self.hash_list = {}
def add(self, *args):
if args:
for item in args:
key = self._key(item)
if self.hash_list.get(key):
self.hash_list[key].append(item)
else:
... |
class Parent():
def __init__(self, last_name, eye_color):
print("Parent Constructor Called.")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last name - " + self.last_name)
print("Eye color - " + self.eye_color)
class Chi... |
"""
file_name = input('请输入需要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
print(each_line)
f.close()
"""
print('----------------------------------------------')
my_list = ['小甲鱼是帅哥']
# print(len(my_list))
assert len(my_list) > 0 # False 抛出异常
"""
try-except语句
try:
检测范围
except Exception[as... |
# Mumbling
def accum(s):
counter = 0
answer = ''
for char in s:
counter += 1
answer += char.upper()
for i in range(counter - 1):
answer += char.lower()
if counter < len(s):
answer += '-'
return answer
# Alternative solution
def... |
#!/usr/bin/python3
# 数组构成的线性表,参考 Java 中的 ArrayList
class ArrayList(object):
"""数组构成的线性表,参考 Java 中的 ArrayList"""
__size = 0
def __init__(self, initial_capacity=10):
if initial_capacity < 0:
raise Exception("Illegal capacity") # 抛出异常
self.__max_size = initial_capacity # 最大数据容... |
#!/usr/bin/env python3
#
# author : Michael Brockus.
# contact: <mailto:michaelbrockus@gmail.com>
# license: Apache 2.0 :http://www.apache.org/licenses/LICENSE-2.0
#
# copyright 2020 The Meson-UI development team
#
class MesonUiQueue:
def __init__(self):
self.items = []
def is_empty(self):
... |
CALLING = 0
WAITING = 1
IN_VEHICLE = 2
ARRIVED = 3
DISAPPEARED = 4 |
def print_progress(iteration, total, start_time, print_every=1e-2):
progress = (iteration + 1) / total
if iteration == total - 1:
print("Completed in {}s.\n".format(int(time() - start_time)))
elif (iteration + 1) % max(1, int(total * print_every / 100)) == 0:
print("{:.2f}% completed. Time ... |
def solve(heights):
temp = heights[0]
for height in heights[1:]:
if height > temp:
temp = height
else:
print(temp)
return
print(temp)
return
t = int(input())
heights = list(map(int, input().split()))
solve(heights)
|
commands = []
with open('./input', encoding='utf8') as file:
for line in file.readlines():
cmd, cube = line.strip().split(" ")
ranges = [
[int(val)+50 for val in dimension[2:].split('..')]
for dimension in cube.split(',')
]
commands.append({'cmd': cmd, 'range... |
class MorphSerializable:
def __init__(self, properties_to_serialize, property_dict):
self.property_dict = property_dict
self.properties_to_serialize = properties_to_serialize
|
#
# PySNMP MIB module F5-BIGIP-GLOBAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F5-BIGIP-GLOBAL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
# The MIT License (MIT)
# -Copyright (c) 2017 Radomir Dopieralski and Adafruit Industries
# -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 th... |
# Desenvolva um programa que possa gerar a tabela de jogos do campeonato
# brasileiro para 4 times (times jogam em casa e na casa do adversário).
# Times: Flamengo, São Paulo, Fluminense, Palmeiras.
# Saída de dados: Flamengo x São Paulo
# Flamengo x Fluminense
# Flamengo x Palmeiras
# São Paulo x Flamengo
for time1 i... |
# https://www.spoj.com/problems/AMR11E/
#
# Author: Bedir Tapkan
def sieve_of_eratosthenes_modified(n):
"""
Sieve of Eratosthenes implementation
with a tweak:
Instead of true-false calculate the number
of prime numbers to generate the composites.
"""
primes = [0] * (n + 1)
prime... |
'''
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
19. Remove Nth Node From End of List
Medium
7287
370
Add to List
Share
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:... |
"""Top-level package for deepboard."""
__author__ = """Federico Domeniconi"""
__email__ = 'federicodomeniconi@gmail.com'
__version__ = '0.1.0'
|
# -*- coding: utf-8 -*-
table = [
{
'id': 500,
'posizione_lat': '45.467269',
'posizione_long': '9.214908',
},
{
'id': 501,
'posizione_lat': '45.481383',
'posizione_long': '9.169981',
}
]
|
A, B = input().split()
a = sum(map(int, A))
b = sum(map(int, B))
print(a if a > b else b)
|
'''
MBEANN settings for solving the OpenAI Gym problem.
'''
class SettingsEA:
# --- Evolutionary algorithm settings. --- #
popSize = 500
maxGeneration = 500 # 0 to (max_generation - 1)
isMaximizingFit = True
eliteSize = 0
tournamentSize = 20
tournamentBestN = 1 # Select best N individua... |
#
# @lc app=leetcode id=57 lang=python3
#
# [57] Insert Interval
#
# @lc code=start
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
start = newInterval[0]
en... |
TAB = " "
NEWLINE = "\n"
def generate_converter(bits_precision, colors_list_hex, entity_name="sprite_converter"):
l = []
# Entity declaration
l += ["library IEEE;"]
l += ["use IEEE.std_logic_1164.all;"]
l += ["use IEEE.numeric_std.all;"]
l += [""]
l += ["entity " + entity_name + " is"]... |
# Default logging settings for DeepRank.
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'brief': {
'format': '%(message)s',
},
'precise': {
'format': '%(levelname)s: %(message)s',
},
},
'filters': {
... |
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
... |
# Databricks notebook source
print("hello world")
# COMMAND ----------
print("hello world2")
|
# Problem Statement
# The previous version of Quicksort was easy to understand, but it was not optimal. It required copying the numbers into other arrays, which takes up space and time. To make things faster, one can create an "in-place" version of Quicksort, where the numbers are all sorted within the array itself.
... |
# WARNING: Changing line numbers of code in this file will break collection tests that use tracing to check paths and line numbers.
# Also, do not import division from __future__ as this will break detection of __future__ inheritance on Python 2.
def question():
return 3 / 2
|
CYBERCRIME_RESPONSE_MOCK = {
'success': True,
'message': 'Malicious: Keitaro'
}
CYBERCRIME_ERROR_RESPONSE_MOCK = {
'error': 'Server unavailable'
}
EXPECTED_DELIBERATE_RESPONSE = {
'data': {
'verdicts': {
'count': 1,
'docs': [
{
'disp... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019-2020 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Circulation configuration callbacks."""
def circulation_cds_extension_max_count(loan):
"""Return a default e... |
num = input()
prime = 0
non_prime = 0
is_prime = True
while num != "stop":
num = int(num)
if num < 0:
print(f"Number is negative.")
num = input()
continue
for i in range(2, (num+1)//2):
if num % i == 0:
non_prime += num
is_prime = False
br... |
class Convert:
"""
Conversion utility functions
"""
@staticmethod
def to_boolean(value: object) -> bool:
"""
Convert the given value into a Boolean, if given a convertible representation
Valid representations include:
- boolean value
- string representation l... |
def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.0,
lr=lambda f: 3e-4 * f,
cliprange=0.2,
value_network='copy'
)
# Daniel: more accurately matches the PPO pape... |
#Faça um programa que pergunte quanto você ganha por hora e o numero de horas trabalhadas no mês.
#Calcule e mostre o total do seu salario referido do mês, sabendo que são descontados:
# 11% para o Imposto de Renda
# 8% para o INSS
# 5% para o sindicato
#Faça um programa que nos dê:
... |
#Q6. Given a string "I love Python programming language", extract the word "programming" (use slicing)
string= "I love Python programming language"
print(string[14:25]) |
# Copyright 2022 Google LLC
#
# 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, ... |
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given a non-empty string containing only digits, determine the total number of ways to decode it.
# Example 1:
# Input: "12"
# Output: 2
# Explanation: It could be decoded as "AB" ... |
#
# PySNMP MIB module ASCEND-MIBT1NET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBT1NET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:12:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def vulkan_memory_allocator_repository():
maybe(
http_archive,
name = "vulkan-memory-allocator",
urls = [
"https://github.com/GPUOpen-LibrariesAndS... |
# class Player():
# def __init__(self, name, hp, job):
# self.__name = name # 前面加__就是私有属性,不会被实例直接修改
# self.hp = hp
# self.job = job
#
# def print_role(self):
# print('%s : %s %s' % (self.__name, self.hp, self.job))
#
# def updateName(self, newname):
# self.__name = ne... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/12 14:15
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : seq_packing.py
# @Software: PyCharm
# 序列封包,将多个值赋值个一个值,最后是创建了一个元组
vals = 10, 20, 99, 66
print(vals)
print(type(vals))
print(vals[1])
a_tuple = tuple(range(1, 10, 2))
... |
x = ["Python", "Java", "Typescript", "Rust"]
# COmprobar si un valor pertenece a esa variable / objeto
a = "python" in x # False
a = "Python" in x # True
a = "Typescrip" in x # False
a = "Typescript" in x # True
a = "python" not in x # True
a = "Python" not in x # False
a = "Typescrip" not in x # True
a = "Typescr... |
#
# PySNMP MIB module MY-FILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-FILE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:06:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
'''
This is code that will help a game master/dungeon master get the initiative and health of the players,
put them all in correct initiative order, then help you go through the turns until combat is over.
'''
def validate_num_input(user_input):
while True:
try:
num_input = int(input(user_in... |
expected_output = {
'ids': {
'100': {
'state': 'active',
'type': 'icmp-jitter',
'destination': '192.0.2.2',
'rtt_stats': '100',
'rtt_stats_msecs': 100,
'return_code': 'OK',
'last_run': '22:49:53 PST Tue May 3 2011'
}... |
def callvars_subcmd(analysis:str, args:list, outdir:str=None,env:str=None) -> None:
if 'help' in args or 'h' in args:
print("Help:")
print("bam --> gvcf")
print("==========================")
print("call-variants <sample-name> <input-files> [-r reference] ")
print("call-varia... |
sum = 0
num1, num2, temp = 1, 2, 1
while (num2 <= 4000000):
if(num2%2==0):
sum += num2
temp = num1
num1 = num2
num2 += temp
print(sum) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exercise 4: Divisors.
Create a program that asks the user for a number and then prints out a
list of all the divisors of that number. (If you don’t know what a
divisor is, it is a number that divides evenly into another number. For
example, 13 is a divisor of 26 becaus... |
# coding:utf-8
'''
@Copyright:LintCode
@Author: taoleetju
@Problem: http://www.lintcode.com/problem/construct-binary-tree-from-inorder-and-postorder-traversal
@Language: Python
@Datetime: 16-06-13 14:40
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
... |
def perm_check(checkSet, mainSet):
checkSet = set(checkSet)
mainSet = set(mainSet)
if checkSet.issubset(mainSet):
return True
else:
return False
def is_subset(checkSet, mainSet):
checkSet = set(checkSet)
mainSet = set(mainSet)
if checkSet.issubset(mainSet):
return ... |
def addition(num):
b=num+1
return b
|
def for_Zero():
""" Pattern of Number : '0' using for loop"""
for i in range(7):
for j in range(5):
if i in (0,6) and j not in(0,4) or j in(0,4) and i not in(0,6) or i+j==5:
print('*',end=' ')
else:
... |
def get_dict_from_list(dict_list, target_key_name, value):
"""
Find a dictionary in a list dictionaries that has a particular value for a key.
:param dict_list:
:param target_key_name:
:param value:
:param parent_key: if the key you are looking for is nested in a parent field.
:return:
"... |
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-10-05 01:28
# @Author : Fabrice LI
# @File : 900_closest_binary_search_tree_value.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a non-empty binary search tree and a target value,
# ... |
RED = 0xFF0000
MAROON = 0x800000
ORANGE = 0xFF8000
YELLOW = 0xFFFF00
OLIVE = 0x808000
GREEN = 0x008000
AQUA = 0x00FFFF
TEAL = 0x008080
BLUE = 0x0000FF
NAVY = 0x000080
PURPLE = 0x800080
PINK = 0xFF0080
WHITE = 0xFFFFFF
BLACK = 0x000000
|
# similar to partial application, but only with one level deeper
def curry_add(x):
def curry_add_inner(y):
def curry_add_inner_2(z):
return x + y + z
return curry_add_inner_2
return curry_add_inner
add_5 = curry_add(5)
add_5_and_6 = add_5(6)
print(add_5_and_6(7))
# or we can even... |
"""
Given an array of non-negative integers arr, you are initially positioned
at start index of the array. When you are at index i, you can jump to
i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
Examp... |
"""
Zip
- expects any no. of iterators with equal indeces
to combine it into a single object.
* Note * if iterators contains unequal length,
iteration stops at the smallest index
"""
names = ["rodel", "ryan"]
grades = [1, 2]
# combine
result = zip(names... |
def is_low_point(map: list[list[int]], x: int, y: int) -> bool:
m, n = len(map), len(map[0])
val = map[x][y]
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
x1, y1 = x + dx, y + dy
if x1 >= 0 and x1 < m and y1 >= 0 and y1 < n and val >= map[x1][y1]:
return False
return True
map = []
with open('... |
# -*- coding: utf-8 -*-
"""Top-level package for Cloud Formation Macro Toolkit."""
__author__ = """Giuseppe Chiesa"""
__email__ = 'mail@giuseppechiesa.it'
__version__ = '0.6.0'
|
#
# @lc app=leetcode id=207 lang=python3
#
# [207] Course Schedule
#
# @lc code=start
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = [[] for _ in range(numCourses)]
visit = [0]*numCourses
for x, y in prerequisites:
graph[x... |
# Sequential Digits
'''
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Inpu... |
class Callback():
callbacks = {}
def registerCallback(self, base, state):
print("registered %s for %s" % (state, base))
self.callbacks[state] = base
def runCallbacks(self):
for key,value in self.callbacks.items():
print("state=%s value=%s, type=%s" % (key, value, type(... |
a = 1; # Setting the variable a to 1
b = 2; # Setting the variable b to 2
print(a+b); # Using the arguments a and b added together using the print function.
|
lista = [i for i in range(0,101)]
lista = [i for i in range(0,101) if i%2 == 0]
tupla = tuple( (i for i in range(0,101) if i%2 == 0))
diccionario = {i:valor for i, valor in enumerate(lista) if i<10}
print(lista)
print()
print(tupla)
print()
print(diccionario)
|
# coding: utf-8
n = int(input())
d = {}
for i in range(n):
temp = input()
if temp in d.keys():
print(temp+str(d[temp]))
d[temp] += 1
else:
print('OK')
d[temp] = 1
|
def lis(a):
lis = [0] * len(a)
# lis[0] = a[0]
for i in range(0, len(a)):
max = -1
for j in range(0, i):
if a[i] > a[j]:
if max == -1 and max < lis[j] +1:
max = a[i]
if max == -1:
max = a[i]
lis[i] = max
return lis
if __name__ == '__main__':
A = [2, 3, 5, 4]
print(lis(A))
|
# Write an implementation of the Queue ADT using a Python list.
# Compare the performance of this implementation to the ImprovedQueue for a range of queue lengths.
class ListQueue:
def __init__(self):
self.list = []
def insert(self, cargo):
self.list.append(cargo)
def is_empty(self):
... |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
#print(new_class)
new_class.append('Peter Warden')
#print(new_class)
new_class.remove('Carla Gentry')
print(new_cla... |
print('='*30)
print('{:^30}'.format('BANCO'))
print('='*30)
valor=int(input('Que valor você quer sacar? R$'))
total=valor
ced5=50
totced5=0
while True:
if total>=ced5:
total-=ced5
totced5+=1
else:
if totced5>0:
print(f'Total de {totced5} cédulas de R$ {ced5}')
if ced5... |
"""
The send_email function is defined here to enable you to play with
code, but of course it doesn't send an actual email.
"""
def send_email(*a):
"""send an e-mail"""
print(*a)
ALERT_SYSTEM = 'console' # other value can be 'email'
ERROR_SEVERITY = 'critical' # other values: 'medium' or 'low'
ERROR_MESSA... |
# add some debug printouts
debug = False
# dead code elimination
dce = False
# assume there will be no backwards
forward_only = True
# assume input tensors are dynamic
dynamic_shapes = True
# assume weight tensors are fixed size
static_weight_shapes = True
# enable some approximation algorithms
approximations = Fa... |
def insertion_sort(l):
"""
Insertion Sort Implementation.
Time O(n^2) run.
O(1) space complexity.
:param l: List
:return: None, orders in place.
"""
# finds the next item to insert
for i in range(1, len(l)):
if l[i] < l[i - 1]:
item = l[i]
# moves the... |
"""
DICIONÁRIO
"""
d1 = {'chave1':'item 1', 'chave2': 'item2'}
d2 = dict(chave1='item 1', chave2 ='item 2') #outra maneira de criar dicionário
d2['nova_chave'] = 'novo item' # adicionando novo item no dicionário
d1['chave'] = 'item'
#para saber se uma key está no dicionário, caso não exista a chave, imprimi valor N... |
# Copyright (C) 2019-2021 Data Ductus AB
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
... |
# Find the sum pair who is divisible by a certain integer in an arry
# You modulo from the start and compute the complement and
# store the modulo that way when u see a complement that matches
# the modulo hashmap you add to the counter
# O(n)
# O(k)
def divisibleSumPairs(n, k, arr):
hMap = dict()
counter =... |
"""Define version constants."""
__version__ = '0.0.1'
__version_info__ = tuple(int(i) for i in __version__.split('.'))
|
s = input()
k = int(input())
subst = list(s)
for i in range(2, k + 1):
for j in range(len(s) - i + 1):
subst.append(s[j:j + i])
subst = sorted(list(set(subst)))
print(subst[k - 1]) |
"""
@author: azubiolo (alexis.zubiolo@gmail.com)
"""
# Factorial of a given integer.
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
# Maximum of a list of non-negative integers. Please do not use the built-in function 'max'.
def maximum_value(l):
max_value = 0
for x in l:
if x... |
#
# PySNMP MIB module ASCEND-MIBMGW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBMGW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:27:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# This object is for creating a daily report, indicating the progress of the
# currently running Time Lapse. The file structure is plain text with some
# slight formatting.
# Every section/seperator will be represented by '-' characters on both sides
# of the given text.
# Every alert will be represented similarly to t... |
# python_version >= '3.5'
#: Okay
async def test():
good = 1
#: N806
async def f():
async with expr as ASYNC_VAR:
pass
|
"""
AccessToken 获取常量定义
"""
# 请求中携带的参数键
GRANT_TYPE = "grant_type"
APPID = "appid"
SECRET = "secret"
TYPE = "client_credential"
# 响应中携带的参数键
TOKEN = "access_token"
EXPIRES = "expires_in"
# 错误响应中的键
CODE = "errcode"
MESSAGE = "errmsg"
|
"""
Программа получает на вход последовательность целых неотрицательных чисел, каждое число записано в отдельной
строке. Последовательность завершается числом 0, при считывании которого программа должна закончить свою работу и
вывести количество членов последовательности (не считая завершающего числа 0).
Числа, следую... |
# -*- coding: utf-8 -*-
"""This module defines all the constants used by pytwis.py."""
REDIS_SOCKET_CONNECT_TIMEOUT = 60
PASSWORD_HASH_METHOD = 'pbkdf2:sha512'
NEXT_USER_ID_KEY = 'next_user_id'
USERS_KEY = 'users'
USER_PROFILE_KEY_FORMAT = 'user:{}'
USERNAME_KEY = 'username'
PASSWORD_HASH_KEY = 'password_hash'
AUTH... |
# birth_year=input("please enter your bith year: ")
curr=2021
# age=curr-int(birth_year)
# print("you are "+ str(age)+" years old)")
# f_name=input("enter your name: ")
# l_name=input("enter your last name: ")
# print(f"hello {l_name} {f_name} you are {age} years old)")
# user_data=input(" Enter Ur name , last na... |
# -*- coding: utf-8 -*-
class HostsNotFound(OSError):
pass
class InvalidFormat(ValueError):
pass
|
def printall(*args, **kwargs):
# Handle the args values
print('args:')
for arg in args:
print(arg)
print('-' * 20)
# Handle the key value pairs in kwargs
print('kwargs:')
for arg in kwargs.values():
print(arg)
printall(1, 2, 3, a="John", b="Hunt")
|
def Mmul(a, b): # 行列の積
# [m×n型][n×p型]
m = len(a)
n = len(a[0])
if len(b) != n:
raise ValueError('列と行の数が一致しません')
p = len(b[0])
ans = [[0]*p for _ in range(m)]
for i in range(m):
for j in range(p):
for k in range(n):
ans[i][j] += a[i][k]*b[k][j] % M... |
"""
We distribute some number of candies, to a row of n = num_people people in
the following way:
We then give 1 candy to the first person, 2 candies to the second person,
and so on until we give n candies to the last person.
Then, we go back to the start of the row, giving n + 1 candies to the fi... |
P,K=map(int,input().split())
L=[i for i in range(K)]
k=[]
L[0]=-1
L[1]=-1
for i in range(K):
if L[i] == i:
k.append(i)
for j in range(i+i,K,i):
L[j]=-1
for i in k:
if P%i == 0:
print("BAD",i)
break
else:
print("GOOD")
|
# Photon/energy
g_eV_per_Hartree = 27.211396641308
g_omega_IR = 0.0569614*g_eV_per_Hartree
# Plot parameters
g_linewidth = 2
g_fontsize = 20
g_colors_list = ['royalblue', 'crimson', 'lawngreen', 'violet', 'orange', 'black', 'deepskyblue', 'pink', 'lightseagreen']
g_linestyles = ["solid",
"dotted",
... |
# work dir
root_workdir = 'workdir'
# seed
seed = 0
# 1. logging
logger = dict(
handlers=(
dict(type='StreamHandler', level='INFO'),
# dict(type='FileHandler', level='INFO'),
),
)
# 2. data
test_cfg = dict(
scales=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
bias=[0.5, 0.25, 0.0, -0.25, -0.5, -... |
a = int(input('Primeiro valor: '))
b = int(input('Segundo valor: '))
c = int(input('Terceiro valor: '))
menor = a
if b < a and b < c: menor = b
if c < a and c < b: menor = c
maior = a
if b > a and b > c: maior = b
if c > a and c > b: maior = c
print(f'O menor valor é: {menor}')
print(f'O maior valor é: {maior}') |
#!/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Reverses a user provided string. #
# Program Author : Happi ... |
# from OME
def get_headers_csv(file_dir):
f = open(file_dir)
header_str = ""
for line in f.readlines():
header_str = line
break
header = []
start_q = False
start_idx = 0
print("header_string: "+header_str)
for idx, ch in enumerate(header_str):
if ch == '"' and ... |
class Dafsm(object):
# Constructor
def __init__(self, name):
self.name = name
def trigger(self, fname, cntx):
raise NotImplementedError()
def call(self, fname, cntx):
raise NotImplementedError()
def queuecall(self, cntx):
raise NotImplementedError()
def switc... |
RED = "0;31"
GREEN = "0;32"
YELLOW = "0;33"
BLUE = "0;34"
GRAY = "0;37"
def _ansicolorize(text, color_code):
return "\033[{}m{}\033[0m".format(color_code, text)
def color_print(text, color_code):
if color_code:
print(_ansicolorize(text, color_code))
else:
print(text)
|
# [剑指 Offer 第 2 版第 51 题] “数组中的逆序对”做题记录
# 第 51 题:数组中的逆序对
# 传送门:数组中的逆序对,牛客网 online judge 地址。
# 在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
# 输入一个数组,求出这个数组中的逆序对的总数。
# 样例:
# 输入:[1,2,3,4,5,6,0]
# 输出:6
def mergeCount(nums,l,mid,r,temp):
for i in range(l,r+1):
temp[i] = nums[i]
i,j,res = l,mid+... |
def in_array(a1, a2):
return sorted({sub for sub in a1 if any(sub in s for s in a2)})
# return sorted({sub for sub in a1 if 1})
# any 传入空可迭代对象时返回False,当可迭代对象中有任意一个不为False,则返回True
# all 传入空可迭代对象时返回True,当可迭代对象中有任意一个不为True,则返回False
# if 真有返回,if假无返回, 真假由 ()里内容决定,对a1里的每个sub反回真,假
# 不知道使用{}的原因,但是换掉会报错 ['duplic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.